HMAC: Message Authentication for Developers
HMAC: Message Authentication for Developers
HMAC (Hash-based Message Authentication Code) proves that a message hasn't been tampered with and was sent by someone who knows the secret key.
What HMAC Does
HMAC takes a message and a secret key, producing a fixed-size tag. The receiver, who also knows the key, recomputes the HMAC and compares. If they match, the message is authentic and unmodified.
How It Works
HMAC(key, message) = Hash((key XOR opad) || Hash((key XOR ipad) || message))
The double-hashing with padded keys prevents length extension attacks that plague plain Hash(key || message).
Common Use Cases
Webhook Verification
Services like Stripe and GitHub sign webhook payloads with HMAC-SHA256:
const crypto = require("crypto");
function verifyWebhook(payload, signature, secret) {
const expected = crypto
.createHmac("sha256", secret)
.update(payload)
.digest("hex");
return crypto.timingSafeEqual(
Buffer.from(signature),
Buffer.from(expected)
);
}
API Authentication
Some APIs use HMAC-signed requests instead of API keys in headers. AWS Signature V4 is a complex example.
JWT Signing
HMAC-SHA256 is the default JWT signing algorithm (HS256). The server creates and verifies tokens using a shared secret.
Cookie Integrity
Sign cookies with HMAC to prevent client-side tampering without encrypting the contents.
Important: Use Constant-Time Comparison
Never compare HMAC tags with ===. Use crypto.timingSafeEqual to prevent timing attacks:
// BAD — vulnerable to timing attack
if (computedHmac === receivedHmac) { ... }
// GOOD — constant-time comparison
if (crypto.timingSafeEqual(Buffer.from(computedHmac), Buffer.from(receivedHmac))) { ... }
Choosing an Algorithm
| Algorithm | Output | Security | Speed |
|-----------|--------|----------|-------|
| HMAC-SHA256 | 32 bytes | Strong | Fast |
| HMAC-SHA384 | 48 bytes | Stronger | Moderate |
| HMAC-SHA512 | 64 bytes | Strongest | Moderate |
HMAC-SHA256 is the standard choice. Use SHA-512 only if you need extra security margin.
Try It
Use our HMAC Generator tool to compute HMAC-SHA256/384/512 tags in your browser using the Web Crypto API.
Conclusion
HMAC is the standard for message authentication. Use it for webhook verification, API signing, and cookie integrity. Always use constant-time comparison and keep your keys secret.