hashlib.md5() TypeError: Unicode 对象必须在散列之前编码 [英] hashlib.md5() TypeError: Unicode-objects must be encoded before hashing
问题描述
我是编码新手,在尝试对字符串进行编码时遇到了问题.
<预><代码>>>>导入哈希库>>>a = hashlib.md5()>>>a.更新('嗨')回溯(最近一次调用最后一次):文件<pyshell#22>",第 1 行,在 <module> 中a.更新('嗨')类型错误:必须在散列之前对 Unicode 对象进行编码>>>a.消化()b'xd4x1dx8cxd9x8fx00xb2x04xe9x80 x98xecxf8B~'现在是否认为 (a) 已编码?
第二个问题:当我在脚本中运行上面相同的代码时,出现此错误:
导入 hashliba = hashlib.md5()a.更新('嗨')a.消化()
回溯(最近一次调用最后一次):文件C:/Users/User/Desktop/Logger/Encoding practice.py",第 3 行,在a.更新('嗨')类型错误:Unicode 对象必须在散列之前编码
为什么代码在 shell 中运行而不是在脚本中运行?我正在使用 Windows 和 Python 3.4
谢谢.
我找到的解决方案是直接在要散列的行中对数据进行编码:
hashlib.sha256("a".encode('utf-8')).hexdigest()
它对我有用,希望能帮到你!
I am new to coding and have ran into a problem trying to encode a string.
>>> import hashlib
>>> a = hashlib.md5()
>>> a.update('hi')
Traceback (most recent call last):
File "<pyshell#22>", line 1, in <module>
a.update('hi')
TypeError: Unicode-objects must be encoded before hashing
>>> a.digest()
b'xd4x1dx8cxd9x8fx00xb2x04xe9x80 x98xecxf8B~'
Is (a) now considered to be encoded?
Second question: When I run the same code above in a script I get this error:
import hashlib
a = hashlib.md5()
a.update('hi')
a.digest()
Traceback (most recent call last): File "C:/Users/User/Desktop/Logger/Encoding practice.py", line 3, in a.update('hi') TypeError: Unicode-objects must be encoded before hashing
Why is the code working in the shell and not the script? I am working with Windows and Python 3.4
Thanks.
The solution I've found is to simply encode the data right away in the line where you're hashing it:
hashlib.sha256("a".encode('utf-8')).hexdigest()
It worked for me, hope it helps!
这篇关于hashlib.md5() TypeError: Unicode 对象必须在散列之前编码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!