TL;DR
This guide shows you how to check if a ciphertext message hasn’t been tampered with using a Message Authentication Code (MAC). We’ll cover generating the MAC, verifying it upon receipt, and what to do if verification fails.
Generating & Verifying a MAC
- Choose a MAC Algorithm: Common choices include HMAC-SHA256 or HMAC-SHA512. The stronger the algorithm, generally the more secure (but also potentially slower).
- Shared Secret Key: You and the sender must agree on a secret key beforehand. This is crucial! Keep it safe – don’t share it in emails or public places.
- Generate the MAC (Sender Side): Before sending the ciphertext, the sender calculates its MAC using the shared secret key and the chosen algorithm.
# Example using Python with HMAC-SHA256 import hmac hash_object = hmac.new(b'your_secret_key', msg=ciphertext.encode(), digestmod='sha256') mac = hash_object.hexdigest() print(mac)The sender sends both the ciphertext and the MAC to the receiver.
- Verify the MAC (Receiver Side): The receiver recalculates the MAC using the same secret key and algorithm, but with the received ciphertext.
- Compare MACs: The receiver compares the calculated MAC with the received MAC.
- If they match: The ciphertext is likely authentic – it hasn’t been altered in transit.
- If they don’t match: The ciphertext has been tampered with, or the wrong secret key was used. Do not trust the message!
# Example using Python with HMAC-SHA256
import hmac
hash_object = hmac.new(b'your_secret_key', msg=received_ciphertext.encode(), digestmod='sha256')
calculated_mac = hash_object.hexdigest()
print(calculated_mac)
What to do if Verification Fails
- Check Key Agreement: Double-check that you and the sender are using the exact same shared secret key. A single character difference will cause a mismatch.
- Resend Message: Ask the sender to resend the message, ensuring they haven’t accidentally modified it before sending.
- Investigate Potential Attacks: If repeated failures occur, consider whether your communication channel might be compromised (e.g., man-in-the-middle attack).
Important Considerations
- Key Management: Securely storing and distributing the shared secret key is paramount. Consider using a key exchange protocol like Diffie-Hellman for automatic key generation if possible.
- Algorithm Strength: Choose an algorithm appropriate for your security needs. SHA256 or SHA512 are generally considered secure, but stay updated on cryptographic best practices.
- MAC vs. Encryption: A MAC only provides integrity and authenticity; it doesn’t provide confidentiality (it doesn’t hide the message content). You typically use a MAC in addition to encryption for complete security.

