My program calculated only sha256 file hash and I decided to expand the number of possible algorithms. So I started to use getattr()
instead direct call. And the hashes have changed.
It took me a while to figure out where the problem was, and here's simple example with string (differences are in ()
):
>>> import hashlib
>>> text = 'this is nonsence'.encode()
# unique original
>>> hash1 = hashlib.sha256()
>>> hash1.update(text)
>>> print(hash1.hexdigest())
ea85e601f8e91dbdeeb46b507ff108152575c816089c2d0489313b42461aa502
# pathetic parody
>>> hash2 = getattr(hashlib,'sha256')
>>> hash2().update(text)
>>> print(hash2().hexdigest())
e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855
# solution
>>> hash3 = getattr(hashlib,'sha256')()
>>> hash3.update(text)
>>> print(hash3.hexdigest())
ea85e601f8e91dbdeeb46b507ff108152575c816089c2d0489313b42461aa502
Can someone please explain me why hash1
not equal hash2()
and equal hash3
?
Did I miss smth? Because for me they are looking the same:
>>> print(hash1)
<sha256 HASH object @ 0x0000027D76700F50>
>>> print(hash2())
<sha256 HASH object @ 0x0000027D76FD7470>
>>> print(hash3)
<sha256 HASH object @ 0x0000027D76D92BF0>
>>> print(type(hash1))
<class '_hashlib.HASH'>
>>>print(type(hash2()))
<class '_hashlib.HASH'>
>>>print(type(hash3))
<class '_hashlib.HASH'>