Compare the result with hexdigest () with the string

I have a generated MD5 hash that I would like to compare with another MD5 hash from the string. The statement below is false, although they look the same when you print them and should be true.

hashlib.md5("foo").hexdigest() == "acbd18db4cc2f85cedef654fccc4a4d8"

Google told me that I should encode the result from hexdigest(), since it does not return a string. However, the code below does not work.

hashlib.md5("foo").hexdigest().encode("utf-8") == "foo".encode("utf-8")
+3
source share
3 answers

Python 2.7, .hexdigest () returns the string str

>>> hashlib.md5("foo").hexdigest() == "acbd18db4cc2f85cedef654fccc4a4d8"
True
>>> type(hashlib.md5("foo").hexdigest())
<type 'str'>

Python 3.1

.md5 () does not accept unicode (which "foo" is), so it must be encoded in a byte stream.

>>> hashlib.md5("foo").hexdigest()
Traceback (most recent call last):
  File "<pyshell#1>", line 1, in <module>
    hashlib.md5("foo").hexdigest()
TypeError: Unicode-objects must be encoded before hashing

>>> hashlib.md5("foo".encode("utf8")).hexdigest()
'acbd18db4cc2f85cedef654fccc4a4d8'

>>> hashlib.md5("foo".encode("utf8")).hexdigest() == 'acbd18db4cc2f85cedef654fccc4a4d8'
True
+9
source

hexdigestreturns a string . Your first statement returns Truein python-2.x.

In python-3.x you will need to encode the function argument md5, in this case equality is also equal True. Without coding, it raises TypeError.

+2
source

Source: https://habr.com/ru/post/1761898/


All Articles