Compare result from hexdigest() to a string

那年仲夏 提交于 2019-11-30 20:31:43

Python 2.7, .hexdigest() does return a str

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

Python 3.1

.md5() doesn't take a unicode (which "foo" is), so that needs to be encoded to 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

Using == for a hash comparison is likely a security vulnerability.

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.

hexdigest returns a string. Your first statement returns True in python-2.x.

In python-3.x you would need to encode argument to md5 function, in that case equality is also True. Without encoding it raises TypeError.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!