πŸ”

HMAC Generator

Generate HMAC (Hash-based Message Authentication Code) signatures for message authentication and data integrity verification. Supports SHA-256, SHA-384, SHA-512, and more.

Security
Loading tool...

How to Use HMAC Generator

How to Use HMAC Generator

Getting Started

HMAC (Hash-based Message Authentication Code) is a cryptographic technique that combines a secret key with a hash function to create a signature. It verifies both the authenticity and integrity of a message.

Basic HMAC Generation

  1. Enter Message: Type or paste the message to sign

    • Can be any text: API requests, JSON payloads, files
    • Message can be any length
    • Supports plain text, JSON, XML, etc.
    • HMAC output length depends only on algorithm, not message
  2. Enter Secret Key: Your private signing key

    • Keep this secret - never share publicly
    • Longer keys are more secure (32+ bytes recommended)
    • Can include any characters
    • Same key needed for verification
    • Key length shown in characters and bits
  3. Select Hash Algorithm: Choose cryptographic hash function

    • SHA-256: Standard for most uses ⭐ (recommended)
    • SHA-384: Enhanced security ⭐ (stronger)
    • SHA-512: Maximum security ⭐ (strongest)
    • SHA-1: Legacy only (deprecated, weak)
    • MD5: Legacy only (deprecated, very weak)
  4. Choose Output Format: How signature is encoded

    • Hexadecimal: Lowercase hex (most common)
    • Base64: Compact text encoding
    • Base64 URL-Safe: For use in URLs (no special chars)
  5. View HMAC Signature: Generated automatically

    • Updates in real-time as you type
    • Copy to clipboard with one click
    • Shows signature length and format
    • Use this signature to verify message later

Features

Real-Time Generation

Instant Updates:

  • HMAC generated as you type
  • No "Generate" button needed
  • See results immediately
  • Updates when changing algorithm or encoding

Live Feedback:

  • Current signature length displayed
  • Algorithm information shown
  • Encoding format confirmed
  • Key length in characters and bits

Multiple Hash Algorithms

SHA-256 (Recommended):

  • Output: 256 bits (64 hex chars)
  • Security: High - industry standard
  • Speed: Fast
  • Use for: APIs, webhooks, JWT, general use
  • Status: Widely supported, trusted

SHA-384 (Enhanced):

  • Output: 384 bits (96 hex chars)
  • Security: Very high
  • Speed: Moderate
  • Use for: Sensitive data, financial applications
  • Status: Strong, recommended for important data

SHA-512 (Maximum):

  • Output: 512 bits (128 hex chars)
  • Security: Very high - maximum available
  • Speed: Moderate
  • Use for: Critical security, blockchain, long-term protection
  • Status: Strongest option

SHA-1 (Deprecated):

  • Output: 160 bits (40 hex chars)
  • Security: Weak - known vulnerabilities
  • Use for: Legacy compatibility only
  • Status: NOT recommended for new systems
  • Warning: Tool shows deprecation warning

MD5 (Deprecated):

  • Output: 128 bits (32 hex chars)
  • Security: Very weak - broken algorithm
  • Use for: Non-security purposes only
  • Status: NOT recommended for security
  • Warning: Tool shows deprecation warning

Output Encoding Options

Hexadecimal:

  • Most common format
  • Lowercase letters (a-f) and numbers (0-9)
  • Easy to read and debug
  • Example: a3f5b2c8d1e4f6a7b9c0d2e3f4a5b6c7
  • Use for: APIs, logs, general purposes

Base64:

  • Compact representation
  • Contains A-Z, a-z, 0-9, +, /, =
  • Shorter than hex (smaller payloads)
  • Example: o/WyyNHk9qe5wNLj9KW2xw==
  • Use for: HTTP headers, JSON, space-constrained

Base64 URL-Safe:

  • Modified Base64 for URLs
  • Replaces + with -, / with _, removes =
  • Safe in URLs without encoding
  • Example: o_WyyNHk9qe5wNLj9KW2xw
  • Use for: URL parameters, file names

Show/Hide Secret Key

Privacy Protection:

  • Secret key hidden by default (password field)
  • Click eye icon to reveal
  • Click again to hide
  • Protects from shoulder surfing
  • Never display in screenshots

Copy Functionality

One-Click Copy:

  • Copy button next to output
  • Copies entire HMAC signature
  • Visual confirmation ("Copied!")
  • Confirmation disappears after 2 seconds
  • Paste into your application

Example Data

Pre-filled Examples:

  • Simple message
  • API request signing
  • JSON payload verification
  • Long message handling

Load Example:

  • Click example button
  • Fills message and secret automatically
  • Sets recommended algorithm
  • Ready to see HMAC immediately

Privacy & Security

Client-Side Processing:

  • All HMAC generation in browser
  • No server communication
  • Data never leaves your device
  • Complete privacy guaranteed

No Storage:

  • Messages not saved
  • Secret keys not stored
  • HMAC not logged
  • Clear on page refresh

Understanding HMAC

What is HMAC?

Definition: HMAC = Hash-based Message Authentication Code

Purpose:

  • Authentication: Verify message came from holder of secret key
  • Integrity: Detect if message was tampered with
  • Non-repudiation: Sender cannot deny sending (with key control)

How it Works:

  1. Combine secret key with message
  2. Apply hash function (SHA-256, etc.)
  3. Output is the HMAC signature
  4. Receiver repeats process with same key
  5. If signatures match, message is authentic and unmodified

Formula:

HMAC(K, m) = H((K βŠ• opad) || H((K βŠ• ipad) || m))
  • K = secret key
  • m = message
  • H = hash function
  • opad, ipad = padding constants
  • || = concatenation
  • βŠ• = XOR operation

HMAC vs Other Methods

HMAC vs Digital Signatures (RSA, ECDSA):

  • HMAC: Symmetric (same key for signing and verifying)
  • Digital Signatures: Asymmetric (private key signs, public key verifies)
  • HMAC: Faster, simpler
  • Digital Signatures: Non-repudiation, key distribution easier
  • HMAC: Both parties need secret key
  • Digital Signatures: Only signer needs private key

HMAC vs Plain Hash (SHA-256):

  • Plain hash: No key, anyone can compute
  • HMAC: Requires secret key, only key holders can create
  • Plain hash: Verifies integrity only
  • HMAC: Verifies both integrity and authenticity
  • Plain hash: Not secure against active attackers
  • HMAC: Secure message authentication

HMAC vs Encryption:

  • HMAC: Does NOT hide message content
  • Encryption: Hides message content
  • HMAC: Verifies authenticity
  • Encryption: Provides confidentiality
  • Combine both: Encrypt-then-MAC for complete security

Security Properties

Collision Resistance:

  • Hard to find two messages with same HMAC
  • Depends on underlying hash function
  • SHA-256: No known practical collisions

Preimage Resistance:

  • Cannot find message from HMAC alone
  • One-way function
  • Cannot reverse HMAC to get original

Key-Dependent:

  • Without key, cannot create valid HMAC
  • Even with message and HMAC, cannot derive key
  • Key must remain secret

Length Extension Attack:

  • Plain hashes vulnerable to this
  • HMAC construction prevents this attack
  • Safe to use even with length extension concerns

Common Use Cases

API Request Signing

Workflow:

  1. Client creates API request
  2. Client generates HMAC of request with secret key
  3. Client sends request + HMAC signature (usually in header)
  4. Server receives request + signature
  5. Server generates HMAC with same key
  6. Server compares signatures
  7. If match, request is authentic; otherwise, reject

Example:

Request: GET /api/users?id=123&timestamp=1234567890
Secret: api-secret-key-2024
HMAC: a3f5b2c8d1e4f6a7b9c0d2e3f4a5b6c7

HTTP Header:
X-Signature: a3f5b2c8d1e4f6a7b9c0d2e3f4a5b6c7

Benefits:

  • Prevents unauthorized API access
  • Detects tampered requests
  • No password in request
  • Can include timestamp to prevent replay attacks

Webhook Verification

Services Using HMAC:

  • GitHub: X-Hub-Signature-256
  • Stripe: Stripe-Signature
  • Slack: X-Slack-Signature
  • Shopify: X-Shopify-Hmac-Sha256

Verification Process:

  1. Service sends webhook to your endpoint
  2. Service includes HMAC in header
  3. Your server receives payload + HMAC
  4. Your server computes HMAC with shared secret
  5. Your server compares computed vs received HMAC
  6. If match, webhook is from legitimate service

Why Important:

  • Anyone can send HTTP requests to your webhook
  • Without HMAC, attacker could send fake webhooks
  • HMAC proves webhook came from legitimate service
  • Prevents webhook spoofing attacks

Example (GitHub):

POST /webhook
X-Hub-Signature-256: sha256=abc123...

Verify:
1. Get shared secret from GitHub settings
2. Compute HMAC-SHA256 of request body with secret
3. Compare with X-Hub-Signature-256 header
4. Process webhook only if match

JWT Token Signing

HS256 Algorithm:

  • JWT signed with HMAC-SHA256
  • Header + Payload + Signature
  • Signature = HMAC(secret, header + payload)

Structure:

eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9  # Header (Base64)
.
eyJzdWIiOiIxMjM0IiwibmFtZSI6IkpvaG4ifQ  # Payload (Base64)
.
a3f5b2c8d1e4f6a7b9c0d2e3f4a5b6c7  # Signature (HMAC)

Security:

  • Anyone can read header and payload (just Base64)
  • Only holder of secret can create valid signature
  • Server verifies signature before trusting token
  • Prevents token tampering

Secure Cookies

Cookie Signing:

  1. Create cookie value
  2. Generate HMAC of value with secret
  3. Store value + HMAC in cookie
  4. When reading cookie, verify HMAC
  5. Reject if HMAC invalid (tampered)

Example:

Cookie: session=user123; signature=a3f5b2c8...

Server verification:
1. Extract session value and signature
2. Compute HMAC of session value
3. Compare with stored signature
4. Trust session only if signatures match

Benefits:

  • Prevents session hijacking
  • Detects cookie tampering
  • Stateless session validation
  • No database lookup needed

Data Integrity Checking

File Verification:

  1. Compute HMAC of file with secret key
  2. Store HMAC separately
  3. Later, recompute HMAC
  4. If HMAC matches, file unmodified

Database Records:

  • Add HMAC column to sensitive tables
  • Compute HMAC of record data
  • Verify HMAC before using data
  • Detect unauthorized database modifications

Backup Validation:

  • Generate HMAC of backup file
  • Store HMAC in separate location
  • Before restoring, verify HMAC
  • Ensures backup not corrupted or tampered

Security Best Practices

Secret Key Management

Key Length:

  • Minimum: Same length as hash output
    • SHA-256: 32 bytes (256 bits)
    • SHA-512: 64 bytes (512 bits)
  • Recommended: Longer is better
  • Use cryptographically random generation

Key Generation:

// Good: Cryptographically random
const crypto = require('crypto')
const secret = crypto.randomBytes(32).toString('hex')

// Bad: Predictable
const secret = 'password123'

Key Storage:

  • βœ“ Environment variables
  • βœ“ Secrets management systems (AWS Secrets Manager, HashiCorp Vault)
  • βœ“ Encrypted configuration files
  • βœ“ Hardware Security Modules (HSM)
  • ❌ Hardcoded in source code
  • ❌ Version control (Git)
  • ❌ Client-side code
  • ❌ Logs or error messages

Key Rotation:

  • Rotate keys regularly (quarterly or annually)
  • Support multiple keys during transition
  • Version keys to track which was used
  • Revoke old keys after migration complete

Algorithm Selection

Recommended Algorithms:

  1. HMAC-SHA256: Default choice for most applications
  2. HMAC-SHA384: Enhanced security needs
  3. HMAC-SHA512: Maximum security, long-term protection

Avoid These:

  • ❌ HMAC-MD5: Broken, multiple vulnerabilities
  • ❌ HMAC-SHA1: Deprecated, collision attacks exist

Migration Path: If currently using weak algorithm:

  1. Add support for new algorithm (SHA-256+)
  2. Accept both old and new during transition
  3. Update all clients to new algorithm
  4. Remove support for old algorithm

Verification Best Practices

Constant-Time Comparison:

// Bad: Timing attack vulnerable
if (receivedHMAC === computedHMAC) { ... }

// Good: Constant-time comparison
const crypto = require('crypto')
if (crypto.timingSafeEqual(
  Buffer.from(receivedHMAC),
  Buffer.from(computedHMAC)
)) { ... }

Why This Matters:

  • Simple string comparison stops at first difference
  • Attacker can measure response time
  • Gradually guess correct HMAC byte-by-byte
  • Constant-time comparison prevents this leak

Always Verify:

  • Never trust data without HMAC verification
  • Reject invalid HMACs immediately
  • Log verification failures (security monitoring)
  • Rate limit to prevent brute force attacks

Replay Attack Prevention

Include Timestamp:

Message: request_data + timestamp
HMAC: HMAC(secret, request_data + timestamp)

Server Validation:

  1. Verify HMAC as usual
  2. Check timestamp is recent (within 5 minutes)
  3. Reject old timestamps
  4. Optional: Track used HMACs (nonce)

Why Important:

  • Attacker could capture valid request + HMAC
  • Replay same request later
  • Timestamp ensures freshness
  • Prevents replay attacks

Combining with Encryption

Encrypt-then-MAC Pattern:

  1. Encrypt plaintext β†’ ciphertext
  2. Compute HMAC of ciphertext
  3. Send ciphertext + HMAC

Why This Order:

  • MAC covers encrypted data
  • Detects tampering before decryption
  • Prevents padding oracle attacks
  • Industry best practice

Bad Pattern (MAC-then-Encrypt):

  • Encrypt (plaintext + MAC)
  • MAC not visible without decryption
  • Cannot detect tampering before decrypt
  • Vulnerable to attacks

Troubleshooting

HMAC Verification Fails

Common Causes:

  1. Wrong Secret Key

    • Most common issue
    • Even one character difference fails
    • Check for typos, spaces, case sensitivity
  2. Different Message

    • Message must be exactly the same
    • Check whitespace, line endings, encoding
    • JSON: Key order matters (unless normalized)
  3. Different Algorithm

    • Must use same algorithm for signing and verifying
    • SHA-256 HMAC β‰  SHA-512 HMAC
  4. Different Encoding

    • Hex vs Base64 produces different strings
    • Convert to same encoding before comparing
  5. Character Encoding Issues

    • UTF-8 vs ASCII vs Latin-1
    • Special characters may encode differently
    • Normalize to UTF-8

Debugging Steps:

  1. Log the message being signed
  2. Log the secret key length (not the key itself!)
  3. Log the algorithm used
  4. Log the encoding format
  5. Compare with expected values
  6. Use test cases with known outputs

Different HMAC Than Expected

Checklist:

  • βœ“ Same message (byte-for-byte)
  • βœ“ Same secret key
  • βœ“ Same algorithm (SHA-256 vs SHA-512)
  • βœ“ Same encoding (hex vs base64)
  • βœ“ No extra whitespace or line breaks
  • βœ“ Correct character encoding (UTF-8)

Test with Known Values:

Message: "Hello, World!"
Secret: "my-secret-key"
Algorithm: HMAC-SHA256
Expected (hex): 2d711642b726b04401627ca9fbac32f5c8530fb1903cc4db02258717921a4881

If your result differs, check each parameter

Advanced Topics

HMAC Construction Details

Two-Pass Structure:

HMAC(K, m) = H(K_outer || H(K_inner || m))

Where:
- K_outer = K βŠ• opad (outer padding)
- K_inner = K βŠ• ipad (inner padding)
- opad = 0x5c repeated
- ipad = 0x36 repeated

Why Two Passes:

  • Prevents length extension attacks
  • Mixes key material thoroughly
  • Proven secure construction
  • Standardized in RFC 2104

Key Derivation

If Secret Too Short:

  • Hash it first to get full-length key
  • Example: K = SHA-256("short-secret")

If Secret Too Long:

  • Hash it to reduce to hash output length
  • Example: K = SHA-256("very-long-secret-key...")

Ideal:

  • Use properly generated random key
  • Length equal to hash output
  • SHA-256: 32 bytes
  • SHA-512: 64 bytes

HMAC in Standards

Defined In:

  • RFC 2104: Original HMAC specification
  • FIPS 198-1: Federal standard
  • ISO/IEC 9797-2: International standard

Used By:

  • TLS/SSL: MAC in encrypted connections
  • IPsec: Packet authentication
  • SSH: Session authentication
  • OAuth: Signature method

Compliance:

  • PCI DSS: Required for payment data
  • HIPAA: Recommended for healthcare
  • GDPR: Data integrity measures
  • SOC 2: Security controls

Quick Reference

Algorithm Selection Guide

Use CaseRecommendedAlternativeAvoid
API authenticationSHA-256SHA-384MD5, SHA-1
Webhook verificationSHA-256SHA-512SHA-1
JWT signingSHA-256SHA-384MD5
Cookie signingSHA-256SHA-512MD5, SHA-1
File integritySHA-512SHA-256MD5, SHA-1
BlockchainSHA-512SHA-256SHA-1

Security Checklist

βœ“ Use SHA-256 or stronger (SHA-384, SHA-512) βœ“ Secret key length β‰₯ hash output length βœ“ Generate keys with cryptographic RNG βœ“ Store keys securely (env vars, secrets manager) βœ“ Never expose keys in client code or URLs βœ“ Use constant-time comparison for verification βœ“ Include timestamp to prevent replay attacks βœ“ Rotate keys regularly (quarterly/annually) βœ“ Log verification failures for monitoring βœ“ Test HMAC generation and verification together

Common Commands

Generate Random Secret (Unix/Linux):

openssl rand -hex 32

Generate HMAC (Command Line):

echo -n "message" | openssl dgst -sha256 -hmac "secret"

Verify HMAC:

# Generate
HMAC=$(echo -n "message" | openssl dgst -sha256 -hmac "secret" | cut -d' ' -f2)

# Compare
if [ "$HMAC" = "expected_value" ]; then
  echo "Valid"
fi

Frequently Asked Questions

Related Utility Tools

Share Your Feedback

Help us improve this tool by sharing your experience

We will only use this to follow up on your feedback