Compare result from hexdigest() to a string

I've got a generated MD5-hash, which I would like to compare to another MD5-hash from a string. The statement below is false, even though 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 doesn't return a string. However, the code below doesn't seem to work either.

hashlib.md5("foo").hexdigest().encode("utf-8") == "foo".encode("utf-8")
6
задан SilentGhost 27 August 2010 в 10:33
поделиться

2 ответа

Python 2.7, .hexdigest() возвращает строку str

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

Python 3.1

.md5() не принимает юникод (которым является «foo»), поэтому его необходимо кодировать в поток байтов. .

>>> 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
12
ответ дан 8 December 2019 в 12:17
поделиться

hexdigest возвращает строку . Ваш первый оператор возвращает True в python-2.x.

В python-3.x вам нужно будет закодировать аргумент в функцию md5, в этом случае равенство также будет True. Без кодирования вызывает TypeError.

2
ответ дан 8 December 2019 в 12:17
поделиться
Другие вопросы по тегам:

Похожие вопросы: