使用 Python 散列 3:我是否需要对每个字符串进行 .encode()?
Hashing with Python 3: Do I need to .encode() every string?
我正在从 Python 2 迁移到 Python 3 并且想知道现在是否需要对每个字符串文字进行编码才能对其进行哈希处理。示例代码将 运行 完美地置于 Python 2:
之下
import hashlib
string = "robots"
hashlib.md5(string).hexdigest()
using Python 3 然而,它抛出一个 TypeError: Unicode-objects must be encoded before hashing
所以我必须在每个字符串后附加一个 .encode()
或者我在这里遗漏了什么?
hashlib
对 bytes-like objects only and the documentation 的操作明确指出:
Note: Feeding string objects into update()
is not supported, as hashes work on bytes, not on characters.
所以任何时候你想在 Python 3 中散列一个 str
对象,你必须先对其进行编码。
我正在从 Python 2 迁移到 Python 3 并且想知道现在是否需要对每个字符串文字进行编码才能对其进行哈希处理。示例代码将 运行 完美地置于 Python 2:
之下import hashlib
string = "robots"
hashlib.md5(string).hexdigest()
using Python 3 然而,它抛出一个 TypeError: Unicode-objects must be encoded before hashing
所以我必须在每个字符串后附加一个 .encode()
或者我在这里遗漏了什么?
hashlib
对 bytes-like objects only and the documentation 的操作明确指出:
Note: Feeding string objects into
update()
is not supported, as hashes work on bytes, not on characters.
所以任何时候你想在 Python 3 中散列一个 str
对象,你必须先对其进行编码。