Created
September 8, 2021 13:00
-
-
Save thechriswalker/a3380b7a24d3f8dc39bc9424048b91f0 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
{ | |
async function hmac_sha256(key, str) { | |
// encode the string key as bytes using UTF8 encoding. | |
const keyBytes = new TextEncoder().encode(key); | |
// generate a key for use in signing with HMAC-SHA256 | |
const secretKey = await crypto.subtle.importKey( | |
"raw", keyBytes, | |
{ name: "HMAC", hash: "SHA-256" }, | |
false, ['sign'] | |
); | |
const messageBytes = new TextEncoder().encode(str); | |
// create the raw signature | |
const signature = await crypto.subtle.sign( | |
"HMAC", | |
secretKey, | |
messageBytes | |
); | |
// and encode to HEX | |
return new Uint8Array(signature).reduce((hex, byte) => hex + (byte < 16 ? "0": "") + byte.toString(16), ""); | |
} | |
// example: | |
const input = `{"processing_id":"123","status":"ok","result":[]}`; | |
const secret = 'foobarbaz'; | |
hmac_sha256(secret, input).then( | |
signature => console.log("Signature:", signature), | |
error => console.error(error) | |
); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment