2022-09-04

Encrypt Files with OpenSSL

a basic demonstration of symmetric encryption

OpenSSL is a software toolkit for general purpose cryptography and secure communication. On GNU/Linux systems, we can leverage the features of OpenSSL using the openssl command line tool.

Let's get started!

Setup

Most probably, the openssl tool would already be installed on your system. You can verify this by running the following command in your shell,

openssl version

If openssl is installed, then the output will look something like this,

OpenSSL 1.1.1n  15 Mar 2022

If you get an error saying command not found, then you need to install the openssl package. On debian based systems, you can install it with the following command,

sudo apt install openssl

For the demonstration purpose, let's create a dummy file called secret.txt. We will encrypt this secret.txt file using openssl.

echo "Hello World" > secret.txt

Encryption

We will be using the AES 256 encryption algorithm to encrypt the file. AES is a symmetric-key encryption algorithm, which means that the same key is used to encrypt as well as decrypt the data. The length of the key can be 128, 192 or 256 bits. We would be using a 256 bit key, hence the algorithm is called AES-256.

However we won't be creating any key explicitly, rather, we would provide a passphrase, and openssl will automatically derive the key from the passphrase.

To encrypt the secret.txt file into secret.enc.txt, run the following command:

openssl aes-256-cbc -e -salt -iter 10000 -pbkdf2 -a -in secret.txt -out secret.enc.txt

Let's have a look on the options we have used,

Option Description
aes-256-cbc the AES-256 algorithm
-e this means we want to do encryption
-salt read more about salt (cryptography)
-iter 10000 we want 10,000 iterations to produce the key
-pbkdf2 passphrase based key derivation function 2
-a base64 encode/decode
-md val Message digest algorithm
-in val our input file
-out val our output file

This will ask for a passphrase. Make sure you remember this passphrase. Now, you will have a secret.enc.txt encrypted file along side your plain text secret.txt file.

We will remove the secret.txt file, which contains our secret message. We used the shred command to overwrite the file and then delete it.

shred -fun5 secret.txt

Decryption

The command for decrypting a file is almost same, except here we use the -d flag (d for decryption), instead of -e (e for encryption), and the input-output files change accordingly.

openssl aes-256-cbc -d -salt -iter 10000 -pbkdf2 -a -in secret.enc.txt -out secret.txt

This will ask for the passphrase. After entering the correct passphrase, a plain text file, secret.txt would be created.

Note

This method is used to encrypt one file at a time. If you want to encrypt multiple files in one go, then make a tarball of all the files, and then encrypt the tarball with this method.