Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

why do I get different hash value everytime I call hexdigest() in hashlib?

Tags:

python

hash

I want to have a unique hash for the same string in python. I use following code for getting a hash :

import hashlib
mysha1 = hashlib.sha1()
mysha1.update("my_url")
print mysha1.hexdigest()
mysha1.update("my_url")
print mysha1.hexdigest() # which is generating a different hash

is there something I missed here?

like image 572
Seyed Vahid Hashemi Avatar asked Dec 10 '22 16:12

Seyed Vahid Hashemi


2 Answers

the update() function feeds strings to be concatenated.

https://docs.python.org/2/library/hashlib.html

>>> import hashlib
>>> mysha1 = hashlib.sha1()
>>> mysha1.update("my_url")
>>> print mysha1.hexdigest()
ebde90b9f0c047ff9f86bec3b71afe5d00594030
>>> mysha1.update("my_url")
>>> print mysha1.hexdigest()
efa6ba48cedd0da886a553ad0e7c131ec79b452e
>>> 
>>> 
>>> sha = hashlib.sha1()
>>> sha.update("my_urlmy_url")
>>> print sha.hexdigest()
efa6ba48cedd0da886a553ad0e7c131ec79b452e
like image 139
Matthew Darnell Avatar answered Jun 05 '23 05:06

Matthew Darnell


When you call update("my_url"), you're concatenating that string to the hash input.

You can now feed this object with arbitrary strings using the update() method. At any point you can ask it for the digest of the concatenation of the strings fed to it so far using the digest() or hexdigest() methods.

You need to make a new sha1 object every time you want a new hash.

like image 23
Blorgbeard Avatar answered Jun 05 '23 06:06

Blorgbeard