I am having a slight problem with HMAC. When running this piece of code:
signature = hmac.new( key=secret_key, msg=string_to_sign, digestmod=sha1, )
I get a strange error:
File "/usr/local/Cellar/python/2.7.6/Frameworks/Python.framework/Versions/2.7/lib/python2.7/hmac.py", line 133, in new return HMAC(key, msg, digestmod) File "/usr/local/Cellar/python/2.7.6/Frameworks/Python.framework/Versions/2.7/lib/python2.7/hmac.py", line 72, in __init__ self.outer.update(key.translate(trans_5C)) TypeError: character mapping must return integer, None or unicode
When I print string_to_sign, it is a proper string like this:
GET \n \n application/json \n \n \n
What does the error mean? Is it because of new lines?
As asked I'll post this as an answer. The error that you faced is a feature of Python's HMAC. It does not accept unicode. This feature is described here.
HMAC is a function which works at byte level. For this reason in Python 3 it accepts only bytes
. In Python 2 we don't have bytes
so it accepts only str
.
Ensure that "key" and "msg" is a string.such as:
s = hmac.new(str(secretkey), str(message), digestmod=hashlib.sha1).hexdigest()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With