✍️

HMAC

HMAC (Hash-based Message Authentication Code) is a cryptographic mechanism that combines a hash function (like SHA-256) with a shared secret key to generate an authentication code. It guarantees that a message wasn't altered and comes from who it claims to be.

Examples

  • HMAC-SHA256('message', 'key123') → a3f5e8d9c1b2...
  • Signed JWT: eyJhbGci... (header + payload + HMAC-SHA256)
  • Stripe Webhook: X-Stripe-Signature: t=timestamp,v1=hmac
  • AWS API request: Authorization: AWS4-HMAC-SHA256 Credential=...
  • Express signed cookie: session=s%3A...; Signature=hmac_value

FAQ

What's the difference between HMAC and a simple hash?

A simple hash (SHA-256, MD5) is public: anyone can calculate it. HMAC requires a secret key, so only those with the key can generate or verify the code. This prevents forgeries.

Does HMAC encrypt data?

No. HMAC only verifies integrity and authenticity. The message travels in clear text. If you need confidentiality, combine HMAC with encryption (e.g., encrypt-then-MAC with AES + HMAC).

Can I truncate an HMAC to save space?

Yes, but carefully. HMAC-SHA256 can be truncated to 128 bits without losing too much security (NIST recommends minimum 80 bits). Never go below 64 bits or you expose yourself to brute-force attacks.