python-哈希错误之前必须对Unicode对象进行编码

处理类似问题的问题:SO 1SO 2SO 3.

我尝试了他们的答案,几乎将任何字符串编码为utf-8,但是hmac仍然告诉我编码我的unicoe字符.最大的问题是我什至无法识别令人讨厌的变量.打印输出告诉我它们是字符串还是字节;在前者的情况下,我附加了.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.”.

因此,您的消息必须为字节类型.在消息夹中使用.encode()将为您提供bytes对象.

注意:这仅适用于python 3!

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

import base64
signature_b64 = base64.b64encode(signature.digest())
上一篇:在PHP中未设置编码数组后没有索引的json


下一篇:python 问题解决:UnicodeEncodeError: 'ascii' codec can't encode character u'\uff08