2010-08-27 143 views
3

我已经生成了一个MD5哈希,我想将它与来自字符串的另一个MD5哈希进行比较。下面的陈述是错误的,尽管它们在打印时看起来是一样的,应该是真实的。将hexdigest()的结果与字符串进行比较

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

谷歌告诉我,我应该在结果从hexdigest()编码,因为它不返回一个字符串。但是,下面的代码似乎也不工作。

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

回答

9

的Python 2.7,.hexdigest()确实返回一个STR

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

的Python 3.1

.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 
+0

你最后一段代码工作正常。不知何故,我在AppEngine开发服务器上测试时没有发现错误信息。我应该在python控制台中测试它。我道歉并且会在下次做。 – nip3o 2010-08-27 11:49:15

2

hexdigest returns a string。你的第一条语句在python-2.x中返回True

在python-3.x中,您需要将参数编码为md5函数,在这种情况下,等于也是True。没有编码它会提高TypeError

相关问题