Python 3.x 在Python中创建HMAC-SHA1哈希时出现的问题
我在生成签名(HMAC-SHA1散列格式)时遇到问题,我一直收到一个类型错误 我正在使用以下代码生成签名:Python 3.x 在Python中创建HMAC-SHA1哈希时出现的问题,python-3.x,hmac,hmacsha1,Python 3.x,Hmac,Hmacsha1,我在生成签名(HMAC-SHA1散列格式)时遇到问题,我一直收到一个类型错误 我正在使用以下代码生成签名: 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 '
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]
回溯(最近一次呼叫最后一次):
文件“C:\Users\…\Documents\serviceinfo\sig.py”,第12行,在
打印(getUrl('/v2/healthcheck'))
文件“C:\Users\…\Documents\serviceinfo\sig.py”,第9行,在getUrl中
hashed=hmac.new(key,raw,sha1)
文件“C:\Users\…\AppData\Local\Programs\Python\Python37-32\lib\hmac.py”,第153行,新格式
返回HMAC(键、消息、digestmod)
文件“C:\Users\…\AppData\Local\Programs\Python\Python37-32\lib\hmac.py”,第49行,在__
raise TypeError(“键:应为字节或字节数组,但获得了%r”%type(键)。\uuuu name\uuuu)
TypeError:key:应为字节或bytearray,但得到'str'
[在0.1s内完成,退出代码为1]
有人能给我指出正确的方向吗?提前谢谢 必须是字节的字节数组。
使用以下代码将字符串对象转换为
key=bytes(str('7car2d2b-7527-14e1-8975-06cf1059afe0'),'utf8')
然后给出hamc.new对象的键
或
您可以使用函数而不是字节
key=bytearray(str('7car2d2b-7527-14e1-8975-06cf1059afe0'), 'utf-8')
然后把钥匙交给hamc.new object谢谢。我尝试了这两个选项,但得到了一个新的错误:“TypeError:在散列之前必须对Unicode对象进行编码”。有什么想法吗?嗨,马特,你有答案吗?