如何使用hashlib模块修复Unicode编码错误?

Nat*_*ate 28 python unicode hashlib

在多次搜索之后,我无法确定如何避免错误说明:"使用此代码时,必须在散列之前对Unicode对象进行编码":

    pwdinput = input("Now enter a password:")
    pwd = hashlib.sha1()
    pwd.update(pwdinput)
    pwd = pwd.hexdigest()
Run Code Online (Sandbox Code Playgroud)

我怎样才能克服这个错误?你如何编码Unicode对象?

JAB*_*JAB 49

pwdinput = input("Now enter a password:").encode('utf-8') # or whatever encoding you wish to use
Run Code Online (Sandbox Code Playgroud)

假设您正在使用Python 3,这会将返回的Unicode字符串转换为以UTF-8编码input()bytes对象,或您希望使用的任何编码.以前版本的Python也有它,但它们对Unicode与非Unicode字符串的处理有点混乱,而Python 3明确区分Unicode字符串(str)和可能或不表示ASCII的不可变字节序列characters(bytes).

http://docs.python.org/library/stdtypes.html#str.encode
http://docs.python.org/py3k/library/stdtypes.html#str.encode

  • 虽然我不是Python 2.x的unicode处理的忠实粉丝,但这个特殊代码在Python 2.7中应该也能很好地工作,因为`str`和`unicode`类型都有编码方法,并且,如果字符串包含只有ASCII字符,字符串的utf-8编码完全等于这些字符的字节串.如果你想要"abc"和u"abc"的哈希值相同,这个事实很重要.如果你对那两个被区别对待的人没问题,那么任何编码都可以. (8认同)