5.22. Performing Low-Level Encryption and Decryption with OpenSSL


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


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);



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:


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


Buffer into which any output is placed.


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


Buffer containing the data to be encrypted.


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

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.