HMAC Generator
Generate HMAC authentication codes using SHA-256, SHA-384, or SHA-512.
How HMAC works
HMAC (Hash-based Message Authentication Code) combines a cryptographic hash function with a secret key to produce a unique authentication code. It's used to verify both the integrity and authenticity of messages.
Introduction
A hash alone proves integrity — anyone can compute it. HMAC adds a secret key, proving both integrity AND authenticity. This tool generates HMAC authentication codes using HMAC-SHA-256, HMAC-SHA-384, and HMAC-SHA-512. Whether you're signing API webhooks, verifying JWT tokens, or building message authentication for inter-service communication, this is the tool that makes it concrete.
What This Tool Does
An HMAC generator creates Hash-based Message Authentication Codes using the Web Crypto API's subtle.importKey() and subtle.sign() methods. HMAC combines a cryptographic hash with a secret key through a nested construction defined in RFC 2104: HMAC(K, m) = H((K' ⊕ opad) || H((K' ⊕ ipad) || m)). It supports three hash variants: HMAC-SHA-256 (most common), HMAC-SHA-384, and HMAC-SHA-512. The output is a fixed-length hex string whose length depends on the chosen hash algorithm (64, 96, or 128 hex characters).
Why It Matters
HMAC is the foundation of API security. Every webhook signature from Stripe, GitHub, and AWS uses HMAC. JWT tokens are signed with HMAC or digital signatures. TLS uses HMAC in its PRF. Without HMAC, there's no way to verify that a message came from a trusted source and hasn't been modified in transit. Understanding HMAC isn't optional for backend developers — it's essential for building secure APIs and microservices.
How It Works
The Web Crypto API implements HMAC through two steps: key import and signing. First, subtle.importKey() creates a CryptoKey object from the raw secret bytes using the 'HMAC' algorithm and a specified hash (SHA-256, SHA-384, or SHA-512). Then, subtle.sign() computes the HMAC over the message using the imported key. Internally, this follows RFC 2104: the key is padded to the block size (64 bytes for SHA-256/384, 128 bytes for SHA-512), XORed with ipad (0x36) and opad (0x5c), and the hash is computed as H(K' ⊕ opad || H(K' ⊕ ipad || message)). The result is a binary digest converted to hexadecimal for display.
A diagram showing the HMAC nested construction: Secret Key → pad to block size → XOR with ipad (0x36) → append message → SHA-256 hash → XOR key with opad (0x5c) → append inner hash → SHA-256 final hash → HMAC output. Side panel shows the Web Crypto API flow: importKey → sign → hex encoding.
Step-by-Step Examples
Enter the webhook payload: {"event":"payment.received","amount":99.99}
Enter a secret key: my-webhook-secret-key-2024
Select HMAC-SHA-256 algorithm.
The tool generates the HMAC signature to include in the X-Hub-Signature header.
a3f2b8c9d1e4f5a6b7c8d9e0f1a2b3c4d5e6f7a8b9c0d1e2f3a4b5c6d7e8f9a0Enter the same message and key for all three algorithms.
HMAC-SHA-256 produces 64 hex characters.
HMAC-SHA-384 produces 96 hex characters.
HMAC-SHA-512 produces 128 hex characters.
SHA-256: 64 chars | SHA-384: 96 chars | SHA-512: 128 charsSign the message 'Hello' with key 'secret1'.
Sign the same message with key 'secret2'.
The two HMACs share no resemblance despite identical messages.
This demonstrates that HMAC security depends entirely on key secrecy.
Different keys produce completely different HMACs for the same message.Code Examples
async function hmacSHA256(key, message) {
const encoder = new TextEncoder();
// Import the key
const cryptoKey = await crypto.subtle.importKey(
'raw',
encoder.encode(key),
{ name: 'HMAC', hash: 'SHA-256' },
false,
['sign']
);
// Sign the message
const signature = await crypto.subtle.sign(
'HMAC',
cryptoKey,
encoder.encode(message)
);
// Convert to hex
return Array.from(new Uint8Array(signature))
.map(b => b.toString(16).padStart(2, '0'))
.join('');
}
// Usage
const hmac = await hmacSHA256('my-secret-key', 'Hello, World!');
console.log(hmac);import hmac
import hashlib
def verify_hmac(key, message, expected_hmac):
computed = hmac.new(
key.encode(),
message.encode(),
hashlib.sha256
).hexdigest()
return hmac.compare_digest(computed, expected_hmac)
# Usage (constant-time comparison prevents timing attacks)
is_valid = verify_hmac(
'my-secret-key',
'Hello, World!',
'a3f2b8c9...'
)
print("Valid" if is_valid else "Invalid")HMAC Algorithm Comparison
| Algorithm | Output (hex chars) | Key Size (recommended) | Security Level |
|---|---|---|---|
| HMAC-SHA-256 | 64 | 32 bytes (256 bits) | 128-bit |
| HMAC-SHA-384 | 96 | 48 bytes (384 bits) | 192-bit |
| HMAC-SHA-512 | 128 | 64 bytes (512 bits) | 256-bit |
HMAC vs Plain Hash vs Digital Signature
| Property | Plain Hash | HMAC | Digital Signature |
|---|---|---|---|
| Integrity | Yes | Yes | Yes |
| Authenticity | No | Yes (shared secret) | Yes (public key) |
| Non-repudiation | No | No | Yes |
| Key requirement | None | Shared secret | Private key |
| Performance | Fastest | Fast | Slower |
| Use case | Checksums | API auth, webhooks | Certificates, code signing |
Benefits
- Generates HMAC signatures using the Web Crypto API for hardware-accelerated performance.
- Supports three SHA variants (256, 384, 512) for different security requirements.
- Uses the RFC 2104 nested construction for standards-compliant HMAC generation.
- Provides both integrity and authenticity — not just data verification but source verification.
- Client-side operation keeps secret keys in browser memory only.
Use Cases
Signing API webhook payloads to verify they originate from a trusted source and have not been tampered with.
Generating authentication tokens for OAuth 2.0 and OpenID Connect identity providers.
Creating message authentication codes for secure inter-service communication in microservices architectures.
Verifying the integrity of software updates by comparing HMAC signatures against trusted keys.
Building challenge-response authentication protocols that prove knowledge of a shared secret.
Common Mistakes to Avoid
Hardcoding HMAC secret keys in source code repositories where they can be discovered by attackers.
Using the same HMAC key for multiple services, creating a single point of failure if the key is compromised.
Assuming HMAC provides confidentiality — it only guarantees integrity and authenticity, not secrecy.
Comparing HMACs using regular equality operators (===) instead of constant-time comparison, leaking timing information.
Using HMAC for password storage instead of dedicated password hashing algorithms like Argon2 or bcrypt.
Security Implications
HMAC is a fundamental building block of API security, used in webhook verification, JWT signing, and request authentication. A compromised HMAC key allows attackers to forge arbitrary authenticated messages. Key rotation and secure storage are essential — treat HMAC secrets with the same rigor as encryption keys. The nested construction (RFC 2104) provides provable security reduction to the underlying hash function.
Security Information
All computation runs in browser memory using the Web Crypto API. The secret key is never transmitted. HMAC provides message integrity and authenticity — an attacker cannot forge a valid HMAC without knowing the secret key. However, HMAC does not provide confidentiality (the message is not encrypted) or non-repudiation (anyone with the key can create the HMAC).
Best Practices
- Use HMAC-SHA256 as the default for API authentication and webhook verification.
- Keep the secret key confidential — HMAC security depends entirely on key secrecy.
- Use different keys for different purposes to limit the impact of key compromise.
- Rotate HMAC keys periodically and update all consumers before the old key expires.
- Use constant-time comparison when verifying HMACs to prevent timing side-channel attacks.
- Store HMAC keys in a secrets manager or hardware security module, never in source code.
Frequently Asked Questions
References & Further Reading
What is HMAC?
HMAC (Hash-based Message Authentication Code) is a cryptographic construction that combines a hash function with a secret key to produce a unique authentication code. Unlike a plain hash, which anyone can compute, HMAC requires knowledge of the secret key to generate or verify the code. This provides both integrity (the message has not been altered) and authenticity (the message came from someone who knows the key).
HMAC is standardized in RFC 2104 and is used extensively in APIs, secure communications, and data verification. Our tool supports HMAC with SHA-256, SHA-384, and SHA-512, providing flexible options for different security requirements.
The HMAC Algorithm Explained
HMAC works by applying a hash function twice with different keys derived from the secret. The process begins by padding the key to the block size of the hash function. If the key is longer than the block size, it is first hashed to reduce its length. The padded key is then XORed with an inner pad (0x36) and combined with the message to produce an inner hash.
Next, the padded key is XORed with an outer pad (0x5c) and combined with the inner hash to produce the final HMAC value. This two-pass structure provides security against length extension attacks, which affect plain hash constructions. The secret key never appears in the output, making it impossible to recover the key from the HMAC value.
In our implementation, the Web Crypto API handles the HMAC computation using the crypto.subtle.sign method with the "HMAC" algorithm identifier. This ensures the computation is performed using the browser's built-in cryptographic functions, providing security and performance benefits.
Real-World HMAC Use Cases
API Authentication: Many APIs use HMAC to sign requests. The client computes an HMAC of the request parameters using a shared secret key, and the server verifies the signature. This prevents tampering with requests and proves the client possesses the secret key.
Webhooks: Services like GitHub, Stripe, and Slack use HMAC to sign webhook payloads. The recipient verifies the HMAC signature to ensure the payload was sent by the trusted source and has not been modified in transit.
JWT Tokens: JSON Web Tokens use HMAC (HS256, HS384, HS512) for symmetric signing. The token payload is signed with a shared secret, allowing any party with the key to verify the token's integrity.
Data Integrity Verification: HMAC can verify that files or data have not been tampered with during transmission or storage. By computing an HMAC before and after transfer, you can confirm data integrity without revealing the actual data.
Common HMAC Mistakes
Using a Weak Secret Key: The security of HMAC depends entirely on the secrecy and randomness of the key. A short or predictable key (like "secret123") can be brute-forced. Use a cryptographically random key of at least 256 bits for SHA-256 HMAC.
Key Reuse Across Different Purposes: Using the same HMAC key for different applications or protocols reduces security. If one application is compromised, all other applications using the same key are also affected. Use separate keys for different use cases.
Timing Attacks: Comparing HMAC values using regular string comparison (like ===) can leak timing information. Use constant-time comparison functions to prevent attackers from deducing the correct HMAC one character at a time.
Not Including All Relevant Data: The HMAC should cover all data that needs integrity protection. If you omit important fields from the HMAC computation, attackers can modify those fields without detection.
Related Cryptographic Tools
Explore these cryptographic tools for authentication and data integrity:
- SHA-256 Generator — Generate SHA-256 hashes without a secret key.
- SHA Hash Tools — Multi-algorithm hash generation including SHA-1, SHA-256, SHA-384, and SHA-512.
- JWT Decoder — Decode and inspect JSON Web Tokens that use HMAC signing.
- Secret Token Generator — Generate secure keys for HMAC authentication.
- Random Bytes Generator — Generate cryptographically secure random bytes for keys.