Generating an HMAC in Javascript doesn't match the one generated in python (with utf-8 encoded characters)

Viewed 205

The python server generates the hmac:

dict_payload = {"name": "Emulsión"}
payload = jsonpickle.encode(dict_payload, unpicklable=False)
python_hmac = hmac.new("secret", bytes(payload, "utf-8"), hashlib.sha256,)

returns - 29c7e4b7049a61c24d0f57c402510d6b0c42b15e97981d6ce96b02fdcf913a45

and in node js:

payload = {"name": "Emulsión"}
crypto
    .createHmac("sha256", "secret")
    .update(payload, "utf8")
    .digest("hex");

returns - 61d834992df9a302d8ca1768d4d04be644ba1c35054b342db3ed29f4b2f1e888

seems that in python the ó character was replaced by \u00f3 how to achieve the same in Javascript?

1 Answers

You need to make sure you are dealing with quotes in your input correctly.

payload = {"name": "Emulsión"}
str(payload)

Gives you:

"{'name': 'Emulsión'}"

This is not the same as a json string which has double quotes:

'{"name": "Emulsión"}'

and will lead to a different result. If you ensure your strings are exactly the same, you'll get the same result:

import hmac 
import hashlib

payload = '{"name": "Emulsión"}'
    
python_hmac = hmac.new(b"secret", bytes(payload, "utf-8"), hashlib.sha256,)

python_hmac.hexdigest()

# '61d834992df9a302d8ca1768d4d04be644ba1c35054b342db3ed29f4b2f1e888'
Related