HMAC (Hash-based Message Authentication Code)

HMAC (Hash-based Message Authentication Code) is a cryptographic construction that combines a secret key with a hash function to produce a message authentication code. For JWTs, HS256 uses HMAC-SHA256: the same secret produces the same signature for the same input, enabling fast verification. Without the secret, producing a valid signature is computationally infeasible when the key has sufficient entropy. HMAC provides integrity and authenticity but not confidentiality. Implementations across Node.js, Python, Go, Ruby, and Java follow the same RFC standards, so concepts transfer directly between stacks. Security reviews should treat this as part of your full authentication threat model, not an isolated configuration detail.

Why It Matters

HMAC is the foundation of symmetric JWT signing. Understanding HMAC helps you reason about secret length requirements, why leaked secrets compromise all historical tokens, and why you must specify the expected algorithm during verification to prevent algorithm confusion attacks. Never roll your own HMAC — use vetted libraries. Getting this wrong often surfaces only after an incident, when forged or replayed tokens expose gaps in validation or secret handling. Platform teams should encode these rules in libraries, linting, and deployment checklists so individual services cannot drift silently. Pair technical controls with monitoring: log verification failures, track unusual token lifetimes, and alert on spikes in 401 responses.

Code Example

Node.js crypto
const crypto = require('crypto');
const secret = 'your-256-bit-secret';
const message = 'header.payload';
const hmac = crypto.createHmac('sha256', secret).update(message).digest('base64url');

Related Terms

Algorithm Guides

Related Tools

Related Articles

Frequently Asked Questions

Is HMAC encryption?

No. HMAC provides integrity and authenticity, not confidentiality. JWT payloads remain readable after base64url decoding. Consult your JWT library documentation for exact option names, defaults, and error types. When in doubt, prefer stricter validation and shorter token lifetimes over permissive shortcuts.

What hash does HS256 use?

SHA-256. HS384 uses SHA-384; HS512 uses SHA-512. All are HMAC constructions with different underlying hash functions. Consult your JWT library documentation for exact option names, defaults, and error types. When in doubt, prefer stricter validation and shorter token lifetimes over permissive shortcuts.

Can HMAC use a public key?

No. HMAC requires a shared symmetric secret. Asymmetric signing uses RSA or ECDSA instead. Consult your JWT library documentation for exact option names, defaults, and error types. When in doubt, prefer stricter validation and shorter token lifetimes over permissive shortcuts.