我有一个在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'
如果我尝试将密钥转换为字节,就像这样: If I try something like transforming the key to bytes like so:
bytes('key')
我明白了
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: string argument without an encoding
我仍然在努力理解Python 3中的编码。
TypeError:Unicode对象必须在哈希之前进行编码
。 - Trect