Skip to content
yutils
Example

Input (message + key)

Message: GET /api/orders
Key: secret-key-1234

Output (HMAC-SHA256)

3f8b2a4c1d9e7b6f5a2c8d4e1b9f6a3c7d2e8b5a4f1c9d6e3b8a5d2c9f6e3b1a

Note

HMAC is a keyed hash — requires both message and key. Without the key, you can't recreate the hash, so integrity AND authenticity are guaranteed.

Usage / FAQ

When to use

  • Sign API requests — AWS Signature V4, Stripe / GitHub webhooks
  • Verify that a webhook payload genuinely came from the sender
  • Learn how JWT HS256 works — it's HMAC-SHA256 under the hood
  • Detect tampering — without the key, an attacker can't re-sign
  • Validate the integrity of security tokens (CSRF tokens, session IDs)

FAQ

Q.HMAC vs plain hash?
A.SHA-256(message) can be reproduced by anyone — forgeable. HMAC-SHA256(message, key) requires the key, so only key-holders can sign. Use HMAC when you need to know who sent the message.
Q.How long should the key be?
A.For SHA-256 based HMAC, ≥32 bytes (256 bits) is recommended. Shorter keys are auto-padded but reduce the security margin. Never hard-code keys in client code.
Q.Do I need constant-time comparison?
A.Yes. Plain `==` comparison on the server is vulnerable to timing attacks — attackers can guess character by character via response time. Use `crypto.timingSafeEqual` or equivalent.
Fun facts
  • HMAC's core insight is that naively keying a hash — `hash(key || message)` — is forgeable. SHA-1/SHA-256/MD5 all use Merkle–Damgård construction and are vulnerable to length-extension attacks. HMAC's ipad/opad double-hash cleanly blocks the whole class.

    Wikipedia — Length extension attack
  • HMAC originated in Mihir Bellare, Ran Canetti, and Hugo Krawczyk's 1996 CRYPTO paper 'Keying Hash Functions for Message Authentication,' and was standardized in 1997 as RFC 2104. IPsec, TLS, and JWT's HS256 all descend from it.

    RFC 2104 (1997)
  • HMAC verification must use a constant-time compare (`crypto.timingSafeEqual`, etc.). `===` or `strcmp` leaks a timing side-channel proportional to the matching prefix length — measurable even across the network. The 2009 Keyczar vulnerability (Lawson) is the canonical case study.

    Wikipedia — Timing attack