2010-08-27 140 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

相關問題