我在Python2中有个脚本,效果很好。

def _generate_signature(data):
   return hmac.new('key', data, hashlib.sha256).hexdigest()

其中data是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'

如果我尝试将 key 转换为字节这样的操作:
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)。

关于python - Python3和hmac。如何处理不是二进制的字符串,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/31848293/

10-09 08:28