Package backend :: Package common :: Module checksum
[hide private]
[frames] | no frames]

Source Code for Module backend.common.checksum

 1  # 
 2  # Copyright (c) 2009--2016 Red Hat, Inc. 
 3  # 
 4  # This software is licensed to you under the GNU General Public License, 
 5  # version 2 (GPLv2). There is NO WARRANTY for this software, express or 
 6  # implied, including the implied warranties of MERCHANTABILITY or FITNESS 
 7  # FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2 
 8  # along with this software; if not, see 
 9  # http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt. 
10  # 
11  # Red Hat trademarks are not licensed under GPLv2. No permission is 
12  # granted to use or replicate Red Hat trademarks that are incorporated 
13  # in this software or its documentation. 
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 
29 30 - class hashlib(object):
31 32 @staticmethod
33 - def new(checksum):
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
43 -def getHashlibInstance(hash_type, used_for_security):
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 # python's md5 lib sucks 58 # there's no way to directly import a file. 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 # Rewind it 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 # cleanup time 83 if file_obj is not None: 84 file_obj.seek(0, 0) 85 else: 86 f.close() 87 return m.hexdigest()
88
89 90 -def getStringChecksum(hashtype, s):
91 """ compute checksum of an arbitrary string """ 92 h = getHashlibInstance(hashtype, False) 93 h.update(s) 94 return h.hexdigest()
95