5.22. Performing Low-Level Encryption and Decryption with OpenSSL

Problem

You have set up your cipher and want to perform encryption and decryption.

Solution

Use the following suite of functions:

int EVP_EncryptUpdate(EVP_CIPHER_CTX *ctx, unsigned char *out, int *outl, 
                      unsigned char *in, int inl);
int EVP_EncryptFinal_ex(EVP_CIPHER_CTX *ctx, unsigned char *out, int *outl);
int EVP_DecryptUpdate(EVP_CIPHER_CTX *ctx, unsigned char *out, int *outl,
                      unsigned char *in, int inl);
int EVP_DecryptFinal_ex(EVP_CIPHER_CTX *ctx, unsigned char *out, int *outl);

Discussion

Warning

As a reminder, use a raw mode only if you really know what you’re doing. For general-purpose use, we recommend a high-level abstraction, such as that discussed in Recipe 5.16. Additionally, be sure to include some sort of integrity validation whenever encrypting, as we discuss throughout Chapter 6.

The signatures for the encryption and decryption routines are identical, and the actual routines are completely symmetric. Therefore, we’ll only discuss the behavior of the encryption functions, and you can infer the behavior of the decryption functions from that.

EVP_EncryptUpdate( ) has the following arguments:

ctx

Pointer to the cipher context previously initialized with EVP_EncryptInit_ex( ).

out

Buffer into which any output is placed.

outl

Pointer to an integer, into which the number of bytes written to the output buffer is placed.

in

Buffer containing the data to be encrypted.

inl

Number of bytes contained in the input buffer. ...

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

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