Unicode Objects must be encoded before hashing 错误

Unicode Objects must be encoded before hashing error

处理类似问题的问题:SO 1, SO 2,

我试过他们的答案,将几乎所有字符串编码为 utf-8,但 hmac 仍然告诉我编码我的 unicoe 字符。最大的问题是我什至无法识别有问题的变量;打印输出告诉我它们是 stringsbytes;对于前者,我附加了 .encode(),但这并没有帮助。

我正在尝试查询 GDAX API,我也在 using the code as given on their API page。为 Python2.7 编写,我认为编码和所有问题可能存在问题,但这对我来说没有意义。

我的代码:

class CoinbaseExchangeAuth(AuthBase):
    def __init__(self, api_key, secret_key, passphrase):
        self.api_key = api_key.encode()
        self.secret_key = secret_key.encode()
        self.passphrase = passphrase.encode()

    def __call__(self, request):
        timestamp = str(time.time())
        message = timestamp + request.method + request.path_url + (request.body or '')
        hmac_key = base64.b64decode(self.secret_key)
    #print(hmac_key, type(hmac_key))
    #print(message, type(message))
    signature = hmac.new(hmac_key, message, hashlib.sha256)

    signature_b64 = signature.digest().encode('base64').rstrip('\n')


    request.headers.update({
        'CB-ACCESS-SIGN': signature_b64,
        'CB-ACCESS-TIMESTAMP': timestamp,
        'CB-ACCESS-KEY': self.api_key,
        'CB-ACCESS-PASSPHRASE': self.passphrase,
        'Content-Type': 'application/json'
    })
    return request

错误:

File "F:\git\knowhere\Private\bitex-crawler\gdax_client\gdaxex\api.py", line 47, in __call__
signature = hmac.new(hmac_key, message, hashlib.sha256)
File "C:\Users\nls\Anaconda3\lib\hmac.py", line 144, in new
return HMAC(key, msg, digestmod)
File "C:\Users\nls\Anaconda3\lib\hmac.py", line 84, in __init__
self.update(msg)
File "C:\Users\nls\Anaconda3\lib\hmac.py", line 93, in update
self.inner.update(msg)
TypeError: Unicode-objects must be encoded before hashing

当我键入检查我提供给 hmac.new() 调用的对象时,它告诉我我有一个 str 对象和一个 bytes 对象。

print(type(hmac_key)) # <bytes>
print(type(message))  # <str>

当然,我想我也需要对那个笨蛋进行编码:

signature = hmac.new(hmac_key, message.encode(), hashlib.sha256)

导致此行出错:

signature_b64 = signature.digest().encode('base64').rstrip('\n')

即:

File "F:/git/knowhere/Private/bitex-crawler/gdax_client/client.py",
[..]
File "F:\git\knowhere\Private\bitex-crawler\gdax_client\gdaxex\api.py", line 123, in _query
r = api_query(url, json=req, auth=auth)
File "C:\Users\nls\Anaconda3\lib\site-packages\requests\api.py", line 67, in get
return request('get', url, params=params, **kwargs)
File "C:\Users\nls\Anaconda3\lib\site-packages\requests\api.py", line 53, in request
return session.request(method=method, url=url, **kwargs)
File "C:\Users\nls\Anaconda3\lib\site-packages\requests\sessions.py", line 454, in request
prep = self.prepare_request(req)
File "C:\Users\nls\Anaconda3\lib\site-packages\requests\sessions.py", line 388, in prepare_request
hooks=merge_hooks(request.hooks, self.hooks),
File "C:\Users\nls\Anaconda3\lib\site-packages\requests\models.py", line 297, in prepare
self.prepare_auth(auth, url)
File "C:\Users\nls\Anaconda3\lib\site-packages\requests\models.py", line 490, in prepare_auth
r = auth(self)
File "F:\git\knowhere\Private\bitex-crawler\gdax_client\gdaxex\api.py", line 49, in __call__
signature_b64 = signature.digest().encode('base64').rstrip('\n')
AttributeError: 'bytes' object has no attribute 'encode'

..所以我不能有未编码的 unicode 对象,但我以后也不能有字节?我到底该如何解决这个问题?感谢对此的任何帮助,因为我非常困惑。

"Parameter msg can be of any type supported by hashlib.".

"Note: Feeding string objects into is not supported, as hashes work on bytes, not on characters.".

因此,您的消息必须是 bytes 类型。在消息上使用 .encode() 会给你字节对象。

注意:这仅对 python 3!

是必需的

要将摘要编码为 base64,请使用 base64 library

import base64
signature_b64 = base64.b64encode(signature.digest())

对于 Python 3.9,我遇到了同样的错误,

self._inner.update(msg) TypeError: Unicode-objects must be encoded before hashing

以下对我有用,

signature = hmac.new(key.encode('utf-8'), msg.encode('utf-8'), hashlib.sha256)
auth_token = str(signature.hexdigest())