【问题标题】:How to fix Unicode encode error using the hashlib module?如何使用 hashlib 模块修复 Unicode 编码错误?
【发布时间】:2011-07-13 17:40:31
【问题描述】:

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

    pwdinput = input("Now enter a password:")
    pwd = hashlib.sha1()
    pwd.update(pwdinput)
    pwd = pwd.hexdigest()

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

【问题讨论】:

    标签: python unicode hashlib


    【解决方案1】:
    pwdinput = input("Now enter a password:").encode('utf-8') # or whatever encoding you wish to use
    

    假设您使用的是 Python 3,这会将 input() 返回的 Unicode 字符串转换为以 UTF-8 编码的 bytes 对象,或者您希望使用的任何编码。以前版本的 Python 也有它,但是它们对 Unicode 和非 Unicode 字符串的处理有点混乱,而 Python 3 在 Unicode 字符串 (str) 和可能或可能的不可变字节序列之间有一个明确的区别不代表 ASCII 字符 (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 中也应该可以很好地工作,因为 strunicode 类型都有编码方法,并且,如果字符串仅包含 ASCII 字符,则字符串的 utf-8 编码与这些字符的字节字符串完全相同。如果您希望 "abc" 和 u"abc" 的哈希值相同,这一事实很重要。如果您可以接受这两者的区别对待,那么任何编码都可以。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-08-02
    • 1970-01-01
    • 2020-11-18
    • 1970-01-01
    • 2022-01-17
    • 2019-12-07
    • 2020-07-10
    相关资源
    最近更新 更多