Difference between revisions of "EVP Symmetric Encryption and Decryption"

From OpenSSLWiki
Jump to navigationJump to search
(Modified manual links to point to the wiki manual pages)
 
(18 intermediate revisions by 7 users not shown)
Line 1: Line 1:
 +
{{DocInclude
 +
|Name=Symmetric Encryption and Decryption
 +
|Url=http://wiki.openssl.org/index.php/Manual:Evp(3)
 +
|Include=evp.h}}
 +
 
The [[Libcrypto API|libcrypto]] library within OpenSSL provides functions for performing symmetric encryption and decryption operations across a wide range of algorithms and modes. This page walks you through the basics of performing a simple encryption and corresponding decryption operation.
 
The [[Libcrypto API|libcrypto]] library within OpenSSL provides functions for performing symmetric encryption and decryption operations across a wide range of algorithms and modes. This page walks you through the basics of performing a simple encryption and corresponding decryption operation.
  
Line 8: Line 13:
  
 
This page assumes that you know what all of these things mean. If you don't then please refer to [[Basics of Encryption]].
 
This page assumes that you know what all of these things mean. If you don't then please refer to [[Basics of Encryption]].
 +
 +
The complete source code of the following example can be downloaded as [[Media:evp-symmetric-encrypt.c|evp-symmetric-encrypt.c]].
 +
  
 
==Setting it up==
 
==Setting it up==
  
The code below sets up the program. In this example we are going to take a simple message ("The quick brown fox jumps over the lazy dog"), and then encrypt it using a predefined key and IV. In this example the key and IV have been hard coded in - in a real situation you would never do this! Following encryption we will then decrypt the resulting ciphertext, and (hopefully!) end up with the message we first started with. This program expects two functions to be defined: "encrypt" and "decrypt". We will define those further down the page.
+
The code below sets up the program. In this example we are going to take a simple message ("The quick brown fox jumps over the lazy dog"), and then encrypt it using a predefined key and IV. In this example the key and IV have been hard coded in - in a real situation you would never do this! Following encryption we will then decrypt the resulting ciphertext, and (hopefully!) end up with the message we first started with. This program expects two functions to be defined: "encrypt" and "decrypt". We will define those further down the page. Note that this uses the auto-init facility in 1.1.0.
 
 
  
 
  #include <openssl/conf.h>
 
  #include <openssl/conf.h>
Line 19: Line 26:
 
  #include <string.h>
 
  #include <string.h>
 
   
 
   
  int main(int arc, char *argv[])
+
  int main (void)
 
  {
 
  {
  /* Set up the key and iv. Do I need to say to not hard code these in a
+
    /*
    * real application? :-)
+
      * Set up the key and iv. Do I need to say to not hard code these in a
    */
+
      * real application? :-)
 +
      */
 
   
 
   
  /* A 256 bit key */
+
    /* A 256 bit key */
  unsigned char *key = "01234567890123456789012345678901";
+
    unsigned char *key = { 0x30, 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37,
 +
                            0x38, 0x39, 0x30, 0x31, 0x32, 0x33, 0x34, 0x35,
 +
                            0x36, 0x37, 0x38, 0x39, 0x30, 0x31, 0x32, 0x33,
 +
                            0x34, 0x35, 0x36, 0x37, 0x38, 0x39, 0x30, 0x31
 +
                          };
 
   
 
   
  /* A 128 bit IV */
+
    /* A 128 bit IV */
  unsigned char *iv = "01234567890123456";
+
    unsigned char *iv = { 0x30, 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37,
 +
                          0x38, 0x39, 0x30, 0x31, 0x32, 0x33, 0x34, 0x35
 +
                        };
 
   
 
   
  /* Message to be encrypted */
+
    /* Message to be encrypted */
  unsigned char *plaintext =
+
    unsigned char *plaintext =
    "The quick brown fox jumps over the lazy dog";
+
        (unsigned char *)"The quick brown fox jumps over the lazy dog";
 
   
 
   
  /* Buffer for ciphertext. Ensure the buffer is long enough for the
+
    /*
    * ciphertext which may be longer than the plaintext, dependant on the
+
      * Buffer for ciphertext. Ensure the buffer is long enough for the
    * algorithm and mode
+
      * ciphertext which may be longer than the plaintext, depending on the
    */
+
      * algorithm and mode.
  unsigned char ciphertext[128];
+
      */
 +
    unsigned char ciphertext[128];
 
   
 
   
  /* Buffer for the decrypted text */
+
    /* Buffer for the decrypted text */
  unsigned char decryptedtext[128];
+
    unsigned char decryptedtext[128];
 
   
 
   
  int decryptedtext_len, ciphertext_len;
+
    int decryptedtext_len, ciphertext_len;
 
   
 
   
  /* Initialise the library */
+
    /* Encrypt the plaintext */
  ERR_load_crypto_strings();
+
    ciphertext_len = encrypt (plaintext, strlen ((char *)plaintext), key, iv,
  OpenSSL_add_all_algorithms();
+
                              ciphertext);
  OPENSSL_config(NULL);
 
 
   
 
   
  /* Encrypt the plaintext */
+
    /* Do something useful with the ciphertext here */
  ciphertext_len = encrypt(plaintext, strlen(plaintext), key, iv,
+
    printf("Ciphertext is:\n");
    ciphertext);
+
    BIO_dump_fp (stdout, (const char *)ciphertext, ciphertext_len);
 
   
 
   
  /* Do something useful with the ciphertext here */
+
    /* Decrypt the ciphertext */
  printf("Ciphertext is:\n");
+
    decryptedtext_len = decrypt(ciphertext, ciphertext_len, key, iv,
  BIO_dump_fp(stdout, ciphertext, ciphertext_len);
+
                                decryptedtext);
 
   
 
   
  /* Decrypt the ciphertext */
+
    /* Add a NULL terminator. We are expecting printable text */
  decryptedtext_len = decrypt(ciphertext, ciphertext_len, key, iv,
+
    decryptedtext[decryptedtext_len] = '\0';
    decryptedtext);
 
 
   
 
   
  /* Add a NULL terminator. We are expecting printable text */
+
    /* Show the decrypted text */
  decryptedtext[decryptedtext_len] = '\0';
+
    printf("Decrypted text is:\n");
 +
    printf("%s\n", decryptedtext);
 
   
 
   
  /* Show the decrypted text */
 
  printf("Decrypted text is:\n");
 
  printf("%s\n", decryptedtext);
 
 
   
 
   
  /* Clean up */
+
    return 0;
  EVP_cleanup();
 
  ERR_free_strings();
 
 
  return 0;
 
 
  }
 
  }
  
The program sets up a 256 bit key and a 128 bit IV. This is appropriate for the 256-bit AES encryption that we going to be doing in CBC mode. Make sure you use the right key and IV length for the cipher you have selected, or it will go horribly wrong!!
+
The program sets up a 256 bit key and a 128 bit IV. This is appropriate for the 256-bit AES encryption that we going to be doing in CBC mode. Make sure you use the right key and IV length for the cipher you have selected, or it will go horribly wrong!! The IV should be random for CBC mode.
  
 
We've also set up a buffer for the ciphertext to be placed in. It is important to ensure that this buffer is sufficiently large for the expected ciphertext or you may see a program crash (or potentially introduce a security vulnerability into your code). Note: The ciphertext may be longer than the plaintext (e.g. if padding is being used).
 
We've also set up a buffer for the ciphertext to be placed in. It is important to ensure that this buffer is sufficiently large for the expected ciphertext or you may see a program crash (or potentially introduce a security vulnerability into your code). Note: The ciphertext may be longer than the plaintext (e.g. if padding is being used).
Line 85: Line 92:
 
  void handleErrors(void)
 
  void handleErrors(void)
 
  {
 
  {
  ERR_print_errors_fp(stderr);
+
    ERR_print_errors_fp(stderr);
  abort();
+
    abort();
 
  }
 
  }
  
Line 99: Line 106:
 
* Finalising the encryption operation
 
* Finalising the encryption operation
  
During initialisation we will provide an EVP_CIPHER object. In this case we are using EVP_aes_256_cbc(), which uses the AES algorithm with a 256-bit key in [[CBC]] mode. Refer to [[EVP#Working with Algorithms and Modes]] for further details.
+
During initialisation we will provide an EVP_CIPHER object. In this case we are using EVP_aes_256_cbc(), which uses the AES algorithm with a 256-bit key in [[CBC]] mode. Refer to [[EVP#Working with Algorithms and Modes|Working with Algorithms and Modes]] for further details.
  
 
  int encrypt(unsigned char *plaintext, int plaintext_len, unsigned char *key,
 
  int encrypt(unsigned char *plaintext, int plaintext_len, unsigned char *key,
  unsigned char *iv, unsigned char *ciphertext)
+
            unsigned char *iv, unsigned char *ciphertext)
 
  {
 
  {
  EVP_CIPHER_CTX *ctx;
+
    EVP_CIPHER_CTX *ctx;
 
   
 
   
  int len;
+
    int len;
 
   
 
   
  int ciphertext_len;
+
    int ciphertext_len;
 
   
 
   
  /* Create and initialise the context */
+
    /* Create and initialise the context */
  if(!(ctx = EVP_CIPHER_CTX_new())) handleErrors();
+
    if(!(ctx = EVP_CIPHER_CTX_new()))
 +
        handleErrors();
 
   
 
   
  /* Initialise the encryption operation. IMPORTANT - ensure you use a key
+
    /*
    * and IV size appropriate for your cipher
+
      * Initialise the encryption operation. IMPORTANT - ensure you use a key
    * In this example we are using 256 bit AES (i.e. a 256 bit key). The
+
      * and IV size appropriate for your cipher
    * IV size for *most* modes is the same as the block size. For AES this
+
      * In this example we are using 256 bit AES (i.e. a 256 bit key). The
    * is 128 bits */
+
      * IV size for *most* modes is the same as the block size. For AES this
  if(1 != EVP_EncryptInit_ex(ctx, EVP_aes_256_cbc(), NULL, key, iv))
+
      * is 128 bits
    handleErrors();
+
      */
 +
    if(1 != EVP_EncryptInit_ex(ctx, EVP_aes_256_cbc(), NULL, key, iv))
 +
        handleErrors();
 
   
 
   
  /* Provide the message to be encrypted, and obtain the encrypted output.
+
    /*
    * EVP_EncryptUpdate can be called multiple times if necessary
+
      * Provide the message to be encrypted, and obtain the encrypted output.
    */
+
      * EVP_EncryptUpdate can be called multiple times if necessary
  if(1 != EVP_EncryptUpdate(ctx, ciphertext, &len, plaintext, plaintext_len))
+
      */
    handleErrors();
+
    if(1 != EVP_EncryptUpdate(ctx, ciphertext, &len, plaintext, plaintext_len))
  ciphertext_len = len;
+
        handleErrors();
 +
    ciphertext_len = len;
 
   
 
   
  /* Finalise the encryption. Further ciphertext bytes may be written at
+
    /*
    * this stage.
+
      * Finalise the encryption. Further ciphertext bytes may be written at
    */
+
      * this stage.
  if(1 != EVP_EncryptFinal_ex(ctx, ciphertext + len, &len)) handleErrors();
+
      */
  ciphertext_len += len;
+
    if(1 != EVP_EncryptFinal_ex(ctx, ciphertext + len, &len))
 +
        handleErrors();
 +
    ciphertext_len += len;
 
   
 
   
  /* Clean up */
+
    /* Clean up */
  EVP_CIPHER_CTX_free(ctx);
+
    EVP_CIPHER_CTX_free(ctx);
 
   
 
   
  return ciphertext_len;
+
    return ciphertext_len;
 
  }
 
  }
  
Line 143: Line 156:
  
 
Finally we need to define the "decrypt" operation. This is very similar to encryption and consists of the following stages:
 
Finally we need to define the "decrypt" operation. This is very similar to encryption and consists of the following stages:
Encrypting consists of the following stages:
+
Decrypting consists of the following stages:
 
* Setting up a context
 
* Setting up a context
 
* Initialising the decryption operation
 
* Initialising the decryption operation
Line 156: Line 169:
  
 
  int decrypt(unsigned char *ciphertext, int ciphertext_len, unsigned char *key,
 
  int decrypt(unsigned char *ciphertext, int ciphertext_len, unsigned char *key,
  unsigned char *iv, unsigned char *plaintext)
+
            unsigned char *iv, unsigned char *plaintext)
 
  {
 
  {
  EVP_CIPHER_CTX *ctx;
+
    EVP_CIPHER_CTX *ctx;
 
   
 
   
  int len;
+
    int len;
 
   
 
   
  int plaintext_len;
+
    int plaintext_len;
 
   
 
   
  /* Create and initialise the context */
+
    /* Create and initialise the context */
  if(!(ctx = EVP_CIPHER_CTX_new())) handleErrors();
+
    if(!(ctx = EVP_CIPHER_CTX_new()))
 +
        handleErrors();
 
   
 
   
  /* Initialise the decryption operation. IMPORTANT - ensure you use a key
+
    /*
    * and IV size appropriate for your cipher
+
      * Initialise the decryption operation. IMPORTANT - ensure you use a key
    * In this example we are using 256 bit AES (i.e. a 256 bit key). The
+
      * and IV size appropriate for your cipher
    * IV size for *most* modes is the same as the block size. For AES this
+
      * In this example we are using 256 bit AES (i.e. a 256 bit key). The
    * is 128 bits */
+
      * IV size for *most* modes is the same as the block size. For AES this
  if(1 != EVP_DecryptInit_ex(ctx, EVP_aes_256_cbc(), NULL, key, iv))
+
      * is 128 bits
    handleErrors();
+
      */
 +
    if(1 != EVP_DecryptInit_ex(ctx, EVP_aes_256_cbc(), NULL, key, iv))
 +
        handleErrors();
 
   
 
   
  /* Provide the message to be decrypted, and obtain the plaintext output.
+
    /*
    * EVP_DecryptUpdate can be called multiple times if necessary
+
      * Provide the message to be decrypted, and obtain the plaintext output.
    */
+
      * EVP_DecryptUpdate can be called multiple times if necessary.
  if(1 != EVP_DecryptUpdate(ctx, plaintext, &len, ciphertext, ciphertext_len))
+
      */
    handleErrors();
+
    if(1 != EVP_DecryptUpdate(ctx, plaintext, &len, ciphertext, ciphertext_len))
  plaintext_len = len;
+
        handleErrors();
 +
    plaintext_len = len;
 
   
 
   
  /* Finalise the decryption. Further plaintext bytes may be written at
+
    /*
    * this stage.
+
      * Finalise the decryption. Further plaintext bytes may be written at
    */
+
      * this stage.
  if(1 != EVP_DecryptFinal_ex(ctx, plaintext + len, &len)) handleErrors();
+
      */
  plaintext_len += len;
+
    if(1 != EVP_DecryptFinal_ex(ctx, plaintext + len, &len))
 +
        handleErrors();
 +
    plaintext_len += len;
 
   
 
   
  /* Clean up */
+
    /* Clean up */
  EVP_CIPHER_CTX_free(ctx);
+
    EVP_CIPHER_CTX_free(ctx);
 
   
 
   
  return plaintext_len;
+
    return plaintext_len;
 
  }
 
  }
  
==Output==
+
==Ciphertext Output==
  
 
If all goes well you should end up with output that looks like the following:
 
If all goes well you should end up with output that looks like the following:
Line 205: Line 224:
  
 
For further details about symmetric encryption and decryption operations refer to the OpenSSL documentation [[Manual:EVP_EncryptInit(3)]].
 
For further details about symmetric encryption and decryption operations refer to the OpenSSL documentation [[Manual:EVP_EncryptInit(3)]].
 +
 +
==Padding==
 +
 +
OpenSSL uses PKCS padding by default. If the mode you are using allows you to change the padding, then you can change it with <tt>[http://www.openssl.org/docs/man1.0.2/crypto/EVP_CIPHER_CTX_set_padding.html EVP_CIPHER_CTX_set_padding]</tt>. From the man page:
 +
 +
<blockquote>EVP_CIPHER_CTX_set_padding() enables or disables padding. By default encryption operations are padded using standard block padding and the padding is checked and removed when decrypting. If the pad parameter is zero then no padding is performed, the total amount of data encrypted or decrypted must then be a multiple of the block size or an error will occur...
 +
 +
PKCS padding works by adding n padding bytes of value n to make the total length of the encrypted data a multiple of the block size. Padding is always added so if the data is already a multiple of the block size n will equal the block size. For example if the block size is 8 and 11 bytes are to be encrypted then 5 padding bytes of value 5 will be added...
 +
 +
If padding is disabled then the decryption operation will only succeed if the total amount of data decrypted is a multiple of the block size.</blockquote>
 +
 +
==C++ Programs==
 +
 +
Questions regarding how to use the EVP interfaces from a C++ program arise on occasion. Generally speaking, using the EVP interfaces from a C++ program is the same as using them from a C program.
 +
 +
You can download a sample program using EVP symmetric encryption and C++11 called [[Media:Evp-encrypt-cxx.tar.gz|evp-encrypt.cxx]]. The sample uses a custom allocator to zeroize memory, C++ smart pointers to manage resources, and provides a <tt>secure_string</tt> using <tt>basic_string</tt> and the custom allocator. You need to use <tt>g++ -std=c++11 ...</tt> to compile it because of <tt>std::unique_ptr</tt>.
 +
 +
You should also ensure you configure an build with <tt>-fexception</tt> to ensure C++ exceptions pass as expected through C code. And you should avoid other flags, like <tt>-fno-exceptions</tt> and <tt>-fno-rtti</tt>.
 +
 +
The program's <tt>main</tt> simply encrypts and decrypts a string using AES-256 in CBC mode:
 +
 +
<pre>typedef unsigned char byte;
 +
typedef std::basic_string<char, std::char_traits<char>, zallocator<char> > secure_string;
 +
using EVP_CIPHER_CTX_ptr = std::unique_ptr<EVP_CIPHER_CTX, decltype(&::EVP_CIPHER_CTX_free)>;
 +
...
 +
 +
int main(int argc, char* argv[])
 +
{
 +
    // Load the necessary cipher
 +
    EVP_add_cipher(EVP_aes_256_cbc());
 +
 +
    // plaintext, ciphertext, recovered text
 +
    secure_string ptext = "Yoda said, Do or do not. There is no try.";
 +
    secure_string ctext, rtext;
 +
 +
    byte key[KEY_SIZE], iv[BLOCK_SIZE];
 +
    gen_params(key, iv);
 +
 
 +
    aes_encrypt(key, iv, ptext, ctext);
 +
    aes_decrypt(key, iv, ctext, rtext);
 +
   
 +
    OPENSSL_cleanse(key, KEY_SIZE);
 +
    OPENSSL_cleanse(iv, BLOCK_SIZE);
 +
 +
    std::cout << "Original message:\n" << ptext << std::endl;
 +
    std::cout << "Recovered message:\n" << rtext << std::endl;
 +
 +
    return 0;
 +
}</pre>
 +
 +
And the encryption routine is as follows. The decryption routine is similar:
 +
 +
<pre>void aes_encrypt(const byte key[KEY_SIZE], const byte iv[BLOCK_SIZE], const secure_string& ptext, secure_string& ctext)
 +
{
 +
    EVP_CIPHER_CTX_ptr ctx(EVP_CIPHER_CTX_new(), ::EVP_CIPHER_CTX_free);
 +
    int rc = EVP_EncryptInit_ex(ctx.get(), EVP_aes_256_cbc(), NULL, key, iv);
 +
    if (rc != 1)
 +
      throw std::runtime_error("EVP_EncryptInit_ex failed");
 +
 +
    // Cipher text expands upto BLOCK_SIZE
 +
    ctext.resize(ptext.size()+BLOCK_SIZE);
 +
    int out_len1 = (int)ctext.size();
 +
 +
    rc = EVP_EncryptUpdate(ctx.get(), (byte*)&ctext[0], &out_len1, (const byte*)&ptext[0], (int)ptext.size());
 +
    if (rc != 1)
 +
      throw std::runtime_error("EVP_EncryptUpdate failed");
 +
 
 +
    int out_len2 = (int)ctext.size() - out_len1;
 +
    rc = EVP_EncryptFinal_ex(ctx.get(), (byte*)&ctext[0]+out_len1, &out_len2);
 +
    if (rc != 1)
 +
      throw std::runtime_error("EVP_EncryptFinal_ex failed");
 +
 +
    // Set cipher text size now that we know it
 +
    ctext.resize(out_len1 + out_len2);
 +
}</pre>
  
 
==Notes on some unusual modes==
 
==Notes on some unusual modes==
Line 215: Line 309:
 
* [[EVP]]
 
* [[EVP]]
 
* [[Libcrypto API]]
 
* [[Libcrypto API]]
 +
* [[EVP Authenticated Encryption and Decryption]]
 +
* [[EVP Asymmetric Encryption and Decryption of an Envelope]]
 +
* [[EVP Signing and Verifying]]
 +
* [[EVP Message Digests]]
 +
* [[EVP Key Agreement]]
 +
* [[EVP Key and Parameter Generation]]
  
 
[[Category:Crypto API]]
 
[[Category:Crypto API]]
 
[[Category:C level]]
 
[[Category:C level]]
 
[[Category:Examples]]
 
[[Category:Examples]]

Latest revision as of 10:27, 15 May 2023

Symmetric Encryption and Decryption
Documentation
#include <openssl/evp.h>

The libcrypto library within OpenSSL provides functions for performing symmetric encryption and decryption operations across a wide range of algorithms and modes. This page walks you through the basics of performing a simple encryption and corresponding decryption operation.

In order to perform encryption/decryption you need to know:

  • Your algorithm
  • Your mode
  • Your key
  • Your Initialisation Vector (IV)

This page assumes that you know what all of these things mean. If you don't then please refer to Basics of Encryption.

The complete source code of the following example can be downloaded as evp-symmetric-encrypt.c.


Setting it up[edit]

The code below sets up the program. In this example we are going to take a simple message ("The quick brown fox jumps over the lazy dog"), and then encrypt it using a predefined key and IV. In this example the key and IV have been hard coded in - in a real situation you would never do this! Following encryption we will then decrypt the resulting ciphertext, and (hopefully!) end up with the message we first started with. This program expects two functions to be defined: "encrypt" and "decrypt". We will define those further down the page. Note that this uses the auto-init facility in 1.1.0.

#include <openssl/conf.h>
#include <openssl/evp.h>
#include <openssl/err.h>
#include <string.h>

int main (void)
{
    /*
     * Set up the key and iv. Do I need to say to not hard code these in a
     * real application? :-)
     */

    /* A 256 bit key */
    unsigned char *key = { 0x30, 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37,
                           0x38, 0x39, 0x30, 0x31, 0x32, 0x33, 0x34, 0x35,
                           0x36, 0x37, 0x38, 0x39, 0x30, 0x31, 0x32, 0x33,
                           0x34, 0x35, 0x36, 0x37, 0x38, 0x39, 0x30, 0x31
                         };

    /* A 128 bit IV */
    unsigned char *iv = { 0x30, 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37,
                          0x38, 0x39, 0x30, 0x31, 0x32, 0x33, 0x34, 0x35
                        };

    /* Message to be encrypted */
    unsigned char *plaintext =
        (unsigned char *)"The quick brown fox jumps over the lazy dog";

    /*
     * Buffer for ciphertext. Ensure the buffer is long enough for the
     * ciphertext which may be longer than the plaintext, depending on the
     * algorithm and mode.
     */
    unsigned char ciphertext[128];

    /* Buffer for the decrypted text */
    unsigned char decryptedtext[128];

    int decryptedtext_len, ciphertext_len;

    /* Encrypt the plaintext */
    ciphertext_len = encrypt (plaintext, strlen ((char *)plaintext), key, iv,
                              ciphertext);

    /* Do something useful with the ciphertext here */
    printf("Ciphertext is:\n");
    BIO_dump_fp (stdout, (const char *)ciphertext, ciphertext_len);

    /* Decrypt the ciphertext */
    decryptedtext_len = decrypt(ciphertext, ciphertext_len, key, iv,
                                decryptedtext);

    /* Add a NULL terminator. We are expecting printable text */
    decryptedtext[decryptedtext_len] = '\0';

    /* Show the decrypted text */
    printf("Decrypted text is:\n");
    printf("%s\n", decryptedtext);


    return 0;
}

The program sets up a 256 bit key and a 128 bit IV. This is appropriate for the 256-bit AES encryption that we going to be doing in CBC mode. Make sure you use the right key and IV length for the cipher you have selected, or it will go horribly wrong!! The IV should be random for CBC mode.

We've also set up a buffer for the ciphertext to be placed in. It is important to ensure that this buffer is sufficiently large for the expected ciphertext or you may see a program crash (or potentially introduce a security vulnerability into your code). Note: The ciphertext may be longer than the plaintext (e.g. if padding is being used).

We're also going to need a helper function to handle any errors. This will simply dump any error messages from the OpenSSL error stack to the screen, and then abort the program.

void handleErrors(void)
{
    ERR_print_errors_fp(stderr);
    abort();
}

Encrypting the message[edit]

So now that we have set up the program we need to define the "encrypt" function. This will take as parameters the plaintext, the length of the plaintext, the key to be used, and the IV. We'll also take in a buffer to put the ciphertext in (which we assume to be long enough), and will return the length of the ciphertext that we have written.

Encrypting consists of the following stages:

  • Setting up a context
  • Initialising the encryption operation
  • Providing plaintext bytes to be encrypted
  • Finalising the encryption operation

During initialisation we will provide an EVP_CIPHER object. In this case we are using EVP_aes_256_cbc(), which uses the AES algorithm with a 256-bit key in CBC mode. Refer to Working with Algorithms and Modes for further details.

int encrypt(unsigned char *plaintext, int plaintext_len, unsigned char *key,
            unsigned char *iv, unsigned char *ciphertext)
{
    EVP_CIPHER_CTX *ctx;

    int len;

    int ciphertext_len;

    /* Create and initialise the context */
    if(!(ctx = EVP_CIPHER_CTX_new()))
        handleErrors();

    /*
     * Initialise the encryption operation. IMPORTANT - ensure you use a key
     * and IV size appropriate for your cipher
     * In this example we are using 256 bit AES (i.e. a 256 bit key). The
     * IV size for *most* modes is the same as the block size. For AES this
     * is 128 bits
     */
    if(1 != EVP_EncryptInit_ex(ctx, EVP_aes_256_cbc(), NULL, key, iv))
        handleErrors();

    /*
     * Provide the message to be encrypted, and obtain the encrypted output.
     * EVP_EncryptUpdate can be called multiple times if necessary
     */
    if(1 != EVP_EncryptUpdate(ctx, ciphertext, &len, plaintext, plaintext_len))
        handleErrors();
    ciphertext_len = len;

    /*
     * Finalise the encryption. Further ciphertext bytes may be written at
     * this stage.
     */
    if(1 != EVP_EncryptFinal_ex(ctx, ciphertext + len, &len))
        handleErrors();
    ciphertext_len += len;

    /* Clean up */
    EVP_CIPHER_CTX_free(ctx);

    return ciphertext_len;
}

Decrypting the Message[edit]

Finally we need to define the "decrypt" operation. This is very similar to encryption and consists of the following stages: Decrypting consists of the following stages:

  • Setting up a context
  • Initialising the decryption operation
  • Providing ciphertext bytes to be decrypted
  • Finalising the decryption operation

Again through the parameters we will receive the ciphertext to be decrypted, the length of the ciphertext, the key and the IV. We'll also receive a buffer to place the decrypted text into, and return the length of the plaintext we have found.

Note that we have passed the length of the ciphertext. This is required as you cannot use functions such as "strlen" on this data - its binary! Similarly, even though in this example our plaintext really is ASCII text, OpenSSL does not know that. In spite of the name plaintext could be binary data, and therefore no NULL terminator will be put on the end (unless you encrypt the NULL as well of course).

Here is the decrypt function:

int decrypt(unsigned char *ciphertext, int ciphertext_len, unsigned char *key,
            unsigned char *iv, unsigned char *plaintext)
{
    EVP_CIPHER_CTX *ctx;

    int len;

    int plaintext_len;

    /* Create and initialise the context */
    if(!(ctx = EVP_CIPHER_CTX_new()))
        handleErrors();

    /*
     * Initialise the decryption operation. IMPORTANT - ensure you use a key
     * and IV size appropriate for your cipher
     * In this example we are using 256 bit AES (i.e. a 256 bit key). The
     * IV size for *most* modes is the same as the block size. For AES this
     * is 128 bits
     */
    if(1 != EVP_DecryptInit_ex(ctx, EVP_aes_256_cbc(), NULL, key, iv))
        handleErrors();

    /*
     * Provide the message to be decrypted, and obtain the plaintext output.
     * EVP_DecryptUpdate can be called multiple times if necessary.
     */
    if(1 != EVP_DecryptUpdate(ctx, plaintext, &len, ciphertext, ciphertext_len))
        handleErrors();
    plaintext_len = len;

    /*
     * Finalise the decryption. Further plaintext bytes may be written at
     * this stage.
     */
    if(1 != EVP_DecryptFinal_ex(ctx, plaintext + len, &len))
        handleErrors();
    plaintext_len += len;

    /* Clean up */
    EVP_CIPHER_CTX_free(ctx);

    return plaintext_len;
}

Ciphertext Output[edit]

If all goes well you should end up with output that looks like the following:

Ciphertext is:
0000 - e0 6f 63 a7 11 e8 b7 aa-9f 94 40 10 7d 46 80 a1   .oc.......@.}F..
0010 - 17 99 43 80 ea 31 d2 a2-99 b9 53 02 d4 39 b9 70   ..C..1....S..9.p
0020 - 2c 8e 65 a9 92 36 ec 92-07 04 91 5c f1 a9 8a 44   ,.e..6.....\...D
Decrypted text is:
The quick brown fox jumps over the lazy dog

For further details about symmetric encryption and decryption operations refer to the OpenSSL documentation Manual:EVP_EncryptInit(3).

Padding[edit]

OpenSSL uses PKCS padding by default. If the mode you are using allows you to change the padding, then you can change it with EVP_CIPHER_CTX_set_padding. From the man page:

EVP_CIPHER_CTX_set_padding() enables or disables padding. By default encryption operations are padded using standard block padding and the padding is checked and removed when decrypting. If the pad parameter is zero then no padding is performed, the total amount of data encrypted or decrypted must then be a multiple of the block size or an error will occur...

PKCS padding works by adding n padding bytes of value n to make the total length of the encrypted data a multiple of the block size. Padding is always added so if the data is already a multiple of the block size n will equal the block size. For example if the block size is 8 and 11 bytes are to be encrypted then 5 padding bytes of value 5 will be added...

If padding is disabled then the decryption operation will only succeed if the total amount of data decrypted is a multiple of the block size.

C++ Programs[edit]

Questions regarding how to use the EVP interfaces from a C++ program arise on occasion. Generally speaking, using the EVP interfaces from a C++ program is the same as using them from a C program.

You can download a sample program using EVP symmetric encryption and C++11 called evp-encrypt.cxx. The sample uses a custom allocator to zeroize memory, C++ smart pointers to manage resources, and provides a secure_string using basic_string and the custom allocator. You need to use g++ -std=c++11 ... to compile it because of std::unique_ptr.

You should also ensure you configure an build with -fexception to ensure C++ exceptions pass as expected through C code. And you should avoid other flags, like -fno-exceptions and -fno-rtti.

The program's main simply encrypts and decrypts a string using AES-256 in CBC mode:

typedef unsigned char byte;
typedef std::basic_string<char, std::char_traits<char>, zallocator<char> > secure_string;
using EVP_CIPHER_CTX_ptr = std::unique_ptr<EVP_CIPHER_CTX, decltype(&::EVP_CIPHER_CTX_free)>;
...

int main(int argc, char* argv[])
{
    // Load the necessary cipher
    EVP_add_cipher(EVP_aes_256_cbc());

    // plaintext, ciphertext, recovered text
    secure_string ptext = "Yoda said, Do or do not. There is no try.";
    secure_string ctext, rtext;

    byte key[KEY_SIZE], iv[BLOCK_SIZE];
    gen_params(key, iv);
  
    aes_encrypt(key, iv, ptext, ctext);
    aes_decrypt(key, iv, ctext, rtext);
    
    OPENSSL_cleanse(key, KEY_SIZE);
    OPENSSL_cleanse(iv, BLOCK_SIZE);

    std::cout << "Original message:\n" << ptext << std::endl;
    std::cout << "Recovered message:\n" << rtext << std::endl;

    return 0;
}

And the encryption routine is as follows. The decryption routine is similar:

void aes_encrypt(const byte key[KEY_SIZE], const byte iv[BLOCK_SIZE], const secure_string& ptext, secure_string& ctext)
{
    EVP_CIPHER_CTX_ptr ctx(EVP_CIPHER_CTX_new(), ::EVP_CIPHER_CTX_free);
    int rc = EVP_EncryptInit_ex(ctx.get(), EVP_aes_256_cbc(), NULL, key, iv);
    if (rc != 1)
      throw std::runtime_error("EVP_EncryptInit_ex failed");

    // Cipher text expands upto BLOCK_SIZE
    ctext.resize(ptext.size()+BLOCK_SIZE);
    int out_len1 = (int)ctext.size();

    rc = EVP_EncryptUpdate(ctx.get(), (byte*)&ctext[0], &out_len1, (const byte*)&ptext[0], (int)ptext.size());
    if (rc != 1)
      throw std::runtime_error("EVP_EncryptUpdate failed");
  
    int out_len2 = (int)ctext.size() - out_len1;
    rc = EVP_EncryptFinal_ex(ctx.get(), (byte*)&ctext[0]+out_len1, &out_len2);
    if (rc != 1)
      throw std::runtime_error("EVP_EncryptFinal_ex failed");

    // Set cipher text size now that we know it
    ctext.resize(out_len1 + out_len2);
}

Notes on some unusual modes[edit]

Worthy of mention here is the XTS mode (e.g. EVP_aes_256_xts()). This works in exactly the same way as shown above, except that the "tweak" is provided in the IV parameter. A further "gotcha" is that XTS mode expects a key which is twice as long as normal. Therefore EVP_aes_256_xts() expects a key which is 512-bits long.

Authenticated encryption modes (GCM or CCM) work in essentially the same way as shown above but require some special handling. See EVP Authenticated Encryption and Decryption for further details.

See also[edit]