HMAC (Hash-based Message Authentication Code) is a construction for creating a message authentication code using a cryptographic hash function combined with a secret key. It provides both integrity verification and authentication of the message.
HMAC(K, m) = H((K' XOR opad) || H((K' XOR ipad) || m))
Where:
- H = Hash function (SHA-256, etc.)
- K = Secret key
- K' = Key padded to block size
- opad = 0x5c repeated
- ipad = 0x36 repeated
- m = Message
import hmac
import hashlib
# Create HMAC
key = b"secret_key"
message = b"data to authenticate"
mac = hmac.new(key, message, hashlib.sha256).hexdigest()
# Verify HMAC (use constant-time comparison!)
received_mac = "..."
expected_mac = hmac.new(key, message, hashlib.sha256).hexdigest()
if hmac.compare_digest(received_mac, expected_mac):
print("Valid!")
// HMAC: Provides authentication, NOT confidentiality
// Anyone can read the message, but only key holder can create valid MAC
// For confidentiality + authenticity:
// Use authenticated encryption (AES-GCM) or Encrypt-then-MAC