Issue 5285: hmac throws TypeErrors (original) (raw)
In Python 2.6 a performance optimization was added to the hmac module (http://bugs.python.org/issue1618455). This appears to have the unintended consequence of no longer accepting unicode strings as input.
Python 2.5.1 (r251:54863, Feb 4 2008, 21:48:13)
import hmac hmac.new(u'key','msg') <hmac.HMAC instance at 0x6e440>
Python 2.6.1 (r261:67515, Dec 9 2008, 14:49:30)
import hmac hmac.new(u'key','msg') Traceback (most recent call last): File "", line 1, in File "/Users/kteague/buildouts/shared/python-2.6.1/lib/python2.6/hmac.py", line 133, in new return HMAC(key, msg, digestmod) File "/Users/kteague/buildouts/shared/python-2.6.1/lib/python2.6/hmac.py", line 72, in init self.outer.update(key.translate(trans_5C)) TypeError: character mapping must return integer, None or unicode
This change is also reflected in Python 3.0 as the hmac module only accepts data as input (althought the docs still mention 'strings').
Python 3.0.1 (r301:69556, Feb 16 2009, 14:38:14)
import hmac hmac.new('key','msg') Traceback (most recent call last): File "", line 1, in File "/Users/kteague/buildouts/shared/python-3.0.1/lib/python3.0/hmac.py", line 140, in new return HMAC(key, msg, digestmod) File "/Users/kteague/buildouts/shared/python-3.0.1/lib/python3.0/hmac.py", line 43, in init raise TypeError("expected bytes, but got %r" % type(key).name) TypeError: expected bytes, but got 'str' hmac.new(b'key',b'msg') <hmac.HMAC object at 0x3a1810>
This module should likely accept both string and unicode (Python 2) or text and data (Python 3) and handle the conversion internally?