1. 程式人生 > >Unicode-objects must be encoded before hashing

Unicode-objects must be encoded before hashing

報錯程式碼:
md5 = hashlib.md5()
md5.update(('This is a sentence.'))
md5.update(('This is a second sentence.'))
print (u'不出意外,這個將是“亂碼”:', md5.digest())
print (u'MD5:', md5.hexdigest())

報錯誤:Unicode-objects must be encoded before hashing

修改後的程式碼:

md5 = hashlib.md5()
md5.update(('This is a sentence.').encode("utf8"))
md5.update(('This is a second sentence.').encode("utf8"))
print (u'不出意外,這個將是“亂碼”:', md5.digest())
print (u'MD5:', md5.hexdigest())

修改原因:注意update()必須指定要加密的字串的字元編碼