Jonathan Ho
Jonathan Ho

Reputation: 11

Javascript HMAC and Python HMAC not returning same hash

I currently have a Javascript code that looks like this

var CryptoJS = require("crypto-js");

var key = "bookbookbook";
var msg = "2020-06-16 20:03:19";

var signature = CryptoJS.HmacSHA1(msg, key);
var checksum = CryptoJS.enc.Utf8.parse(signature);

console.log("checksum: " + CryptoJS.enc.Base64.stringify(checksum));

the checksum is ODNjOWY5NThmYzUxODNkYWM1MjhjZTY3ZTYzYmQxNjE1ZDRkZDQ5Zg==

I tried to convert it to Python

import base64
import time
import hmac
import hashlib

key = "bookbookbook".encode(encoding='utf-8')
msg = "2020-06-16 20:03:19".encode(encoding='utf-8')

digest = hmac.new(key, msg, hashlib.sha1).digest()
checksum = base64.b64encode(digest).decode('utf-8')

print(checksum)

but the checksum returned is this g8n5WPxRg9rFKM5n5jvRYV1N1J8=

How do I make it return the same?

Upvotes: 1

Views: 817

Answers (2)

Jonathan Ho
Jonathan Ho

Reputation: 11

I found the solution. Although I do agree with Kaddath the Javascript sucks, I'm unable to alter it due to the fact that 1) it has been been used and running for several years and 2) I'm doing a port to Python, not fixing/updating the original code and 3) "da bossman" says just port not fix

Here's the Python code that produces the same output:

import base64
import time
import hmac
import hashlib
import binascii

key = "bookbookbook".encode(encoding='utf-8')
msg = "2020-06-16 20:03:19".encode(encoding='utf-8')

digest = hmac.new(key, msg, hashlib.sha1).digest()

checksum = base64.b64encode(binascii.hexlify(bytearray(digest)))
print("checksum: ", checksum.decode('utf-8'))

Upvotes: 0

Kaddath
Kaddath

Reputation: 6151

this step is unnecessary and transforms your data, making the result wrong: var checksum = CryptoJS.enc.Utf8.parse(signature); (Utf8.parse is used to convert an UTF-8 string to wordsArray, but you already have a wordsArray as a result from CryptoJS.HmacSHA1's call)

Your code should be: (took responsability to change variables names to something more proper)

var CryptoJS = require("crypto-js");

var key = "bookbookbook";
var msg = "2020-06-16 20:03:19";

var encrypted = CryptoJS.HmacSHA1(msg, key);

console.log("encrypted in Base64: " + CryptoJS.enc.Base64.stringify(encrypted));

see it in action in a fiddle, you'll see same result as the python code

Upvotes: 1

Related Questions