node.jspython-3.xhmacsha512

The hmac 512 migration from Node.js to Python 3.6 results does not match


Now I'm developing hmac 512 migration from Node.js to Python 3.6. Two codes make different results. The Node.js results is correct. The goal is to produce Python 3.6 code. Where should I do something for the problem ?

(1) Node.js

var crypto = require('crypto');

var data = {
    'request' : '/api/v1/account/balances',
    'nonce'   : 1589963590749
 };

secret = "SECRET";
data = JSON.stringify(data);
payload = Buffer.from(data).toString('base64');

signature = crypto.createHmac('sha512', secret).update(payload).digest('hex');
console.log(signature);

"94e40c0ad3d14746e7a15c31d3b4f8e4060d4cec81cbc529bce2ae02a45bf2b0b8ed3ad0a7842b6b3d26fe9bec045a3cedc8b546bb1c4a921416f03ed98815fb"

(2) Python3.6

import hmac, hashlib, json, base64

data = {
    'request': '/api/v1/account/balances',
    'nonce'  : 1589963590749
}

secret = "SECRET"
data = json.dumps(data)
payload = base64.b64encode(data.encode())
secret = secret.encode()
signature = hmac.new(secret, payload, hashlib.sha512).hexdigest()
print(signature)

"9aaa9f01dd2ab21bfc46bb1e369748afc5f638fa157578078472219b9bc615f4796d7a9502efcf7c4fdc5208a52470c5b850257d0c36050c9b2650d277fa8f8c"


Solution

  • You could find an issue step by step:

    1. Compare base64 encoded strings:

    JS: eyJyZXF1ZXN0IjoiL2FwaS92MS9hY2NvdW50L2JhbGFuY2VzIiwibm9uY2UiOjE1ODk5NjM1OTA3NDl9 which is (decoded):

    {"request":"/api/v1/account/balances","nonce":1589963590749}
    

    Python: eyJyZXF1ZXN0IjogIi9hcGkvdjEvYWNjb3VudC9iYWxhbmNlcyIsICJub25jZSI6IDE1ODk5NjM1OTA3NDl9 which is (decoded):

    {"request": "/api/v1/account/balances", "nonce": 1589963590749}
    

    Can you see the difference? Yes, there's a space after a colon.

    1. Find the way how to get rid of the trailing whitespaces, in your case you could dump via:
    data = json.dumps(data, separators=(',', ':'))