我有一个生成的MD5-hash,我想将其与字符串中的另一个MD5-hash进行比较。即使在打印时它们看起来相同,也应为true,但下面的语句为false。
hashlib.md5("foo").hexdigest() == "acbd18db4cc2f85cedef654fccc4a4d8"
Google告诉我,我应该对
hexdigest()
的结果进行编码,因为它不返回字符串。但是,下面的代码似乎也不起作用。hashlib.md5("foo").hexdigest().encode("utf-8") == "foo".encode("utf-8")
最佳答案
Python 2.7,.hexdigest()确实返回了str
>>> hashlib.md5("foo").hexdigest() == "acbd18db4cc2f85cedef654fccc4a4d8"
True
>>> type(hashlib.md5("foo").hexdigest())
<type 'str'>
Python 3.1
.md5()不采用unicode(“foo”是unicode),因此需要将其编码为字节流。
>>> 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
关于python - 将hexdigest()的结果与字符串进行比较,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3583265/