【问题标题】:Hashing with Python 3: Do I need to .encode() every string?使用 Python 3 散列:我需要对每个字符串进行 .encode() 吗?
【发布时间】:2016-05-08 07:09:51
【问题描述】:

我正在从 Python 2 迁移到 Python 3,想知道现在是否需要对每个字符串文字进行编码,然后才能对其进行哈希处理。示例代码将在 Python 2 下完美运行:

import hashlib
string = "robots"
hashlib.md5(string).hexdigest()

但是,使用 Python 3,它会抛出一个 TypeError: Unicode-objects must be encoded before hashing,所以我必须在每个字符串之后附加一个 .encode(),或者我在这里遗漏了什么?

【问题讨论】:

  • string = b"robots"string 是标准库模块,变量名是个坏主意)

标签: python python-3.x hash encoding encode


【解决方案1】:

hashlib 仅在 bytes-like objects 上运行,documentation 明确指出:

注意:不支持将字符串对象输入update(),因为散列适用于字节,而不是字符。

因此,任何时候您想在 Python 3 中对 str 对象进行哈希处理,都必须先对其进行编码。

【讨论】:

  • 因为在 Python 2 中你有 strunicode。在 Python 3 中,它们是 bytesstrstr 的概念改变了,hashlib 没有改变。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2022-01-22
  • 1970-01-01
  • 2015-12-14
  • 1970-01-01
  • 2021-08-25
  • 1970-01-01
  • 2012-06-13
相关资源
最近更新 更多