hash_hmac sha512 authentication in python

2019-02-15 13:59发布

问题:

I'm trying to write python authentication bot for: https://comkort.com/page/private_api

There is no full php example. I'm guess somebody could put it here.

There is only snippet of php code:

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

How to write authentication on python with hash_hmac sha512 ?

I want to extract my open orders POST https://api.comkort.com/v1/private/order/list.

My current variant is:

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

I'm caught this

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

May be hexdigest() instead digest()? I don't know, I'm playing around this b prefix and different output hmac's options, everytime I'm caught one error: "Invalid sign".

Related: HMAC signing requests in Python

回答1:

If somebody interesting, I've solve this by myself.

#!/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 } )