Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python HMAC: TypeError: character mapping must return integer, None or unicode

Tags:

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?

like image 925
Richard Knop Avatar asked Dec 31 '13 00:12

Richard Knop


2 Answers

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.

like image 130
smeso Avatar answered Sep 22 '22 05:09

smeso


Ensure that "key" and "msg" is a string.such as:

s = hmac.new(str(secretkey), str(message), digestmod=hashlib.sha1).hexdigest()

like image 25
zhuxiongxian Avatar answered Sep 23 '22 05:09

zhuxiongxian