【问题标题】:Issue creating a HMAC-SHA1 hash in Python在 Python 中创建 HMAC-SHA1 哈希的问题
【发布时间】:2020-03-04 18:20:43
【问题描述】:

我在生成签名时遇到问题(采用 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]

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

【问题讨论】:

    标签: python-3.x hmac hmacsha1


    【解决方案1】:

    您的key value 必须是字节的字节数组。 使用以下代码将字符串对象转换为bytes

    key=bytes(str('7car2d2b-7527-14e1-8975-06cf1059afe0'),'utf8')
    

    然后给出 hamc.new 对象的密钥

    或者

    您可以使用bytearray 函数代替字节

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

    然后给出 hamc.new 对象的密钥

    【讨论】:

    • 谢谢。我已经尝试了这两个选项,但出现了一个新错误:“TypeError:Unicode 对象必须在散列之前进行编码”。有什么想法吗?
    • 嗨@Matt 你有答案吗?
    猜你喜欢
    • 1970-01-01
    • 2011-11-20
    • 2021-04-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多