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.
SecurityHow 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
-
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
-
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
-
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)
-
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)
-
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:
- Combine secret key with message
- Apply hash function (SHA-256, etc.)
- Output is the HMAC signature
- Receiver repeats process with same key
- 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:
- Client creates API request
- Client generates HMAC of request with secret key
- Client sends request + HMAC signature (usually in header)
- Server receives request + signature
- Server generates HMAC with same key
- Server compares signatures
- If match, request is authentic; otherwise, reject
Example:
Request: GET /api/users?id=123×tamp=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:
- Service sends webhook to your endpoint
- Service includes HMAC in header
- Your server receives payload + HMAC
- Your server computes HMAC with shared secret
- Your server compares computed vs received HMAC
- 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:
- Create cookie value
- Generate HMAC of value with secret
- Store value + HMAC in cookie
- When reading cookie, verify HMAC
- 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:
- Compute HMAC of file with secret key
- Store HMAC separately
- Later, recompute HMAC
- 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:
- HMAC-SHA256: Default choice for most applications
- HMAC-SHA384: Enhanced security needs
- 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:
- Add support for new algorithm (SHA-256+)
- Accept both old and new during transition
- Update all clients to new algorithm
- 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:
- Verify HMAC as usual
- Check timestamp is recent (within 5 minutes)
- Reject old timestamps
- 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:
- Encrypt plaintext β ciphertext
- Compute HMAC of ciphertext
- 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:
-
Wrong Secret Key
- Most common issue
- Even one character difference fails
- Check for typos, spaces, case sensitivity
-
Different Message
- Message must be exactly the same
- Check whitespace, line endings, encoding
- JSON: Key order matters (unless normalized)
-
Different Algorithm
- Must use same algorithm for signing and verifying
- SHA-256 HMAC β SHA-512 HMAC
-
Different Encoding
- Hex vs Base64 produces different strings
- Convert to same encoding before comparing
-
Character Encoding Issues
- UTF-8 vs ASCII vs Latin-1
- Special characters may encode differently
- Normalize to UTF-8
Debugging Steps:
- Log the message being signed
- Log the secret key length (not the key itself!)
- Log the algorithm used
- Log the encoding format
- Compare with expected values
- 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 Case | Recommended | Alternative | Avoid |
|---|---|---|---|
| API authentication | SHA-256 | SHA-384 | MD5, SHA-1 |
| Webhook verification | SHA-256 | SHA-512 | SHA-1 |
| JWT signing | SHA-256 | SHA-384 | MD5 |
| Cookie signing | SHA-256 | SHA-512 | MD5, SHA-1 |
| File integrity | SHA-512 | SHA-256 | MD5, SHA-1 |
| Blockchain | SHA-512 | SHA-256 | SHA-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
Temperature Converter
FeaturedConvert temperatures between Celsius, Fahrenheit, and Kelvin instantly with live conversion
Use Tool βUnit Converter
FeaturedConvert between length, weight, and volume units instantly. Support for metric and imperial systems.
Use Tool βWord Counter
FeaturedCount words, characters, sentences, and reading time instantly
Use Tool βArea Converter
FeaturedConvert areas between square feet, square meters, acres, hectares, and square yards instantly
Use Tool βTime Zone Converter
FeaturedConvert between time zones and see current or custom time across different parts of the world
Use Tool βSpeed Converter
FeaturedConvert speeds between miles per hour (MPH), kilometers per hour (KPH), and knots instantly
Use Tool βMinify JavaScript
Minify and compress JavaScript code to reduce file size for production. Remove comments, whitespace, and optimize code for faster loading.
Use Tool βPaper Size Converter
Convert between international paper sizes (A4, Letter, Legal) with dimensions in mm, cm, and inches. Compare ISO A/B series and North American paper standards.
Use Tool βShare Your Feedback
Help us improve this tool by sharing your experience