python用hashlib 遇到 TypeError: Unicode-objects must be encoded before hashing

使用hashlib库的朋友想必都遇到过以下的错误吧:“Unicode-objects must be encoded before hashing”,意思是在进行md5哈希运算前,需要对数据进行编码

>>> import hashlib
>>> date = 'gooboys.com'
>>> m = hashlib.md5(date)
Traceback (most recent call last):
  File "", line 1, in 
TypeError: Unicode-objects must be encoded before hashing

只需进行转码一下可以了,下面是解决方法:

>>> m = hashlib.md5(date.encode('utf-8'))
>>> print(m.hexdigest())
7ba10da18d9aecb8e25907a32c0eecee
>>> 

在实验楼处进行python验证码破解的实验中遇到的错误,代码片段,附上正确的解法:

for letter in letters:
    m = hashlib.md5()
 
    im3 = im2.crop((letter[0], 0, letter[1], im2.size[1]))
    # m.update(("%s%s" % (time.time(), count))) 原代码
    # 正确代码
    m.update(("%s%s" % (time.time(), count)).encode('utf-8'))
    im3.save("./%s.gif" % (m.hexdigest()))
    count += 1

有错欢迎提出指导
THEDARYEYES更多内容原文链接

你可能感兴趣的:(python用hashlib 遇到 TypeError: Unicode-objects must be encoded before hashing)