6.18. Making Encryption and Message Integrity Work Together

Problem

You need to encrypt data and ensure the integrity of your data at the same time.

Solution

Use either an encryption mode that performs both encryption and message integrity checking, such as CWC mode, or encrypt data with one secret key and use a second key to MAC the encrypted data.

Discussion

Unbelievably, many subtle things can go wrong when you try to perform encryption and message integrity checking in tandem. This is part of the reason encryption modes such as CWC and CCM are starting to appear, both of which perform encryption and message integrity checking together, and they are still secure (such modes are compared in Recipe 5.4, and CWC is discussed in Recipe 5.10). However, if you’re not willing to use one of those encryption modes, follow these guidelines to ensure security:

  • Use two separate keys, one for encryption and one for MAC’ing.

  • Encrypt first, then MAC the ciphertext.

We recommend encrypting, then MAC’ing the ciphertext (the encrypt-then-authenticate paradigm; see Figure 6-4) because other approaches aren’t always secure.

The encrypt-then-authenticate paradigm

Figure 6-4. The encrypt-then-authenticate paradigm

For example, if you’re using a stream-based mode such as CTR (discussed in Recipe 5.9), or if you’re using CBC mode (Recipe 5.6), you will still have a good design if you use a MAC to authenticate the plaintext, then encrypt both the ...

Get Secure Programming Cookbook for C and C++ now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.