为什么这个 hmac 摘要在 Python 2.7 和 Python 3.7 上不同?

Why is this hmac digest different on Python 2.7 and Python 3.7?

我正在尝试将一个项目从 Python 2.7 移至 Python 3.7,并将 运行 移至 hmac 摘要的问题中。 运行 以下代码产生 2 个不同的结果

import hmac, hashlib
print(hmac.new(bytes([]), bytes([]), hashlib.sha1).hexdigest())

在 Python 2.7 上:1bd590e48bea8f0c8cc70602bc55d317c3de7c52

在 Python 3.7 上:fbdb1d1b18aa6c08324b7d64b71fb76370690e1d

为什么这两个结果不同?

在Python 3.7中,bytes()bytes([])都被解释为b''

在Python 2.7中,bytes()被解释为'',大致相当于Python 3.7中的b''

但是,Python 2.7 将 bytes([]) 解释为 '[]'

这就是差异的来源。如果您使用 bytes()b'' 而不是 bytes([]),您应该在 Python 2.7 和 Python 3.7 中得到相同的结果。

在 2.7 中,bytes([]) 是 str 类型,而在 3.7 中,bytes([]) 是类型 bytes。

如果您在 2.7 和 3.7 中为密钥和消息添加类似 b"hello" 的内容,您将得到相同的散列值。