Back to cheatsheets
Cryptography
HMAC Signing
Generate HMAC-SHA256/384/512 signatures with secret keys for message authentication.
What you'll learn
- HMAC-SHA256 sign
- HMAC verify (constant-time)
How to use these snippets
- Click the Copy button next to any snippet to copy it to your clipboard.
- Paste the code into your project, IDE, or terminal.
- Replace placeholder values (like
example.comoryour-secret) with your actual data. - Review the code comments for important security notes and caveats.
- Try the interactive related tool to see the concept in action.
Code Snippets
Copy-paste code snippets
2 ready-to-use snippets for hmac signing. Click copy and paste into your project.
HMAC-SHA256 sign
async function hmacSign(key, message) {
const enc = new TextEncoder();
const cryptoKey = await crypto.subtle.importKey(
'raw', enc.encode(key),
{ name: 'HMAC', hash: 'SHA-256' }, false, ['sign']
);
const sig = await crypto.subtle.sign(
'HMAC', cryptoKey, enc.encode(message)
);
return btoa(String.fromCharCode(...new Uint8Array(sig)));
}
HMAC verify (constant-time)
async function hmacVerify(key, message, expectedSig) {
const sig = await hmacSign(key, message);
// Constant-time comparison
if (sig.length !== expectedSig.length) return false;
let diff = 0;
for (let i = 0; i < sig.length; i++) {
diff |= sig.charCodeAt(i) ^ expectedSig.charCodeAt(i);
}
return diff === 0;
}
Tool
Related ShieldX tool
Try this concept hands-on with the interactive tool.
100% Free · No signup · No cost
Generate something unguessable right now
148 bits of entropy, a crack-time estimate you can trust, and a clipboard that clears itself after 30 seconds.
Part of the Toolly ecosystem · secure.toolly.site