如何在python 3.x中通过hmac生成API签名

时间:2019-04-29 09:28:08

标签: python-3.x api signature

我正在尝试将REST API调用从Java转换为Python,但无法生成API标头签名。

我尝试了以下代码-

consumerKey = "xyz"
consumerSecret = "xyz"
callBackURL = "www.example.com"
t = str(time.time()).split('.')
timestamp = t[0]
oauthstr = client_id + ":" + client_secret
auth = base64.b64encode(oauthstr.encode())
url = "https://example.com/v2/oauth/generateaccesstoken"
querystring = {"grant_type":"client_credentials"}
base_str = callback + client_id + t[0]

signature = hmac.new(str.encode(base_str), str.encode(client_secret), hashlib.sha256).hexdigest()
signature = base64.b64encode(signature.encode())

payload = ""
headers = {
    'Authorization': "Basic "+auth.decode(),
    'signature': signature,
    'timestamp': timestamp,
    }

response = requests.request("POST", url, data=payload, headers=headers, params=querystring)

我收到{“ Error”:“ 4301”},这意味着-“已传递HMAC签名,但不是正确的签名”

在Java中,我正在生成签名-

mixcode = callBackURL+consumerKey+timeStamp;
Mac sha256_HMAC = Mac.getInstance("HmacSHA256");
SecretKeySpec secret_key = new SecretKeySpec(consumerSecret.getBytes(), "HmacSHA256");
sha256_HMAC.init(secret_key);
signature = Base64.encodeBase64String(sha256_HMAC.doFinal(mixcode.getBytes()));

0 个答案:

没有答案