How to encrypt with AES programmatically
When using OpenSSL
as a library, we do not have to limit ourselves to the functionality that the openssl
tool provides. openssl
is a good tool, but it does not expose the whole functionality of OpenSSL. For instance, openssl enc
does not support encryption or decryption in GCM, but OpenSSL as a library allows us to do that.
In this section, we are going to develop a program that can encrypt a file using an AES-256 cipher in GCM. We will call our program encrypt
.
In order to avoid passing too many values on the command line, we will store the IV and authentication tag in the encrypted file. Unlike the encryption key, the IV and auth tag are public information and do not have to be kept secret. The format of the encrypted file will be the following:
Table 2.1 – The encrypted file format
Our encryption program will need three command-line arguments:
- Input file name
- Output file name
- Encryption...