File encryption and decryption with OpenSSL

February 14, 2010

File encryption and decryption is very easy with OpenSSL, which is installed on most any Linux system. Consider the following commands:

Encryption:

$ openssl enc -aes-256-cbc -a -salt -in unencrypted-file -out encrypted-file.txt

This will prompt for a password to use as an encryption key. The -a switch uses Base64 encoding for the encrypted output, which is handy for representing encrypted data as text.

Decryption:

$ openssl enc -d -aes-256-cbc -a -in encrypted-file.txt -out unencrypted-file

These commands can then be placed within Bash functions and added to .bashrc:

.bashrc:

function enc() { openssl enc -aes-256-cbc -a -salt -in "$1" -out "$2"; }
function dec() { openssl enc -d -aes-256-cbc -a -in "$1" -out "$2"; }

These functions shorten above encryption and decryption commands to:

Encryption:

$ enc unencrypted-file encrypted-file.txt

Decryption:

$ dec encrypted-file.txt unencrypted-file