【问题标题】:Coinlist exchange API authentication - PythonCoinlist 交易所 API 认证 - Python
【发布时间】:2021-06-29 17:40:56
【问题描述】:

在过去的一个月里,我一直在尝试了解 coinlist API (https://coinlist.co),因为没有可用的 API 包装器,这是一项艰巨的任务。我发现他们的 API 文档与 coinbase 交易所非常相似,并尝试推断但没有成功。

import json, hmac, hashlib, time, requests
from requests.auth import AuthBase

# Before implementation, set environmental variables with the names API_KEY and API_SECRET
API_KEY = 'xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx'
API_SECRET = 'xxxx/xxxxxxxxxxxxxxxxxxxxx/xxxxxxxxxxxxxxxxx=='

# Create custom authentication for Coinlist API
class CoinlistWalletAuth(AuthBase):
    def __init__(self, api_key, secret_key):
        self.api_key = api_key
        self.secret_key = secret_key

    def __call__(self, request):
        timestamp = str(int(time.time()))
        message = timestamp + request.method + request.path_url + (request.body or '')
        signature = hmac.new(self.secret_key, message, hashlib.sha256).hexdigest()

        request.headers.update({
            'CL-ACCESS-SIGN': signature,
            'CL-ACCESS-TIMESTAMP': timestamp,
            'CL-ACCESS-KEY': self.api_key,
        })
        return request
auth = CoinlistWalletAuth(API_KEY, API_SECRET)
#Test1 - Fetching account balance
response = requests.get('https://trade-api.coinlist.co/v1/accounts', auth=auth)

我得到这个 TypeError: key: expected bytes or bytearray, but got 'str' 在调用响应时。

文档说 - 您必须对签名进行 base64 编码(sha256 HMAC 的输出)。为什么会失败?

【问题讨论】:

    标签: python cryptography exchange-server coinbase-api


    【解决方案1】:

    两件事:

    TypeError: key: expected bytes or bytearray, but got 'str'

    hmac.new(key, msg=None, digestmod='')

    返回一个新的 hmac 对象。 key 是一个字节或字节数组对象,提供密钥。 (...)

    import base64
    ...
    secret_key_as_bytes = base64.b64decode(self.secret_key, altchars=None)
    

    The CL-ACCESS-SIG header is generated by creating a sha256 HMAC using the base64-decoded secret key on the prehash string timestamp + HTTP method + path + body (where '+' represents string concatenation) and base64-encode the output.

    digest = hmac.new(secret_key_as_bytes, message, hashlib.sha256).digest()
    signature = str(base64.b64encode(digest))
    

    【讨论】:

      【解决方案2】:

      希望还不算太晚 hmac.new() 函数需要关键参数是字节,所以:

      byte_key = bytes(self.secret_key, 'UTF-8')  # key.encode() would also work in this case
      

      但还没有完成,如果你这样做,你会得到

      TypeError: Unicode 对象必须在散列之前进行编码 要解决这个问题,您的消息应该被编码。

      message = message.encode()
      
      
      h = hmac.new(byte_key, message, hashlib.sha256).hexdigest()
      

      现在完成了。 但是我得到了 400。伤心。

      我发现有人这样做了: https://gist.github.com/badmofo/d109fbc447fea64d99e5ca58bdf53d7b

      【讨论】:

        猜你喜欢
        • 2017-04-08
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-02-25
        • 1970-01-01
        • 1970-01-01
        • 2017-11-01
        相关资源
        最近更新 更多