What is HMAC?
HMAC (Hash-based Message Authentication Code) is a cryptographic technique that combines a secret key with a hash function to verify both the integrity and authenticity of a message. It ensures that data has not been tampered with and comes from a trusted source.
Quick Facts
| Full Name | Hash-based Message Authentication Code |
|---|---|
| Created | 1996 (RFC 2104) |
| Specification | Official Specification |
How HMAC Works
HMAC was published in 1996 and is defined in RFC 2104. It works by hashing the message twice with the secret key in a specific way, making it resistant to length extension attacks that affect plain hash functions. HMAC can use any cryptographic hash function like SHA-256 or SHA-512. The resulting code is a fixed-size value that changes completely if either the message or key is modified. HMAC is widely used in API authentication, JWT signatures, and secure communication protocols.
Key Characteristics
- Combines secret key with hash function
- Provides both integrity and authenticity
- Resistant to length extension attacks
- Can use any hash function (SHA-256, SHA-512)
- Fixed-size output regardless of input
- Requires shared secret between parties
Common Use Cases
- API request signing
- JWT signature verification
- Webhook payload verification
- Secure cookie signing
- Message authentication in protocols
Example
HMAC Calculation:
Message: "Hello, World!"
Secret Key: "my-secret-key"
Algorithm: HMAC-SHA256
Result: 5f8c9f4e3a2b1c0d9e8f7a6b5c4d3e2f1a0b9c8d7e6f5a4b3c2d1e0f9a8b7c6d
JavaScript (Node.js):
const crypto = require('crypto');
const hmac = crypto.createHmac('sha256', 'my-secret-key');
hmac.update('Hello, World!');
const signature = hmac.digest('hex');
Python:
import hmac
import hashlib
signature = hmac.new(
b'my-secret-key',
b'Hello, World!',
hashlib.sha256
).hexdigest()
API Signature Example:
Timestamp: 1704067200
Method: POST
Path: /api/orders
Body: {"item": "widget"}
String to sign: "1704067200.POST./api/orders.{\"item\":\"widget\"}"
HMAC-SHA256 signature: <calculated_signature>