Online HMAC Generator: Message Authentication Code Explained
What Is HMAC
HMAC (Hash-based Message Authentication Code) is an algorithm that uses a cryptographic hash function and a secret key to verify both the integrity and authenticity of a message.
In simple terms, HMAC is a "keyed hash" — only someone with the same key can generate or verify an HMAC value. Try generating one yourself with our HMAC generator: paste a message and secret key, and the signature appears instantly.
HMAC vs Regular Hashing
| Feature | Regular Hash (e.g., SHA-256) | HMAC |
|---|---|---|
| Input | Message only | Message + Key |
| Verifiable without key | ✅ | ❌ |
| Tamper-resistant | ❌ (anyone can compute) | ✅ (requires key) |
| Typical use | File integrity, password storage | API signing, message auth |
How HMAC Works
The HMAC computation formula (RFC 2104):
HMAC(K, m) = H((K' ⊕ opad) || H((K' ⊕ ipad) || m))
Where:
K= Keym= MessageH= Hash function (e.g., SHA-256)K'= Processed key: hashed first if longer than the hash block size (SHA-256: 64 bytes; SHA-384/512: 128 bytes), zero-padded to block size if shorteropad= Outer padding (0x5c repeated for one block)ipad= Inner padding (0x36 repeated for one block)
Two key design intuitions:
- Why two hashes instead of
H(key || message): the inner and outer pads mix the key into two separate stages of the hash, and the outer hash's input never contains the raw message — which is exactly the structural reason HMAC resists length-extension attacks (details below). - Why over-long keys get hashed first: key bytes beyond the block size would be truncated into "wasted entropy" by padding — a 128-byte key used with 64-byte-block SHA-256 puts its last 64 bytes straight into the XOR, actually reducing effective security. Hashing first normalizes any key length to "at most one block".
HMAC vs Digital Signatures vs KDFs: Which One When
Three primitives that are constantly confused, with completely different jobs:
| HMAC | Digital signature (Ed25519/RSA) | HKDF/PBKDF2 | |
|---|---|---|---|
| Key model | Symmetric (same key signs & verifies) | Asymmetric (private signs, public verifies) | Derives new keys from a secret |
| Proves origin to third parties | ❌ (the verifier can also forge) | ✅ (non-repudiation) | N/A |
| Speed | Very fast (≈ hash speed) | 1–3 orders of magnitude slower | HKDF fast / PBKDF2 deliberately slow |
| Typical use | API signing, webhook verification, JWT HS256 | Code signing, certificates, JWT RS256/EdDSA | Session keys, password storage |
Rule of thumb: both parties trust each other and share a key → HMAC; a third party without the key must verify → digital signature; you already have a high-entropy secret to branch into many keys → HKDF; you only have a password → PBKDF2/argon2. Switch the tool to HKDF mode to try Extract/Expand; see HKDF explained for the theory.
How to Use the Online HMAC Generator
This site's HMAC Generator computes in real time — no button to click; results appear as you type.
HMAC mode
- Set mode to HMAC
- Enter the message in the Message box
- Enter the key in the Secret Key box
- Pick the Output Format (Hex or Base64)
- With Display Mode set to Show All, all five algorithms (MD5 / SHA-1 / SHA-256 / SHA-384 / SHA-512) are computed side by side; choose Show Selected to enable only the ones you need
- Click Copy next to any result
Output length cheat sheet (Hex): MD5 = 32 chars, SHA-1 = 40, SHA-256 = 64, SHA-384 = 96, SHA-512 = 128. Base64 output is roughly 2/3 the length of Hex.
HKDF mode
- Set mode to HKDF (Extract + Expand)
- Enter IKM (high-entropy input keying material; switch input encoding to Hex for RFC vectors)
- Optionally enter Salt / Info (purpose label); set the OKM length in bytes
- The result panel shows PRK (Extract) and OKM (Expand) together
Empty salt/info are valid (RFC 5869: empty salt becomes HashLen zero octets). Do not stretch user passwords with HKDF — that is a slow-KDF job.
Implementation notes
Everything runs locally in your browser: HMAC SHA-1/256/384/512 go through WebCrypto's crypto.subtle.sign('HMAC', ...); MD5, which WebCrypto doesn't support, is implemented manually with spark-md5 following RFC 2104. HKDF mode: Extract is HMAC(salt, IKM); Expand uses deriveBits({ name: 'HKDF', ... }), aligned with RFC 5869 appendix vectors. Message/key/IKM follow the selected encoding; in HMAC mode nothing is computed while either field is empty; an empty key is rejected by WebCrypto. Material stays in localStorage only and is never uploaded.
Common HMAC Use Cases
1. API Request Signing
Many APIs (AWS, Stripe, WeChat Pay) require HMAC-signed requests:
Authorization: HMAC-SHA256 signature=abc123...
The server computes HMAC with the same key over request parameters and compares it to the client-submitted signature to verify the request hasn't been tampered with.
2. Webhook Verification
GitHub, Stripe, and other platforms verify webhooks using 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)
);
}
3. JWT Signing
JWT's HS256 algorithm is essentially HMAC-SHA256:
header.payload.signature
where signature = HMAC-SHA256(base64(header) + "." + base64(payload), secret)
To verify by hand: paste the JWT's header.payload portion verbatim into the HMAC generator message box, enter the signing key, select SHA-256, and the output converted to Base64URL should match the signature segment. For the signing internals and pitfalls like the alg=none attack, see the JWT guide.
4. Message Integrity Verification
When transmitting messages over untrusted networks, appending an HMAC ensures the message hasn't been altered in transit.
HMAC Key Security Best Practices
- Key length: At least 256 bits (32 bytes); use cryptographically secure random generation
- Key storage: Never hardcode in source code; use environment variables or key management services
- Key rotation: Rotate keys periodically and reject requests signed with expired keys
- Timestamp for replay prevention: Include timestamps in signed messages and reject expired ones
Length-extension attacks: why HMAC exists instead of hash(key+data)
Naive MAC constructions break on Merkle–Damgård hashes (SHA-256 included): knowing hash(key || message) lets an attacker compute hash(key || message || suffix) without the key — the length-extension attack. This is not theoretical: it broke real APIs (Flickr's 2009 signature forgery). HMAC's double-hash structure (inner and outer keyed pads) provably resists it. The lesson for implementers: never invent MAC constructions — HMAC-SHA256(key, data) in every standard library is the correct answer, and any code computing sha256(secret + payload) as a "signature" is a vulnerability, not a simplification.
Constant-time comparison: the timing side channel
Comparing the received MAC with the computed one via == or === leaks: string comparison returns false at the first differing byte, and an attacker who can measure response time recovers the correct MAC byte-by-byte (seconds of requests, not years). Every serious library ships a constant-time compare — crypto.timingSafeEqual in Node, hmac.compare_digest in Python, crypto/subtle.timingSafeEqual in browsers. If your webhook handler verifies signatures with ===, fix that today; it is the single most common real-world HMAC bug. Rate-limiting the verification endpoint is the companion control (the attack needs many timed requests).
Replay protection: the MAC says authentic, not fresh
A valid HMAC proves the message came from the key-holder — it says nothing about when. Replay attacks (capture a signed request, send it again) defeat HMAC alone; the standard pattern is to include a timestamp and nonce in the signed payload: HMAC(key, timestamp + nonce + body), reject timestamps outside a five-minute window, track nonces within the window. Stripe's webhook signatures follow exactly this shape. Without the nonce, an attacker inside the time window can still replay; without the timestamp, replay works forever.
FAQ
What's the Difference Between HMAC and Digital Signatures?
HMAC uses symmetric keys (same key for generation and verification); digital signatures use asymmetric keys (private key signs, public key verifies). HMAC is faster but can't prove signature origin to third parties. Choose based on whether non-repudiation is needed.
Which Hash Algorithm Should I Use?
HMAC-SHA256 is the recommended standard. SHA-1 and MD5 are considered insecure and shouldn't be used in new projects.
Can HMAC Prevent Replay Attacks?
Not alone. HMAC only verifies message integrity, not freshness. Combine it with timestamps (timestamp parameter) or nonces to prevent replay attacks.
Are MD5/SHA-1 in the tool still usable?
HMAC's security profile differs from raw hashing: MD5/SHA-1 collision attacks don't apply directly to HMAC (the attacker doesn't hold the key), and HMAC-MD5 has no practical break on record. But both are deprecated, and there's no reason to use them in new projects — they remain in the tool for verifying legacy systems and side-by-side teaching, not for signing new systems.
Related Reading
- JWT Explained: Structure, Signature Verification & Security (HS256 = HMAC-SHA256 in practice)
- SHA-256 Hash Algorithm Explained (the hash primitive under HMAC)
- Hashing vs Encryption: What's the Difference (where MACs sit on this axis)
- HKDF Explained (deriving keys with HMAC)
- Hash Collisions Explained (why MD5/SHA-1 were retired)
A ToolVault engineering note. More free local-first tools at the homepage.
Related Tools
Related Articles
Post-Quantum Migration Self-Check: From Algorithm Inventory to Hybrid TLS — 12 Things to Do in 2026
A practical self-check framework for PQC migration: why three overlapping regulatory timelines make 2026 the starting line, how to build a cryptographic bill of materials (CBOM), ranking by HNDL exposure, enabling X25519+ML-KEM hybrid TLS, and what crypto-agility means in practice. With a 12-item checklist.
Passkeys, Explained: Why the Server Can No Longer Hold a Copy of Your Password
Passkeys (WebAuthn/FIDO2) deepened: registration vs assertion ceremonies, platform authenticators and roaming keys, synced passkeys, how they relate to passwords/TOTP/JWT, and why origin binding makes phishing resistance structural. Servers store public keys only; note that this site has no dedicated Passkey tool page.
ML-KEM, Explained: How Kyber Got Into Your TLS Handshake
An engineering tour of ML-KEM (FIPS 203, formerly Kyber): Kyber-to-standard naming, encapsulate/decapsulate and IND-CCA, the three parameter sizes, how X25519+ML-KEM feeds the TLS 1.3 HKDF schedule, the ClientHello-bloat middlebox trap, OpenSSL 3.5 / nginx enablement, and browser-side implementation boundaries.