Skip to content

Instantly share code, notes, and snippets.

@thechriswalker
Created September 8, 2021 13:00
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save thechriswalker/a3380b7a24d3f8dc39bc9424048b91f0 to your computer and use it in GitHub Desktop.
Save thechriswalker/a3380b7a24d3f8dc39bc9424048b91f0 to your computer and use it in GitHub Desktop.
{
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