Python:Unicode对象必须在散列之前进行编码




我正在与加密货币交易所合作,该交易所需要对秘密API密钥进行编码才能访问私有API调用。我已经复制并粘贴了他们的 Python 代码以开始使用它执行我的调用,但每次我发出请求时都会收到此错误。

TypeError: Unicode-objects must be encoded before hashing

我知道这意味着什么;我是一名程序员。我在从交易所收到的代码中找不到问题的根源,因为我没有使用 hmac、hashlib 或 base64。我在下面的代码中用单词"exchange"替换了交易所名称的所有实例。不显示任何 API 密钥。

exchangeconfig = Exchange('key', 'secret')
base = 'https://exchange.com/'
def post_request(key, secret, path, data):
    hmac_obj = hmac.new(secret, path + chr(0) + data, hashlib.sha512)
    hmac_sign = base64.b64encode(hmac_obj.digest())
    header = {
        'Content-Type': 'application/json',
        'User-Agent': 'exchangev2 based client',
        'Rest-Key': key,
        'Rest-Sign': hmac_sign,
    }
    proxy = ProxyHandler({'http': '127.0.0.1:8888'})
    opener = build_opener(proxy)
    install_opener(opener)
    request = Request(base + path, data, header)
    response = urlopen(request, data)
    return json.load(response)
def gen_tonce():
    return str(int(time.time() * 1e6))
class Exchange:
    def __init__(self, key, secret):
        self.key = key
        self.secret = base64.b64decode(secret)
    def request(self, path, params={}):
        params = dict(params)
        params['tonce'] = gen_tonce()
        # data = urllib.urlencode(params)
        data = json.dumps(params)
        result = post_request(self.key, self.secret, path, data)
        if result['result'] == 'success':
            return result['data']
        else:
            raise Exception(result['result'])
exchangeconfig.request("api/3/account")

请帮我弄清楚这一点。 顺便说一句:这条线似乎特别有问题:

hmac_obj = hmac.new(secret, path + chr(0) + data, hashlib.sha512)

谢谢。

更新:修复了该错误。现在进入这个:

TypeError: POST data should be bytes, an iterable of bytes, or a file object. It cannot be of type str.

这些哈希库处理字节对象,因此您应该首先将字符串编码为字节(假设解码端使用 UTF-8(:

hmac_obj = hmac.new(secret, path.encode('utf-8') + b'' + data.encode('utf-8'), hashlib.sha512)

最新更新