Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why Python and Node.js's HMAC result is different in this code?

Recently, I have a task to make HMAC to communicate API server. I got a sample code of node.js version which makes HMAC of message. Using concept and sample, I've got to make a python code which is equivalent with node.js version but result is different, but I have no idea why.

Please review both code and help finding the difference.

Python 3.0

import hmac
import string
import hashlib
import base64

secret = 'PYPd1Hv4J6'
message = '1515928475.417'
key = base64.b64encode(secret.encode('utf-8'))

hmac_result = hmac.new(key, message.encode('utf-8'), hashlib.sha512)
print(base64.b64encode(hmac_result.digest()))

Result (Python 3.6)

b'7ohDRJGMGYjfHojnrvNpM3YM9jb+GLJjbQvblzrE17h2yoKfIRGEBSjfOqQFO4iKD7owk+gSciFxFkNB+yPP4g=='

Node.JS

var crypto = require('crypto');

var secret = 'PYPd1Hv4J6';
var message = '1515928475.417'
var key = Buffer(secret, 'base64');

var hmac = crypto.createHmac('sha512', key);
var hmac_result = hmac.update(message).digest('base64');
console.log(hmac_result)

Result (Node.JS 6.11)

m6Z/FxI492VXKDc16tO5XDNvty0Tmv0b1uksSbiwh87+4rmg43hEXM0WmWzkTP3aXB1s5rhm05Hu3g70GTrdEQ==
like image 892
cakel Avatar asked Jan 29 '23 20:01

cakel


1 Answers

Your input keys are different, so the outputs will be different.

Node:

var secret = 'PYPd1Hv4J6';
var message = '1515928475.417'
var key = Buffer(secret, 'base64'); // buffer of bytes from the base64-encoded string 'PYPd1Hv4J6'
                                    //  <Buffer 3d 83 dd d4 7b f8 27>

Python:

secret = 'PYPd1Hv4J6'
message = '1515928475.417'
key = base64.b64encode(secret.encode('utf-8')) # did you mean b64decode here?
like image 54
Jacob Krall Avatar answered Mar 05 '23 04:03

Jacob Krall