Warm tip: This article is reproduced from stackoverflow.com, please click
php python hmac

php hmac sha512 signature not working/different then in python

发布于 2020-04-03 23:38:49

I can't find the problem why the signature keys are different. I think it has to do with python, it need to have bytes for input. But the output of both language is total different. Not sure what's wrong with it.

API_SECRET = 'ErLN2dewKAfY5j4bHOIFQaCKogJIv8Tq'

php

$digest2 = [
'486',
'GET',
'/orderlist',
'2.0',
'2020-01-29T11:45:47+01:00'];

print_r(base64_encode(hash_hmac('sha512', implode('', $digest2), $this->_API_SECRET, true)));

It wil give this code :

BsPgLClFDYl6oMRXkph7sz3opLeRAenzZ1w1X5fhiyDC4WVZViTvIWnLZWb1lQDVCRZ2/MkPT8irU9gax3m2Iw==

But when i tried to get the same code in python:

python

digest2 =['486','GET','/orderlist','2.0','2020-01-29T11:45:47+01:00']
#token = hmac.new(bytes('API_SECRET'.encode("utf-8")), msg=bytes(''.join(digest2 ).encode("utf-8")), digestmod=hashlib.sha512).hexdigest()
digest = hmac.new(bytes('API_SECRET'.encode("utf-8")), bytes(''.join(digest2 ),"utf-8"), digestmod=hashlib.sha512).hexdigest()
return base64.b64encode(digest.encode("utf-8"))

It will give this code:

b'YThhNGI0ZGZkN2Q5YmJmNDg5OTJmNzE1NGZiMWQyMWExYzQyODU3OGUxNmQ1ZTRkZWUxOGViZTUxNmFhM2M4MGZmZTYzMTJhNWNhYWQ5MDg3NDdlMGQ0NDBmMDliZThkNTA2ODA1YTlkMjJmZGMwZTk3NjVkNmM2MmE0NTViMjQ=
Questioner
ftft32
Viewed
18
hurlenko 2020-01-31 20:19

You used base64 encoding on hexed string. Also you used API_SECRET as string instead of variable. Here's the working solution

import hashlib
import hmac
import base64

API_SECRET = "ErLN2dewKAfY5j4bHOIFQaCKogJIv8Tq"
digest2 = ["486", "GET", "/orderlist", "2.0", "2020-01-29T11:45:47+01:00"]
digest = hmac.new(
    API_SECRET.encode("utf-8"),
    "".join(digest2).encode("utf-8"),
    digestmod=hashlib.sha512,
).digest()
print(base64.b64encode(digest))

Prints

'BsPgLClFDYl6oMRXkph7sz3opLeRAenzZ1w1X5fhiyDC4WVZViTvIWnLZWb1lQDVCRZ2/MkPT8irU9gax3m2Iw=='