Python HMAC : TypeError: character mapping must return integer, 无或 unicode

标签 python

我在使用 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/

相关文章:

python - h2o:遍历行

python - subprocess.poll() 不工作

Python Google Drive API discovery.build 失败,退出代码为 -1073740777 (0xC0000417)

python - ValueError : could not broadcast input array from shape (11253, 1) 进入形状 (11253)

for-loop - 对于列表,除非在 python 中为空

Python程序随机挂起

python - npm install grunt-takana 在 node-gyp 重建时失败

python - "Two-to-many"与 Flask-SQLAlchemy 的关系

python - 无法解码图像并形成矩阵

python - 在 Windows 10 上导入 win32api 时出现 DLL 错误