Tutorial 2.10: Message Authentication Codes (MACs)

Table of Contents

Learning Objectives

After completing this tutorial, you should be able to:

Overview

Encryption provides confidentiality—it prevents unauthorized parties from reading the content of a message. However, encryption alone does not protect against tampering. An adversary can modify ciphertext, and the resulting plaintext may be altered in ways the receiver cannot detect. To ensure that a message has not been modified and that it originated from the claimed sender, we need message authentication.

Message Authentication Codes (MACs) provide both data integrity and data origin authentication. A MAC is a short piece of information (a "tag") that is generated from a message and a secret key. Anyone who possesses the secret key can verify the integrity and authenticity of the message. Without the secret key, an adversary cannot generate a valid MAC for a message (even if they have seen other message-MAC pairs).

In this tutorial, we explore the theory and practice of MACs. We begin by defining MACs and their security properties. We then examine the major MAC constructions: HMAC (Hash-based MAC), which uses cryptographic hash functions; CMAC (Cipher-based MAC), which uses block ciphers; and Poly1305, a fast MAC often used with stream ciphers. We discuss the security of MACs against various attacks and the importance of key management.

We also explore how MACs are used in authenticated encryption schemes, where confidentiality and integrity are combined. We analyze the different approaches (Encrypt-then-MAC, MAC-then-Encrypt, Encrypt-and-MAC) and their security implications. Finally, we examine real-world applications of MACs in protocols such as TLS, IPsec, and SSH.

Relationship to the Tutorial Series

In Tutorial 2.9, we studied cryptographic hash functions. HMAC builds on hash functions to provide message authentication. In Tutorials 2.4–2.7, we studied symmetric encryption. CMAC and other MACs can be built from block ciphers. Tutorials 2.11–2.15 will cover public-key cryptography, which uses different mechanisms (digital signatures) for authentication and non-repudiation.

Introduction to MACs

Message Authentication Code (MAC)
A MAC is a cryptographic checksum generated from a message M and a secret key K. The MAC tag T = MAC(K, M) is a fixed-size value that provides both data integrity (the message has not been altered) and data origin authentication (the message originated from the holder of the key).

A MAC has the following properties:

┌─────────────────────────────────────────────────────────────────┐ │ MAC GENERATION │ ├─────────────────────────────────────────────────────────────────┤ │ │ │ Message (M) │ │ │ │ │ │ │ │ ├──────────────┐ │ │ │ │ │ │ ▼ ▼ │ │ ┌─────────┐ ┌─────────┐ │ │ │ Key │ │ MAC │ │ │ │ (K) │──►│Algorithm│ │ │ └─────────┘ └────┬────┘ │ │ │ │ │ ▼ │ │ ┌───────────┐ │ │ │ MAC Tag │ │ │ │ (T) │ │ │ └───────────┘ │ │ │ │ Verification: Given M, K, and T, verify if T = MAC(K, M). │ │ │ │ • Without K, cannot compute T for M. │ │ • Provides integrity: any modification to M changes T. │ │ • Provides authentication: only key holder could have │ │ produced T. │ └─────────────────────────────────────────────────────────────────┘

Figure 1: MAC generation and verification.

MAC vs. Digital Signature

FeatureMACDigital Signature
Key typeSymmetric (shared secret)Asymmetric (private/public key pair)
Key distributionRequires secure key sharingPublic keys can be distributed openly
Non-repudiationNo (anyone with the key can create tags)Yes (only the private key holder can sign)
PerformanceFastSlower
Use caseIntegrity and authentication with shared keysAuthentication, non-repudiation, PKI

MAC Security Properties

A secure MAC must satisfy the following properties:

1. Unforgeability (Existential Unforgeability under Chosen Message Attack)

An adversary who has access to an oracle that produces MAC tags for messages of their choosing cannot generate a valid MAC for any message not previously queried (or for a message where they have not seen a valid MAC).

Formal definition: For any probabilistic polynomial-time adversary A with access to a MAC oracle, the probability that A outputs a valid (M, T) pair where M was not queried to the oracle is negligible.

2. Resistance to Verification Oracle Attacks

The adversary should not be able to learn anything useful from a verification oracle (i.e., being told whether a candidate MAC is valid).

3. Key Secrecy

Even with many message-tag pairs, an adversary cannot recover the secret key.

4. Collision Resistance

It should be infeasible to find two different messages with the same MAC under the same key.

Key Insight: The security of a MAC depends on both the strength of the underlying primitive (hash function or block cipher) and the construction. HMAC, for example, is secure even if the underlying hash function is vulnerable to collision attacks (as long as the hash function is still pseudorandom).

HMAC (Hash-based MAC)

HMAC (Hash-based Message Authentication Code) is the most widely used MAC algorithm. It is defined in RFC 2104 and FIPS 198-1. HMAC uses a cryptographic hash function (e.g., SHA-256) and a secret key to produce a MAC tag.

HMAC Construction

HMAC computes the MAC as:

HMAC(K, M) = H((K ⊕ opad) || H((K ⊕ ipad) || M))

Where:

┌─────────────────────────────────────────────────────────────────┐ │ HMAC CONSTRUCTION │ ├─────────────────────────────────────────────────────────────────┤ │ │ │ Step 1: Pad key to block size (B) │ │ K' = K padded with zeros to B bytes │ │ │ │ Step 2: Compute inner hash │ │ inner = H(K' ⊕ ipad || M) │ │ │ │ Step 3: Compute outer hash │ │ HMAC = H(K' ⊕ opad || inner) │ │ │ │ Where: │ │ ipad = 0x36 repeated B times │ │ opad = 0x5C repeated B times │ │ │ │ ┌──────────────────────────────────────────────────────────┐ │ │ │ K'⊕opad ──► H ─────────────────┐ │ │ │ │ ▲ │ │ │ │ │ │ │ │ │ │ │ K'⊕ipad ──► H ──► inner ───────┘ │ │ │ │ ▲ │ │ │ │ │ │ │ │ │ M │ │ │ └──────────────────────────────────────────────────────────┘ │ │ │ └─────────────────────────────────────────────────────────────────┘

Figure 2: HMAC construction.

HMAC Variants

VariantHash FunctionOutput Size (bits)Security (bits)
HMAC-MD5MD5128Deprecated (MD5 broken)
HMAC-SHA1SHA-1160Deprecated (SHA-1 broken)
HMAC-SHA256SHA-256256128 (collision), 256 (preimage)
HMAC-SHA512SHA-512512256 (collision), 512 (preimage)
HMAC-SHA3-256SHA3-256256128 (collision), 256 (preimage)

HMAC Security Properties

HMAC Security Strength

The security strength of HMAC is determined by the smaller of:

  1. The output size of the hash function (providing collision resistance).
  2. The key size (providing brute-force resistance).

For HMAC-SHA256 with a 256-bit key, the security strength is 256 bits for key recovery and 128 bits for forgery (birthday bound).

HMAC Example (Conceptual)
Message: "Hello, World!"
Key: 0x0123456789ABCDEF... (256 bits)
HMAC-SHA256(K, M) = 5f4dcc3b5aa765d61d8327deb882cf99b1a9e3b7bc2f7a...
(Actual computation requires proper implementation; this is illustrative.)

CMAC (Cipher-based MAC)

CMAC (Cipher-based Message Authentication Code) is a MAC algorithm that uses a block cipher (e.g., AES) as its underlying primitive. It is defined in NIST SP 800-38B and is also known as OMAC (One-key MAC).

CMAC Construction

CMAC operates on messages of arbitrary length by:

  1. Padding the message if it is not a multiple of the block size.
  2. Processing each block through the block cipher in CBC-like mode.
  3. Using subkeys derived from the master key for the final block.

The CMAC algorithm uses two subkeys (K₁ and K₂) derived from the master key K:

The message is processed block by block, and the final block is XORed with K₁ or K₂ before the final encryption.

┌─────────────────────────────────────────────────────────────────┐ │ CMAC CONSTRUCTION │ ├─────────────────────────────────────────────────────────────────┤ │ │ │ Input: M (message), K (key) │ │ │ │ 1. Derive subkeys K₁ and K₂ from K. │ │ │ │ 2. If M is a multiple of block size: │ │ M' = M || 0x80... (with padding) │ │ Use K₁ for final block. │ │ Else: │ │ M' = M || 0x80...00 (with padding) │ │ Use K₂ for final block. │ │ │ │ 3. Process M' in CBC-like mode: │ │ for each block except last: │ │ state = state ⊕ block │ │ state = EK(state) │ │ │ │ 4. Final block: │ │ state = state ⊕ (last_block ⊕ Kᵢ) │ │ tag = EK(state) │ │ │ │ 5. Output tag (first n bits, if truncated). │ │ │ └─────────────────────────────────────────────────────────────────┘

Figure 3: CMAC construction.

CMAC Advantages

CMAC with AES

AES-CMAC is widely used in many protocols, including:

Poly1305 and Other MACs

Poly1305

Poly1305 is a fast MAC designed by Daniel J. Bernstein. It is often used with the ChaCha20 stream cipher (ChaCha20-Poly1305) to provide authenticated encryption. Poly1305 is a universal hash function-based MAC.

Poly1305 Key Features:

Poly1305 Algorithm:

  1. Split the message into 16-byte blocks.
  2. Compute a polynomial evaluation modulo 2130-5 using the key as coefficients.
  3. Add a constant (the second part of the key).
  4. Output a 16-byte tag.

Other MAC Algorithms

AlgorithmDescriptionStatus
CBC-MACCipher Block Chaining MACDeprecated (use CMAC instead)
UMACUniversal hash-based MACSecure, less common
VMACVectorized MACSecure, optimized for multimedia
GMACGalois MAC (used in GCM)Secure, part of AES-GCM

Authenticated Encryption with MAC

Authenticated Encryption (AE) combines encryption and authentication into a single operation. There are three common approaches to combining a block cipher (for confidentiality) with a MAC (for authentication).

1. Encrypt-then-MAC (EtM)

The message is first encrypted, then a MAC is computed over the ciphertext.

C = EK1(M)
T = MACK2(C)
Output: C || T

Verification: Receiver verifies the MAC on the ciphertext, then decrypts.

Security: This is the preferred approach because:

2. MAC-then-Encrypt (MtE)

The MAC is computed over the plaintext, then the plaintext and MAC are encrypted together.

T = MACK2(M)
C = EK1(M || T)
Output: C

Verification: Receiver decrypts, extracts the MAC, and verifies it.

Security: This approach is less secure because:

Historically used in SSL/TLS (before TLS 1.3) and SSH.

3. Encrypt-and-MAC (E&M)

The message is both encrypted and MACed separately, and both are sent.

C = EK1(M)
T = MACK2(M)
Output: C || T

Verification: Receiver verifies the MAC on the plaintext (after decryption).

Security: This is the least secure because:

Used in SSH (historically) and some implementations of IPSec.

Recommendation: Encrypt-then-MAC is the recommended approach for combining encryption and authentication. It provides the strongest security guarantees and is used in TLS 1.3 and other modern protocols.

Authenticated Encryption with Associated Data (AEAD)

AEAD modes (like GCM, CCM, ChaCha20-Poly1305) combine encryption and authentication in a single pass. They also support Additional Authenticated Data (AAD)—data that is authenticated but not encrypted (e.g., headers).

AEAD Security: AEAD modes provide both confidentiality and integrity with strong security guarantees. They are recommended for all new systems.

Security Analysis of MACs

Attack Models

Common MAC Attacks

Security Strengths

MAC AlgorithmSecurity Strength (bits)Key Size (bits)
HMAC-SHA256128 (forgery), 256 (key recovery)256
HMAC-SHA512256 (forgery), 512 (key recovery)512
AES-CMAC128 (forgery), 128 (key recovery)128
Poly1305128256

Key Management Considerations

Implementation Considerations

Constant-Time Verification

MAC verification must be constant-time to avoid timing side-channel attacks. The comparison of the computed tag with the provided tag must take the same time regardless of where the mismatch occurs.

Wrong: if (tag == expected_tag) { ... } (short-circuits on mismatch).

Correct: if (timing_safe_compare(tag, expected_tag)) { ... }.

Tag Length

Shorter tags reduce security against forgery attacks. For HMAC-SHA256, using the full 256-bit output is recommended. For some applications, truncation may be acceptable but must be done carefully.

Recommendations:

Key Length

The key should be at least as long as the security strength of the MAC. For HMAC-SHA256, use a 256-bit key. For AES-CMAC, use a 128-bit key (or 256-bit for AES-256).

Nonce Handling (for Randomized MACs)

Some MACs (like Poly1305) require a nonce. The nonce must be unique for each message with the same key. Reusing a nonce can lead to forgery or key recovery.

Standards and Recommendations

Recommendations

Case Studies

Case Study 1: SSL/TLS and MACs

SSL/TLS versions up to 1.2 used MAC-then-Encrypt (MtE) with HMAC. This led to padding oracle attacks like POODLE (2014) and Lucky Thirteen (2013), which exploited the fact that the MAC was verified after decryption, allowing attackers to learn information about the plaintext.

Lesson: MtE is vulnerable to padding oracle attacks. TLS 1.3 switched to AEAD modes (GCM, ChaCha20-Poly1305), which use Encrypt-then-MAC and are immune to these attacks.

Case Study 2: IPsec and MACs

IPsec uses Encrypt-then-MAC in the ESP (Encapsulating Security Payload) protocol. This provides strong security because the MAC is verified before decryption. IPsec supports HMAC-SHA1, HMAC-SHA256, and AES-CMAC.

Lesson: EtM provides better security and is recommended for all protocols.

Case Study 3: Wi-Fi Protected Access (WPA2)

WPA2 uses AES-CCMP, which combines AES-CTR for encryption and AES-CBC-MAC for authentication (CCM mode). The MAC provides integrity and authenticity, and the design uses AEAD, ensuring that the header information is also authenticated.

Case Study 4: The MD5-HMAC Vulnerability

HMAC-MD5 is theoretically secure even though MD5 is broken for collisions. However, HMAC-MD5 is still vulnerable if the key is too short or if the attacker can find collisions in the underlying hash function. Since MD5 is broken, HMAC-MD5 is deprecated for new applications.

Key Takeaways

Section Summaries

Quiz

  1. What is the primary purpose of a Message Authentication Code (MAC)?
  2. AnswerA MAC provides both data integrity (ensuring the message has not been altered) and data origin authentication (verifying that the message originated from the holder of the secret key).
  3. What is the difference between a MAC and a digital signature?
  4. AnswerA MAC uses a symmetric key (shared secret) and does not provide non-repudiation (anyone with the key can create a valid tag). A digital signature uses asymmetric keys (private/public) and provides non-repudiation.
  5. What is the HMAC construction, and why is it secure even if the underlying hash function is vulnerable to collision attacks?
  6. AnswerHMAC uses two nested hashes: H((K ⊕ opad) || H((K ⊕ ipad) || M)). It is secure because it requires the hash function to be pseudorandom, not just collision-resistant. Even if collisions are found, the HMAC remains secure as long as the key is secret.
  7. What are the three approaches to combining encryption and authentication, and which is recommended?
  8. AnswerThe three approaches are Encrypt-then-MAC (EtM), MAC-then-Encrypt (MtE), and Encrypt-and-MAC (E&M). Encrypt-then-MAC is recommended because it provides the strongest security guarantees and avoids padding oracle attacks.
  9. What is CMAC and how does it differ from HMAC?
  10. AnswerCMAC (Cipher-based MAC) uses a block cipher (like AES) as the underlying primitive, whereas HMAC uses a hash function. CMAC is useful when AES is available but SHA is not.
  11. What is the Poly1305 MAC and where is it commonly used?
  12. AnswerPoly1305 is a fast MAC based on universal hashing modulo 2130-5. It is commonly used with the ChaCha20 stream cipher in the ChaCha20-Poly1305 authenticated encryption scheme, which is used in TLS 1.3 and SSH.
  13. Why is constant-time verification important for MACs?
  14. AnswerConstant-time verification prevents timing side-channel attacks. If the comparison of the computed tag with the provided tag takes different times depending on where a mismatch occurs, an attacker could use timing measurements to learn information about the correct tag.
  15. What is the difference between Encrypt-then-MAC and MAC-then-Encrypt in terms of security?
  16. AnswerEncrypt-then-MAC authenticates the ciphertext before decryption, preventing padding oracle attacks. MAC-then-Encrypt does not authenticate before decryption, making it vulnerable to padding oracle attacks.
  17. What is the recommended HMAC variant for new applications?
  18. AnswerHMAC-SHA256 or HMAC-SHA512. HMAC-MD5 and HMAC-SHA1 are deprecated.
  19. What is a verification oracle attack, and how does it relate to MACs?
  20. AnswerA verification oracle attack occurs when an attacker can submit (message, tag) pairs to a system and learn whether the tag is valid. This can be used to forge tags if the MAC is weak or if the system leaks information about the verification.

Exercises

  1. HMAC Construction

    Describe the steps of the HMAC algorithm using SHA-256 as the underlying hash function. What are the values of ipad and opad for SHA-256?

  2. Sample Solution

    HMAC-SHA256 steps:

    1. Pad the key K to 64 bytes (the block size of SHA-256) by appending zeros.
    2. Compute ipad = 0x36 repeated 64 times.
    3. Compute opad = 0x5C repeated 64 times.
    4. Compute inner = SHA-256((K ⊕ ipad) || M).
    5. Compute HMAC = SHA-256((K ⊕ opad) || inner).

    ipad = 0x363636... (64 bytes), opad = 0x5C5C5C... (64 bytes).

  3. MAC Security Strength

    For HMAC-SHA256 with a 128-bit key, what is the effective security strength for key recovery and forgery?

  4. Sample Solution

    Key recovery: 128 bits (limited by the key size).

    Forgery: min(128 bits (key size), 128 bits (birthday bound for collision resistance of SHA-256)) = 128 bits.

    So both key recovery and forgery have 128-bit security.

  5. Encrypt-then-MAC vs. MAC-then-Encrypt

    Explain why Encrypt-then-MAC is considered more secure than MAC-then-Encrypt. Provide an example of a vulnerability that can occur with MAC-then-Encrypt.

  6. Sample Solution

    In Encrypt-then-MAC, the MAC is verified on the ciphertext before decryption. This ensures that any tampering is detected before the data is decrypted, preventing padding oracle attacks.

    In MAC-then-Encrypt, the ciphertext is decrypted first, and then the MAC is verified on the plaintext. If the decryption process reveals whether the padding is valid, an attacker can use this oracle to recover plaintext (padding oracle attack).

    Example: The POODLE attack on SSL/TLS exploited the MAC-then-Encrypt construction to decrypt ciphertext by manipulating the padding.

  7. CMAC Subkeys

    Explain how the subkeys K₁ and K₂ are derived in CMAC. Why are two different subkeys needed?

  8. Sample Solution

    K₁ = EK(0x00...00) · x (multiplication in GF(2128)).

    K₂ = K₁ · x.

    Two subkeys are needed to distinguish between messages that are a multiple of the block size and those that are not. If the message is a multiple of the block size, K₁ is used for the final block. If not, K₂ is used. This ensures that the final block is processed differently depending on the padding, preventing ambiguity.

  9. MAC Forgery Scenario

    Assume an attacker has intercepted a valid (message, tag) pair. What attacks could they attempt, and how does the MAC prevent them?

  10. Sample Solution

    Possible attacks:

    If the attacker has many message-tag pairs, they might try to recover the key. Key recovery is infeasible for a secure MAC (e.g., 2128 or 2256 operations).

Homework

  1. Research: TLS 1.3 Authenticated Encryption

    Research how TLS 1.3 uses authenticated encryption. Write a 500-word report that covers:

  2. Sample Answer

    Complete answer would describe that TLS 1.3 supports AES-GCM, ChaCha20-Poly1305, and AES-CCM. It moved away from CBC-HMAC to eliminate padding oracle vulnerabilities and to simplify the protocol. AAD in TLS 1.3 includes the header information (e.g., record type, version, length) that is authenticated but not encrypted.

  3. MAC Performance Comparison

    Compare the performance of HMAC-SHA256, AES-CMAC, and Poly1305 in software. Write a report that includes:

  4. Sample Answer

    Complete answer would include benchmarks showing Poly1305 is very fast (often 1-2 cycles/byte), HMAC-SHA256 is moderate (5-10 cycles/byte), and AES-CMAC is fast if AES-NI is available. HMAC-SHA256 is suitable for most applications; AES-CMAC is good when AES hardware is available; Poly1305 is excellent when paired with ChaCha20.

  5. Design an Authenticated Encryption Scheme

    Design an authenticated encryption scheme for a communication protocol that uses AES-CTR for confidentiality and HMAC-SHA256 for authentication. Specify:

  6. Sample Answer

    Complete answer would use Encrypt-then-MAC with two keys: Kenc for AES-CTR and Kmac for HMAC. The plaintext is encrypted with AES-CTR using a nonce/counter, then HMAC-SHA256 is computed over the ciphertext and additional data (e.g., sequence number). The receiver verifies the MAC before decrypting. Nonces must be unique per session, and sequence numbers prevent replay attacks. Security is provided by the combination of AES-CTR confidentiality and HMAC integrity/authentication.

  7. Analyze a MAC Vulnerability

    Research the Lucky Thirteen attack on TLS 1.2 (and earlier). Write a 500-word report that explains:

  8. Sample Answer

    Complete answer would explain that Lucky Thirteen is a timing side-channel attack on TLS that exploits the variable time taken to process MAC verification when the padding is invalid. The attacker can measure the response time to distinguish between valid and invalid padding, enabling plaintext recovery. MAC-then-Encrypt is vulnerable because the MAC is verified after decryption. The attack was mitigated by implementing constant-time MAC verification and by transitioning to AEAD modes in TLS 1.3.

  9. Mini-Project: Implement HMAC-SHA256

    Implement HMAC-SHA256 in your preferred programming language (or use a library). Test it with the test vectors from RFC 4231. Write a report on your implementation, including:

  10. Sample Answer

    Complete answer would include source code (or a detailed description), the test results (e.g., HMAC-SHA256("key", "The quick brown fox jumps over the lazy dog") = f7bc83f430538424b13298e6aa6fb143ef4d59a14946175997479dbc2d1a3cd8), and a discussion of how the implementation handles key padding and the two nested hashes.

Summary

This tutorial has provided a comprehensive examination of Message Authentication Codes (MACs) and their role in providing data integrity and data origin authentication. We began by defining MACs and their essential security properties: unforgeability, resistance to verification oracle attacks, and key secrecy.

We examined the major MAC constructions in detail:

We explored how MACs are used in authenticated encryption, analyzing the three approaches: Encrypt-then-MAC (recommended), MAC-then-Encrypt (vulnerable to padding oracle attacks), and Encrypt-and-MAC (least secure). We discussed AEAD modes (GCM, CCM, ChaCha20-Poly1305) which combine encryption and authentication in a single pass.

We analyzed the security of MACs against various attack models (chosen message, verification oracle) and the importance of implementation considerations such as constant-time verification, key length, and tag length. The case studies illustrated how MAC vulnerabilities have been exploited in the wild (POODLE, Lucky Thirteen) and how modern protocols (TLS 1.3) have addressed them.

With this foundation, you are now equipped to select and use MACs appropriately in cryptographic systems, understand their security properties, and recognize the risks associated with improper implementation or use.

Connection to the Next Tutorial

In Tutorial 2.11: Public-Key Cryptography Fundamentals, we will shift from symmetric to asymmetric cryptography. While MACs use symmetric keys, public-key cryptography uses key pairs (public and private) and provides different security services, including non-repudiation and secure key exchange.