使用SHA56和Python请求进行Binance API调用

时间:2018-02-02 23:46:33

标签: python python-3.x python-requests sha256 sha

Haven在Python中工作很多,我显然没有发送正确的签名。如何散列并正确传递?

SIGNED endpoints require an additional parameter, signature, to be sent in the query string or request body.
Endpoints use HMAC SHA256 signatures. The HMAC SHA256 signature is a keyed HMAC SHA256 operation. Use your secretKey as the key and totalParams as the value for the HMAC operation.
The signature is not case sensitive.
totalParams is defined as the query string concatenated with the request body.

完整文档: https://github.com/binance-exchange/binance-official-api-docs/blob/master/rest-api.md

import requests, json, time, hashlib


apikey = "myactualapikey"
secret = "myrealsecret"
test = requests.get("https://api.binance.com/api/v1/ping")
servertime = requests.get("https://api.binance.com/api/v1/time")

servertimeobject = json.loads(servertime.text)
servertimeint = servertimeobject['serverTime']

hashedsig = hashlib.sha256(secret)

userdata = requests.get("https://api.binance.com/api/v3/account",
    params = {
        "signature" : hashedsig,
        "timestamp" : servertimeint,
    },
    headers = {
        "X-MBX-APIKEY" : apikey,
    }
)
print(userdata)

我正在

{"code":-1100,"msg":"Illegal characters found in parameter 'signature'; legal range is '^[A-Fa-f0-9]{64}$'."}

1 个答案:

答案 0 :(得分:3)

此:

hashedsig = hashlib.sha256(secret)

为您提供哈希对象,而不是字符串。您需要以十六进制格式获取字符串:

hashedsig = hashlib.sha256(secret).hexdigest()

您可以通过将您链接的文档(显示它们需要十六进制字符串)与原始hashedsig及其提供的函数进行比较来解决这个问题。

其次,正如评论者指出的那样,您需要申请HMAC,而不仅仅是SHA256:

params = urlencode({
    "signature" : hashedsig,
    "timestamp" : servertimeint,
})
hashedsig = hmac.new(secret.encode('utf-8'), params.encode('utf-8'), hashlib.sha256).hexdigest()

您可以在此处找到类似的代码:http://python-binance.readthedocs.io/en/latest/_modules/binance/client.html