Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/351.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
为什么这个hmac摘要在Python2.7和Python3.7上有所不同?_Python_Python 3.x_Python 2.x_Hmac_Hashlib - Fatal编程技术网

为什么这个hmac摘要在Python2.7和Python3.7上有所不同?

为什么这个hmac摘要在Python2.7和Python3.7上有所不同?,python,python-3.x,python-2.x,hmac,hashlib,Python,Python 3.x,Python 2.x,Hmac,Hashlib,我试图将一个项目从Python2.7迁移到Python3.7,并遇到了一个hmac摘要问题。运行以下代码会产生两种不同的结果 import hmac, hashlib print(hmac.new(bytes([]), bytes([]), hashlib.sha1).hexdigest()) 在Python 2.7上:1bd590e48bea8f0c8cc70602bc55d317c3de7c52 在Python 3.7上:fbdb1d1b18aa6c08324b7d64b71fb76370

我试图将一个项目从Python2.7迁移到Python3.7,并遇到了一个hmac摘要问题。运行以下代码会产生两种不同的结果

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'

在Python2.7中,
bytes()
被解释为
'
,这大致相当于Python3.7中的
b'

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

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

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

如果您在2.7和3.7中为密钥和消息添加类似
b“hello”
的内容,您将得到相同的哈希值