Hashing and HMAC gives different output in Python and JS

111 Views Asked by At

I am trying to convert a python code That encode a string With HMAC into JS using Crypto JS. But the HMAC string produced in the python and JS COde is different.

Python code

`

import hashlib, json, hmac, secrets

date = "2024-01-16 16:11:11"
nonce = 'ksjdnf5646512'
data = {key:value}
method = 'PATCH'
api = 'api'
content_type = 'application/json'
    
hashed_data = hashlib.sha256(json.dumps(data).encode('utf-8')).digest()
string_to_hash = f"{method}\n{date}\n{api}\n{content_type}\n{nonce}\n{hashed_data}"
hmac_string = str(hmac.new('secretkey'.encode('utf-8'), string_to_hash.encode('utf-8'), hashlib.sha256).hexdigest())

print(json.dumps(data))
print(json.dumps(data).encode('utf-8'))
print(hashlib.sha256(json.dumps(data).encode('utf-8')))
print(string_to_hash)
print(hashed_data)
print(hmac_string)

JS Code

var CryptoJS = require("crypto-js");
date = "2024-01-16 16:11:11"
nonce = 'ksjdnf5646512'
data = {key: value}
method = 'PATCH'
api = 'api'
content_type = 'application/json'
data = JSON.stringify(data)
hashed_data = CryptoJS.SHA256(CryptoJS.enc.Latin1.parse(data))
const string_to_hash = `${method}\n${date}\n${api}\n${content_type}\n${nonce}\n${hashed_data}`;
const hmacString = CryptoJS.enc.Hex.stringify(CryptoJS.HmacSHA256(CryptoJS.enc.Latin1.parse(string_to_hash), CryptoJS.enc.Latin1.parse('secretkey')))
console.log(hmacString)

The HMAC string produced in both codes are different.I need it to be same.

I tried using different encryptions in Crypto JS. I cannot chenge the python code. I can write the JS code as i want. I thik the issue might be due to difference in libraries in python and js

1

There are 1 best solutions below

1
Frank Yellin On

When I set data = {'hello': 100} using both Python and JS, I got the following:

>>> json.dumps(data)
'{"hello": 100}'
> JSON.stringify(data)
'{"hello":100}'

These are not identical strings. Therefore you should not expect them to give you identical results when you run hmac. As already noted above, you should only hmac a string for which you know its exact format.