def hash_file(path, base=64, block_size=65536): hash_maker = hashlib.sha256() with open(path, 'rb') as file: block = file.read(block_size) while len(block) > 0: hash_maker.update(block) block = file.read(block_size) if base == 64: return base64.b64encode(hash_maker.digest()).decode() elif base == 32: return base32hex.b32encode(hash_maker.digest()).replace('=', '-') else: raise ValueError(f'base{base} is unknown!')
def __str__(self): salt_str = '-' if len(self.salt) > 0: salt_str = self.salt[1:].hex().upper() owner_types_str = "" if self.owner_types != 'none': owner_types_str = self.owner_types return '{} IN NSEC3 {} {} {} {} {} {}'.format( self.fqdn, self.hash_algorithm, self.flags, self.iterations, salt_str, base32hex.b32encode(self.next_hash[1:]).upper().strip('='), owner_types_str)
def hash_object(obj, base=64): """ :type obj: Obj :type base: int :rtype str """ if hasattr(obj, '__hash64__') and base == 64: return obj.__hash64__() elif hasattr(obj, '__hash32__') and base == 32: return obj.__hash32__() hash_maker = hashlib.sha256() hash_maker.update(repr(make_hashable(obj)).encode()) if base == 64: return base64.b64encode(hash_maker.digest()).decode() elif base == 32: return base32hex.b32encode(hash_maker.digest()).replace('=', '-') else: raise ValueError(f'base{base} is unknown!')
def string(self): # type: () -> str byte_value = self.bytes() return base32hex.b32encode(byte_value).lower()[:trimLen]
def make_hash_sha256(obj): hasher = hashlib.sha256() hasher.update(repr(obj).encode()) return base32hex.b32encode(hasher.digest()).replace('=', '-')
def test_array_to_string(self): x = base32hex.b32encode([0x4d, 0x88, 0xe1, 0x5b, 0x60, 0xf4, 0x86, 0xe4, 0x28, 0x41, 0x2d, 0xc9]) self.assertEqual('9m4e2mr0ui3e8a215n4g===='.upper(), x)
def test_string_encode(self): x = base32hex.b32encode('base32hex_encoder') self.assertEqual('C9GN6P9J69K6AU2VCLN66RR4CLP0===='.upper(), x)