1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16 import os
17
18 try:
19 import hashlib
20 import inspect
21
22 hashlib_has_usedforsecurity = 'usedforsecurity' in inspect.getargspec(hashlib.new)[0]
23 except ImportError:
24 import md5
25 import sha
26 from Crypto.Hash import SHA256 as sha256
27
28 hashlib_has_usedforsecurity = False
31
32 @staticmethod
34 if checksum == 'md5':
35 return md5.new()
36 elif checksum == 'sha1':
37 return sha.new()
38 elif checksum == 'sha256':
39 return sha256.new()
40 else:
41 raise ValueError("Incompatible checksum type")
42
44 """Get an instance of a hashlib object.
45 """
46 if hashlib_has_usedforsecurity:
47 return hashlib.new(hash_type, usedforsecurity=used_for_security)
48 else:
49 return hashlib.new(hash_type)
50
51
52 -def getFileChecksum(hashtype, filename=None, fd=None, file_obj=None, buffer_size=None, used_for_security=False):
53 """ Compute a file's checksum
54 Used by rotateFile()
55 """
56
57
58
59 if buffer_size is None:
60 buffer_size = 65536
61
62 if hashtype == 'sha':
63 hashtype = 'sha1'
64
65 if filename is None and fd is None and file_obj is None:
66 raise ValueError("no file specified")
67 if file_obj:
68 f = file_obj
69 elif fd is not None:
70 f = os.fdopen(os.dup(fd), "rb")
71 else:
72 f = open(filename, "rb")
73
74 f.seek(0, 0)
75 m = getHashlibInstance(hashtype, used_for_security)
76 while 1:
77 buf = f.read(buffer_size)
78 if not buf:
79 break
80 m.update(buf)
81
82
83 if file_obj is not None:
84 file_obj.seek(0, 0)
85 else:
86 f.close()
87 return m.hexdigest()
88
91 """ compute checksum of an arbitrary string """
92 h = getHashlibInstance(hashtype, False)
93 h.update(s)
94 return h.hexdigest()
95