I'm having issues generating a signature (in a HMAC-SHA1 hash format), I keep getting a TypeError.
I'm using the following code to generate the signature:
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'))
The error I keep getting is:
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]
Is anyone able to point me in the right direction? Thanks in advance!
your key value must be a byte array of bytes. to convert a string object to a bytes using following code
key=bytes(str('7car2d2b-7527-14e1-8975-06cf1059afe0'),'utf8')
and then give the key to hamc.new object
Or
you can use bytearray function instead of bytes
key=bytearray(str('7car2d2b-7527-14e1-8975-06cf1059afe0'), 'utf-8')
and then give the key to hamc.new object