我在使用 HMAC 时遇到了一点问题。运行这段代码时:
signature = hmac.new(
key=secret_key,
msg=string_to_sign,
digestmod=sha1,
)
我收到一个奇怪的错误:
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
当我打印 string_to_sign 时,它是一个像这样的正确字符串:
GET
\n
\n
application/json
\n
\n
\n
错误是什么意思?是因为换行吗?
最佳答案
如被问及,我会将其发布为答案。 您遇到的错误是 Python 的 HMAC 的 feature。它不接受 unicode。 此功能描述为here .
HMAC 是一个在字节级别工作的函数。由于这个原因,在 Python 3 中它只接受 bytes
。在 Python 2 中,我们没有 bytes
,因此它只接受 str
。
关于Python HMAC : TypeError: character mapping must return integer, 无或 unicode,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20849805/