我有一个Python2的脚本,效果很好.
def _generate_signature(data):
return hmac.new('key', data, hashlib.sha256).hexdigest()
其中数据是json.dumps
的输出.
现在,如果我try 在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'
如果我try 像这样将密钥转换为字节:
bytes('key')
我明白了
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: string argument without an encoding
我仍在努力理解Python 3中的编码.