Python HMAC:TypeError:字符映射必须返回整数,None或unicode

Ric*_*nop 21 python

我对HMAC有轻微的问题.运行这段代码时:

signature = hmac.new(
    key=secret_key,
    msg=string_to_sign,
    digestmod=sha1,
)
Run Code Online (Sandbox Code Playgroud)

我收到一个奇怪的错误:

  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
Run Code Online (Sandbox Code Playgroud)

当我打印string_to_sign时,它是一个正确的字符串,如下所示:

GET
\n
\n
application/json
\n
\n
\n
Run Code Online (Sandbox Code Playgroud)

错误是什么意思?是因为新线?

sme*_*eso 39

如我所知,我会将此作为答案发布.您遇到的错误是Python HMAC的一个特性.它不接受unicode.此功能在此处描述.

HMAC是一个在字节级工作的函数.出于这个原因,在Python 3中它只接受bytes.在Python 2中我们没有bytes它只接受它str.


小智 15

确保"key"和"msg"是一个字符串.如:

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