Générateur HMAC
Générez des signatures HMAC avec les algorithmes SHA-256, SHA-384 et SHA-512
What is HMAC?
HMAC (Hash-based Message Authentication Code) is a cryptographic mechanism that combines a secret key with a hash function to produce an authentication tag for a message. Defined in RFC 2104, HMAC provides both data integrity verification and message authentication — guaranteeing that a message has not been altered in transit and that it originated from a party holding the shared secret key. Unlike plain hash functions that only detect accidental corruption, HMAC protects against deliberate tampering by an attacker who does not possess the secret key.
The HMAC construction works by applying the hash function twice with different padding derived from the key:
HMAC(K, m) = H((K' ⊕ opad) || H((K' ⊕ ipad) || m)), where K' is the key padded or hashed
to the block size, opad is the outer padding (0x5c repeated), and ipad is the inner padding (0x36 repeated).
This nested structure prevents length-extension attacks that affect naive constructions like
H(key || message).
HMAC vs Plain Hash Functions
A plain cryptographic hash function like SHA-256 takes a message and produces a fixed-size digest. Anyone can compute the hash of any message — there is no secret involved. This makes plain hashes suitable for integrity checks (detecting accidental corruption) but useless for authentication. An attacker who intercepts a message can simply recompute the hash after modifying the payload.
HMAC solves this by incorporating a secret key into the computation. Only parties who possess the key can generate or verify the correct HMAC tag. This transforms a hash function into a message authentication code (MAC) — a cryptographic primitive that provides:
- Authentication: Proves the sender holds the shared secret key. Without the key, an attacker cannot forge a valid HMAC tag for any message.
- Integrity: Any modification to the message (even a single bit flip) produces a completely different HMAC output, making tampering immediately detectable.
- Replay protection: When combined with timestamps or nonces, HMAC prevents attackers from reusing previously captured valid message-tag pairs.
The plain hash-generator tool on this site computes unkeyed digests (SHA-256, SHA-512, etc.)
for file integrity verification and content addressing. This HMAC tool adds the critical secret key
dimension — use it whenever you need to prove who produced a digest, not just what
was digested.
HMAC in API Authentication and Webhook Verification
HMAC is the backbone of request signing in modern APIs. Services like AWS (Signature Version 4), Stripe, GitHub, Shopify, and Twilio use HMAC-SHA-256 to authenticate webhook deliveries and API requests. The typical flow is:
- The service provider and consumer share a secret key during integration setup.
- When sending a webhook or API request, the sender computes
HMAC-SHA-256(secret, requestBody)and attaches the result in a header (e.g.,X-Hub-Signature-256for GitHub). - The receiver recomputes the HMAC using the same secret and the received body, then compares signatures using a constant-time comparison to prevent timing attacks.
- If signatures match, the request is authentic. If they differ, the request is rejected as potentially forged.
This pattern eliminates the need for TLS client certificates or OAuth token exchange for server-to-server communication. The secret never travels over the wire — only the computed HMAC tag is transmitted, making the system secure even if an attacker observes the traffic (assuming TLS protects against replay).
AWS Signature Version 4 extends this further by signing a canonical request string that includes the HTTP method, path, query parameters, headers, and a hashed payload — binding the HMAC to every aspect of the request to prevent parameter manipulation.
Secret Key Management for HMAC
The security of HMAC depends entirely on the secrecy and strength of the key. A weak or compromised key renders all HMAC computations meaningless — an attacker with the key can forge valid tags for arbitrary messages. Follow these best practices for HMAC key management:
- Key length: Use keys at least as long as the hash output (32 bytes for HMAC-SHA-256, 64 bytes for HMAC-SHA-512). RFC 2104 recommends keys no shorter than the hash output length. Shorter keys reduce security; longer keys are hashed down to the block size internally.
- Key generation: Generate keys using a cryptographically secure random number generator (
crypto.getRandomValues()in browsers,crypto.randomBytes()in Node.js). Never use predictable values like timestamps, user IDs, or sequential counters as HMAC keys. - Key rotation: Rotate secrets periodically and immediately upon suspected compromise. Maintain a grace period where both old and new keys are accepted to avoid service disruption during rotation.
- Storage: Store HMAC secrets in environment variables, secret managers (AWS Secrets Manager, HashiCorp Vault), or hardware security modules (HSMs). Never commit secrets to source control or embed them in client-side code.
- Constant-time comparison: When verifying HMAC tags, always use constant-time comparison functions (e.g.,
crypto.timingSafeEqual()in Node.js) to prevent timing side-channel attacks that could leak information about the expected tag byte by byte.
Choosing the Right HMAC Algorithm
HMAC can be instantiated with any cryptographic hash function. The choice of underlying hash determines the output size, performance characteristics, and security margin:
- HMAC-SHA-256: The most widely used variant. Produces a 256-bit (32-byte) tag. Required by AWS Signature V4, GitHub webhooks, Stripe signatures, and most modern APIs. Provides 128-bit security against forgery — sufficient for all current applications.
- HMAC-SHA-384: Produces a 384-bit tag. Used in TLS 1.3 cipher suites and environments requiring NIST Suite B compliance. Slightly slower than SHA-256 on 32-bit platforms but faster on 64-bit systems due to SHA-512 internals.
- HMAC-SHA-512: Produces a 512-bit tag. Maximum security margin (256-bit forgery resistance). Preferred for long-term secret protection and high-security environments. Often faster than SHA-256 on 64-bit processors because SHA-512 operates on 64-bit words natively.
- HMAC-SHA-1: Deprecated for new applications. While HMAC-SHA-1 remains theoretically secure (HMAC's security does not require collision resistance), migration to SHA-256 is recommended for defense in depth and compliance requirements.
This tool supports HMAC-SHA-256, HMAC-SHA-384, and HMAC-SHA-512 via the Web Crypto API
(SubtleCrypto), ensuring all computations run locally in your browser with
hardware-accelerated cryptographic primitives — no data is sent to any server.
Code Examples
Computing HMAC-SHA-256 with Web Crypto API
// Generate HMAC-SHA-256 using SubtleCrypto (browser & Node.js 20+)
async function computeHmac(secret, message) {
const encoder = new TextEncoder();
// Import the secret key for HMAC signing
const cryptoKey = await crypto.subtle.importKey(
'raw',
encoder.encode(secret),
{ name: 'HMAC', hash: 'SHA-256' },
false,
['sign']
);
// Compute the HMAC signature
const signature = await crypto.subtle.sign(
'HMAC',
cryptoKey,
encoder.encode(message)
);
// Convert ArrayBuffer to hex string
return Array.from(new Uint8Array(signature))
.map(b => b.toString(16).padStart(2, '0'))
.join('');
}
// Example: Verify a GitHub webhook signature
const secret = 'whsec_your_webhook_secret';
const payload = '{"action":"push","ref":"refs/heads/main"}';
const hmac = await computeHmac(secret, payload);
// → "a1b2c3d4e5f6..." (64-char hex string)Verifying webhook signatures with constant-time comparison (Node.js)
import { createHmac, timingSafeEqual } from 'node:crypto';
function verifyWebhookSignature(payload, signature, secret) {
const expected = 'sha256=' + createHmac('sha256', secret)
.update(payload, 'utf8')
.digest('hex');
// Constant-time comparison prevents timing attacks
if (expected.length !== signature.length) return false;
return timingSafeEqual(
Buffer.from(expected),
Buffer.from(signature)
);
}
// Usage with Express middleware
app.post('/webhooks/github', (req, res) => {
const sig = req.headers['x-hub-signature-256'];
const valid = verifyWebhookSignature(req.body, sig, process.env.WEBHOOK_SECRET);
if (!valid) return res.status(401).send('Invalid signature');
// Process webhook...
});Standards & Specifications
- RFC 2104 — Original HMAC specification defining the keyed-hash message authentication code construction
- RFC 4868 — Specifies HMAC-SHA-256, HMAC-SHA-384, and HMAC-SHA-512 for use in IPsec and other protocols
- FIPS 198-1 — NIST standard for HMAC — mandated for US government applications requiring message authentication
Questions Fréquentes
What is HMAC and how is it different from a regular hash?
HMAC (Hash-based Message Authentication Code) is a cryptographic hash that uses a secret key. Unlike regular hashes, HMAC requires both the data and a secret key to generate the signature. This makes it useful for verifying both data integrity and authenticity—only someone with the secret key can generate a valid HMAC.
Which HMAC algorithm should I use?
HMAC-SHA256 is the most commonly used and provides excellent security for most applications. HMAC-SHA384 and HMAC-SHA512 offer stronger security with longer output but are slightly slower. For API authentication, webhooks, and JWT signing, HMAC-SHA256 is the standard choice.
What's the difference between hex and base64 output?
Both formats represent the same HMAC value, just encoded differently. Hex uses 0-9 and a-f characters and is twice as long as the raw bytes. Base64 uses A-Z, a-z, 0-9, +, and / characters and is more compact. Use hex for readability and debugging, base64 for APIs and when space matters.
How do I verify an HMAC signature?
To verify an HMAC, generate a new HMAC using the same input data and secret key, then compare it to the received signature. If they match exactly, the data is authentic and hasn't been tampered with. Never compare HMACs using string comparison that could leak timing information in production systems.
Can someone reverse an HMAC to get my secret key?
No, HMAC is cryptographically secure and cannot be reversed to reveal the secret key or original data. However, weak or short keys can be vulnerable to brute-force attacks. Always use strong, random secret keys of at least 32 characters (256 bits) for production systems.
Is my data and secret key sent to a server?
No, all HMAC generation happens entirely in your browser using the Web Crypto API. Your input data and secret key never leave your device. This ensures complete privacy and security for sensitive information.
What are common use cases for HMAC?
HMAC is widely used for API authentication (signing requests), webhook verification (GitHub, Stripe), JWT token signing, message authentication in protocols, and verifying data integrity in distributed systems. It's the standard way to prove that data came from someone who knows the secret key.