python中的hash_hmac sha512身份验证

时间:2014-07-24 18:50:48

标签: python authentication httprequest private-key

我正在尝试为https://comkort.com/page/private_api

编写python身份验证机器人

没有完整的php示例。我猜有人可以把它放在这里。

只有一段PHP代码:

$query_string = http_build_query($_POST, '', '&');
$ethalon_sign = hash_hmac("sha512", $query_string, $api_secret_key);

如何使用hash_hmac sha512在python上编写身份验证?

我想提取open orders POST https://api.comkort.com/v1/private/order/list

我目前的变体是:

import hashlib
import hmac
import requests
import time

privateKey = b'myprivatekey'
publicKey = 'my public key'

url = 'https://api.comkort.com/v1/private/order/list'
tosign = b'market_alias=doge_ltc'
signing = hmac.new( privateKey , tosign, hashlib.sha512 )
headers = {'sign': signing.digest(), "apikey": publicKey, "nonce": int( time.time() ) }

r = requests.get(url, headers=headers)
print r.text

我抓住了这个

{"code":401,"error":"Invalid sign","field":"sign"}

可能是hexdigest()而不是digest()?我不知道,每次我发现一个错误时,我都在玩这个b前缀和不同的输出hmac选项:"无效的符号&#34 ;

相关:HMAC signing requests in Python

1 个答案:

答案 0 :(得分:9)

如果有人感兴趣,我自己就解决了这个问题。

#!/usr/bin/python

import hashlib
import hmac
import requests
import time

apikey = '';
apisecret = '';

def request_comkort( url, payload ):
        tosign = "&".join( [i + '=' + payload[i] for i in payload] )
        sign = hmac.new( apisecret, tosign , hashlib.sha512);
        headers = {'sign': sign.hexdigest(), 'nonce': int( time.time() ), 'apikey': apikey }
        r = requests.post(url, data=payload, headers=headers)
        return r.text

# Get balance
print request_comkort( "https://api.comkort.com/v1/private/user/balance";, {} )
# Get Open Orders 
print request_comkort( "https://api.comkort.com/v1/private/order/list";, {'market_alias': "DOGE_LTC" } )
# Make Ask
print request_comkort( "https://api.comkort.com/v1/private/order/sell";, { 'market_alias':"HTML_DOGE", "amount": "1000", "price": "123123" } )
# Cancel order
print request_comkort( "https://api.comkort.com/v1/private/order/cancel";, { 'order_id': 10943 } )