5.17. Performing Block Cipher Setup (for CBC, CFB, OFB, and ECB Modes) in OpenSSL

Problem

You need to set up a cipher so that you can perform encryption and/or decryption operations in CBC, CFB, OFB, or ECB mode.

Solution

Here are the steps you need to perform for cipher setup in OpenSSL, using their high-level API:

  1. Make sure your code includes openssl/evp.h and links to libcrypto (-lcrypto).

  2. Decide which algorithm and mode you want to use, looking up the mode in Table 5-6 to determine which function instantiates an OpenSSL object representing that mode. Note that OpenSSL provides only a CTR mode implementation for AES. See Recipe 5.9 for more on CTR mode.

  3. Instantiate a cipher context (type EVP_CIPHER_CTX).

  4. Pass a pointer to the cipher context to EVP_CIPHER_CTX_init( ) to initialize memory properly.

  5. Choose an IV or nonce, if appropriate to the mode (all except ECB).

  6. Initialize the mode by calling EVP_EncryptInit_ex( ) or EVP_DecryptInit_ex( ) , as appropriate:

    int EVP_EncryptInit_ex(EVP_CIPHER_CTX *ctx, const EVP_CIPHER *type, ENGINE
                           *engine, unsigned char *key, unsigned char *ivornonce);
    int EVP_DecryptInit_ex(EVP_CIPHER_CTX *ctx, const EVP_CIPHER *type, ENGINE
                           *engine, unsigned char *key, unsigned char *ivornonce);
  7. If desired, perform any additional configuration the cipher may allow (see Recipe 5.20).

Discussion

Warning

Use the raw OpenSSL API only when absolutely necessary because there is a huge potential for introducing a security vulnerability by accident. For general-purpose use, ...

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.