GeneratePass
HMAC AUTHENTICATION CODE

HMAC Generator

Generate HMAC authentication codes using SHA-256, SHA-384, or SHA-512.

About HMAC

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.

Educational Diagram

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

Example 1: Signing an API Webhook Payload
1

Enter the webhook payload: {"event":"payment.received","amount":99.99}

2

Enter a secret key: my-webhook-secret-key-2024

3

Select HMAC-SHA-256 algorithm.

4

The tool generates the HMAC signature to include in the X-Hub-Signature header.

Resulta3f2b8c9d1e4f5a6b7c8d9e0f1a2b3c4d5e6f7a8b9c0d1e2f3a4b5c6d7e8f9a0
Example 2: Comparing HMAC Algorithm Output Lengths
1

Enter the same message and key for all three algorithms.

2

HMAC-SHA-256 produces 64 hex characters.

3

HMAC-SHA-384 produces 96 hex characters.

4

HMAC-SHA-512 produces 128 hex characters.

ResultSHA-256: 64 chars | SHA-384: 96 chars | SHA-512: 128 chars
Example 3: Key Sensitivity Demonstration
1

Sign the message 'Hello' with key 'secret1'.

2

Sign the same message with key 'secret2'.

3

The two HMACs share no resemblance despite identical messages.

4

This demonstrates that HMAC security depends entirely on key secrecy.

ResultDifferent keys produce completely different HMACs for the same message.

Code Examples

JavaScriptWeb Crypto API — HMAC-SHA-256
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);
PythonPython — HMAC Verification
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

AlgorithmOutput (hex chars)Key Size (recommended)Security Level
HMAC-SHA-2566432 bytes (256 bits)128-bit
HMAC-SHA-3849648 bytes (384 bits)192-bit
HMAC-SHA-51212864 bytes (512 bits)256-bit

HMAC vs Plain Hash vs Digital Signature

PropertyPlain HashHMACDigital Signature
IntegrityYesYesYes
AuthenticityNoYes (shared secret)Yes (public key)
Non-repudiationNoNoYes
Key requirementNoneShared secretPrivate key
PerformanceFastestFastSlower
Use caseChecksumsAPI auth, webhooksCertificates, 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

01

Signing API webhook payloads to verify they originate from a trusted source and have not been tampered with.

02

Generating authentication tokens for OAuth 2.0 and OpenID Connect identity providers.

03

Creating message authentication codes for secure inter-service communication in microservices architectures.

04

Verifying the integrity of software updates by comparing HMAC signatures against trusted keys.

05

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

Fundamentals

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.

Technical Deep Dive

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.

Practical Applications

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.

Security Pitfalls

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 Tools

Related Cryptographic Tools

Explore these cryptographic tools for authentication and data integrity:

Frequently Asked Questions

What is the difference between HMAC and a regular hash?
A regular hash can be computed by anyone with access to the data. HMAC requires a secret key, providing authentication in addition to integrity. Only parties who know the secret key can generate or verify the HMAC, making it suitable for verifying data origin.
How long should an HMAC secret key be?
For HMAC-SHA256, a key of at least 256 bits (32 bytes) is recommended. Longer keys do not improve security since the hash output length limits the effective security. Always generate keys using a cryptographically secure random number generator.
Can HMAC be used for password hashing?
While HMAC can be used for password hashing, it is not recommended. HMAC is designed for message authentication, not password storage. Use dedicated password hashing algorithms like Argon2, bcrypt, or scrypt, which include salting and key stretching to resist brute-force attacks.
Which HMAC algorithm should I choose?
HMAC-SHA256 is the most commonly used and recommended for most applications. HMAC-SHA384 and HMAC-SHA512 provide additional security margins but are rarely necessary. Choose based on your security requirements and any regulatory or compliance standards you must follow.
Is HMAC vulnerable to quantum computers?
Current quantum computers do not threaten HMAC security. Quantum algorithms like Grover's algorithm can speed up hash preimage attacks, but this only reduces the effective security by half. HMAC-SHA256 would still provide 128-bit security against quantum attacks, which remains sufficient for most applications.