我在Python2中有个运行良好的脚本。
def _generate_signature(data):
return hmac.new('key', data, hashlib.sha256).hexdigest()
数据是的输出json.dumps
。
现在,如果我尝试在Python 3中运行相同类型的代码,则会得到以下信息:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/lib/python3.4/hmac.py", line 144, in new
return HMAC(key, msg, digestmod)
File "/usr/lib/python3.4/hmac.py", line 42, in __init__
raise TypeError("key: expected bytes or bytearray, but got %r" %type(key).__name__)
TypeError: key: expected bytes or bytearray, but got 'str'
如果我尝试将密钥转换为字节这样的操作:
bytes('key')
我懂了
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: string argument without an encoding
我仍在努力理解Python 3中的编码。
您可以使用字节字面量: b'key'
def _generate_signature(data):
return hmac.new(b'key', data, hashlib.sha256).hexdigest()
除此之外,请确保data
也是字节。例如,如果从文件中读取文件,则在打开文件时需要使用binary
模式(rb
)。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句