Main question
I have the following short piece of legacy code that I am trying to port from Python (with just standard lib) to JavaScript - from the name of the methods I assume it creates a SHA-1 digest of the abc
string
import hashlib
import hmac
print(hmac.new(b"abc", None, hashlib.sha1).hexdigest())
I searched for how to do that in the browser in JS and found the following code in the Mozilla documentation
var msgUint8 = new TextEncoder().encode('abc');
var hashBuffer = await crypto.subtle.digest('SHA-1', msgUint8);
var hashArray = Array.from(new Uint8Array(hashBuffer));
var hashHex = hashArray.map(b => b.toString(16).padStart(2, '0')).join('');
console.log(hashHex)
the problem is, they yield two completely different results, and I have no idea why:
cc47e3c0aa0c2984454476d061108c0b110177ae
- Pythona9993e364706816aba3e25717850c26c9cd0d89d
- JavaScript
I tried comparing the bytes of b"abc"
with what new TextEncoder().encode('abc')
returns and they are exactly the same: 0x61 0x62 0x63
, so the problem lies somewhere else and I have no idea where.
I need the JavaScript code to return what the Python code returns. Any ideas?
Additionally
My final goal is to actually port this code (note the b"hello"
instead of None
):
print(hmac.new(b"abc", b"hello", hashlib.sha1).hexdigest())
so if you have an idea on that one too - I would hugely appreciate it!