在 Python 中创建 HMAC-SHA1 哈希时出现问题

Issue creating a HMAC-SHA1 hash in Python

我在生成签名(采用 HMAC-SHA1 哈希格式)时遇到问题,我不断收到 TypeError。

我正在使用以下代码生成签名:

from hashlib import sha1
import hmac
import binascii
def getUrl(request):
    devId = 2
    key = '7car2d2b-7527-14e1-8975-06cf1059afe0'
    request = request + ('&' if ('?' in request) else '?')
    raw = request+'devid={0}'.format(devId)
    hashed = hmac.new(key, raw, sha1)
    signature = hashed.hexdigest()
    return 'http://api.domain.com'+raw+'&signature={1}'.format(devId, signature)
print(getUrl('/v2/healthcheck'))

我不断收到的错误是:

Traceback (most recent call last):
  File "C:\Users\...\Documents\serviceinfo\sig.py", line 12, in <module>
    print(getUrl('/v2/healthcheck'))
  File "C:\Users\...\Documents\serviceinfo\sig.py", line 9, in getUrl
    hashed = hmac.new(key, raw, sha1)
  File "C:\Users\...\AppData\Local\Programs\Python\Python37-32\lib\hmac.py", line 153, in new
    return HMAC(key, msg, digestmod)
  File "C:\Users\...\AppData\Local\Programs\Python\Python37-32\lib\hmac.py", line 49, in __init__
    raise TypeError("key: expected bytes or bytearray, but got %r" % type(key).__name__)
TypeError: key: expected bytes or bytearray, but got 'str'
[Finished in 0.1s with exit code 1]

有人能给我指出正确的方向吗?提前致谢!

您的 key value 必须是字节数组。 使用以下代码

将字符串对象转换为 bytes
key=bytes(str('7car2d2b-7527-14e1-8975-06cf1059afe0'),'utf8')

然后把钥匙交给hamc.new对象

你可以使用 bytearray 函数代替 bytes

key=bytearray(str('7car2d2b-7527-14e1-8975-06cf1059afe0'), 'utf-8')

然后把钥匙交给hamc.new对象