Hash-based Message Authentication Code Implementation
To implement HMAC using SHA-256 hash function
Observe how small changes in message affect the resulting MAC
Ensuring data integrity and authenticity
HMAC (Hash-based Message Authentication Code) is a message authentication mechanism based on cryptographic hash functions like SHA-256.
Message hasn't been tampered with
Message came from someone who knows the secret key
HMAC combines a secret key, a message, and a cryptographic hash function (e.g., SHA-256):
This construction ensures resistance to length-extension and collision attacks, unlike simple H(key || message).
from Crypto.Hash import HMAC, SHA256
# Secret key
key = b'secretkey123'
# Messages
msg1 = b'GECBHARUCH'
msg2 = b'GECBharuch' # Slightly different
# Generate HMAC using SHA-256
hmac1 = HMAC.new(key, msg1, SHA256).hexdigest()
hmac2 = HMAC.new(key, msg2, SHA256).hexdigest()
print("HMAC of msg1:", hmac1)
print("HMAC of msg2:", hmac2)
HMAC of msg1: 1ea6242d27ef42d9b686ef9ad0f71ba49c5ed48b70d344a5e4da3625dcb2d641 HMAC of msg2: d6025e3bd35aac9aac30e7643d778ddc75414efce655df9e96d67675bb91c708
| Feature | Description |
|---|---|
| Secure | Resistant to length-extension, collision attacks, and key-recovery |
| Preferred | Over simple hashing (hash(key + msg)), which is insecure |
| Used in | TLS, SSH, APIs (e.g., AWS signing), JWT authentication |
| Key Management | Key must be secret; exposure compromises security |
| Feature | HMAC (SHA-256) | CBC-MAC | CMAC |
|---|---|---|---|
| Based On | Hash function | Block cipher (AES) | Block cipher (AES) |
| Secure for | Variable-length messages | Fixed-length or prefixed messages | Variable-length messages |
| Collision Safe | Yes | No (if misused) | Yes |
| Common Uses | APIs, TLS, JWT, emails | Legacy systems | IPsec, Bluetooth |
Securing transaction messages
Verifying requests using shared secret keys
Ensuring tokens haven't been tampered with
Ensuring downloaded files are genuine
Preventing spoofing or tampering
| Concept | Explanation |
|---|---|
| HMAC | A MAC based on a hash function and a secret key |
| SHA-256 | A secure hash algorithm used within the HMAC |
| Key Role | Key is required to compute and verify the MAC |
| Use Case | To verify that a message is authentic and unaltered |
After this practical, students will be able to:
Grasp the role of HMAC in securing messages
See how HMAC responds to message and key changes
Differentiate HMAC from other MACs like CBC-MAC