5.16. Using a High-Level, Error-Resistant Encryption and Decryption API


You want to do encryption or decryption without the hassle of worrying about choosing an encryption algorithm, performing an integrity check, managing a nonce, and so on.


Use the following “Encryption Queue” implementation, which relies on the reference CWC mode implementation (discussed in Recipe 5.10) and the key derivation function from Recipe 4.11.



Be sure to take into account the fact that functions in this API can fail, particularly the decryption functions. If a decryption function fails, you need to fail gracefully. In Recipe 9.12, we discuss many issues that help ensure robust network communication that we don’t cover here.

This recipe provides an easy-to-use interface to symmetric encryption. The two ends of communication must set up cipher queues in exactly the same configuration. Thereafter, they can exchange messages easily until the queues are destroyed.

This code relies on the reference CWC implementation discussed in Recipe 5.10. We use CWC mode because it gives us both encryption and integrity checking using a single key with a minimum of fuss.

We add a new data type, SPC_CIPHERQ , which is responsible for keeping track of queue state. Here’s the declaration of the SPC_CIPHERQ data type:

typedef struct {
  cwc_t         ctx;
  unsigned char nonce[SPC_BLOCK_SZ];

SPC_CIPHERQ objects are initialized by calling spc_cipherq_setup( ) , which requires the code from

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

O’Reilly members experience live online training, plus books, videos, and digital content from nearly 200 publishers.