简体   繁体   中英

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?

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

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'))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM