Python 将 hexdigest() 的结果与字符串进行比较
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3583265/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Compare result from hexdigest() to a string
提问by nip3o
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.
我有一个生成的 MD5-hash,我想将它与字符串中的另一个 MD5-hash 进行比较。下面的陈述是错误的,即使它们在您打印时看起来相同并且应该是正确的。
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.
谷歌告诉我,我应该对结果进行编码hexdigest(),因为它不返回字符串。但是,下面的代码似乎也不起作用。
hashlib.md5("foo").hexdigest().encode("utf-8") == "foo".encode("utf-8")
采纳答案by pycruft
Python 2.7, .hexdigest() does return a str
Python 2.7,.hexdigest() 确实返回一个 str
>>> hashlib.md5("foo").hexdigest() == "acbd18db4cc2f85cedef654fccc4a4d8"
True
>>> type(hashlib.md5("foo").hexdigest())
<type 'str'>
Python 3.1
蟒蛇 3.1
.md5() doesn't take a unicode (which "foo" is), so that needs to be encoded to a byte stream.
.md5() 不采用 unicode(即“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
回答by SilentGhost
hexdigestreturns a string. Your first statement returns Truein python-2.x.
hexdigest返回一个字符串。你的第一条语句True在 python-2.x 中返回。
In python-3.x you would need to encode argument to md5function, in that case equality is also True. Without encoding it raises TypeError.
在 python-3.x 中,您需要将参数编码为md5函数,在这种情况下,相等也是True. 没有编码它会引发TypeError.
回答by jwilkins
Using == for a hash comparison is likely a security vulnerability.
使用 == 进行哈希比较可能是一个安全漏洞。
https://groups.google.com/forum/?fromgroups=#!topic/keyczar-discuss/VXHsoJSLKhM
https://groups.google.com/forum/?fromgroups=#!topic/keyczar-discuss/VXHsoJSLKhM
It's possible for an attacker to look for timing differences and iterate through the keyspace efficiently and find a value that will pass the equality test.
攻击者有可能寻找时间差异并有效地遍历键空间并找到将通过相等性测试的值。

