What is an HMAC?
HMAC stands for Hash-based Message Authentication Code. It is a specific type of message authentication code involving a cryptographic hash function (like SHA-256) combined with a secret cryptographic key.
When two parties share a secret key, HMACs allow them to verify both the data integrity and the authenticity of a message. If a hacker intercepts a message and modifies the payload, the HMAC signature will completely change. Because the hacker does not possess the secret key, they cannot generate a new, valid signature for their tampered payload.
How to generate an HMAC in JavaScript
If you need to implement webhook verification or API signing in your own Node.js or browser application, you should use the native Web Crypto API. Here is the framework-free approach:
async function generateHMAC(secret, payloadStr) {
const encoder = new TextEncoder();
// 1. Import the raw secret key
const key = await crypto.subtle.importKey(
"raw",
encoder.encode(secret),
{ name: "HMAC", hash: "SHA-256" },
false,
["sign"]
);
// 2. Sign the payload to generate the buffer
const signatureBuffer = await crypto.subtle.sign(
"HMAC",
key,
encoder.encode(payloadStr)
);
// 3. Convert buffer to Hex string
const hashArray = Array.from(new Uint8Array(signatureBuffer));
return hashArray.map(b => b.toString(16).padStart(2, '0')).join('');
}