案例代码片段如下:
pwd = 123
s1 = sha1()
s1.update(pwd)
pwd2 = s1.hexdigest()
出现如下异常:
Traceback (most recent call last):
File ".......", line 11, in <module> s1.update(pwd)
TypeError: Unicode-objects must be encoded before hashing
Process finished with exit code 1
原因,对密码进行加密时,需要先使用encode()对输入的密码进行统一编码。所以,代码中的s1.update(pwd)应修改为:s1.update(pwd.encode(“gb2312”))。
其中,encode(“gb2312”)中的双引号可为单引号,并且gb2312可以更换为gbk、ascii、gb18030、utf8、utf-8、utf16、utf-16、utf32、utf-32(字母不区分大小写)等。

本文介绍了一段Python代码中使用SHA1对密码进行加密时出现的TypeError异常,原因是未对Unicode对象进行编码。文章详细解释了如何通过使用encode()方法将密码转换为字节串来解决此问题,同时提供了多种编码格式选项。
6489

被折叠的 条评论
为什么被折叠?



