将hexdigest()的结果与字符串进行比较

8 投票
3 回答
38038 浏览
提问于 2025-04-16 03:23

我有一个生成的MD5哈希值,我想把它和另一个字符串生成的MD5哈希值进行比较。下面的代码虽然看起来一样,但比较的结果却是假的,这让我很困惑。

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

我在网上查到,应该对hexdigest()的结果进行编码,因为它返回的不是字符串。不过,下面的代码似乎也没有解决这个问题。

hashlib.md5("foo").hexdigest().encode("utf-8") == "foo".encode("utf-8")

3 个回答

2

hexdigest 会返回一个字符串。在 Python 2.x 中,你的第一个语句会返回 True

在 Python 3.x 中,你需要对传给 md5 函数的参数进行编码,这样的话,结果也是 True。如果不编码,就会出现 TypeError 的错误。

5

用==来比较哈希值可能会存在安全隐患。

https://groups.google.com/forum/?fromgroups=#!topic/keyczar-discuss/VXHsoJSLKhM

攻击者可能会利用时间差异,快速尝试不同的值,从而找到一个能通过相等性测试的值。

15

在Python 2.7中,.hexdigest()会返回一个字符串。

>>> 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

撰写回答