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:


$ 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.


$ 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:


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:


$ enc unencrypted-file encrypted-file.txt


$ dec encrypted-file.txt unencrypted-file