jsSHA and Python hashlib give different results for same input

Question:

The following snippets use Nodejs and Python to calculate a hash from the same input content, but they give different results. It’s weird.

// npm install jssha
const jssha = require("jssha");
var s = new jssha("SHA-1", "TEXT");
s.setHMACKey("abc", "TEXT")
s.update("123")
console.log(s.getHMAC("B64"))

The result is vpEGplDt4B9KMf3iOB0G9ftz5hI=

import hmac
import hashlib
import base64

hashed = hmac.new(b"abc", b"TEXT", hashlib.sha1)
hashed.update("123".encode('utf-8'))
print(base64.b64encode(hashed.digest()).decode())

The result is f1/O4xLhhZgwtm6IMAwLDmjzQgg=

Asked By: haolee

||

Answers:

this will get the same hmac as javascript:

import hmac
import hashlib
import base64

hashed = hmac.new(key=b"abc", msg=b"", digestmod=hashlib.sha1)
hashed.update("123".encode('utf-8'))
print(base64.b64encode(hashed.digest()).decode())
# vpEGplDt4B9KMf3iOB0G9ftz5hI=

i do not know anything about this javascript api, but i guess "TEXT" tells javascript how the data/key is encoded.

Answered By: hiro protagonist