Crypt and decrypt files with OpenSSL from the command line

I finally managed to add to my ~/.bashrc a function to crypt and decrypt files and directories using OpenSSL. Add these to your ~/.bashrc and reload it with source ~/.bashrc

function sslcrypt {
  item=$(echo $1 | sed -e 's/\/$//') # get rid of trailing / on directories

  if [ ! -r $item ]; then
    exit 1;
  fi

  if [ -d $item ]; then
    tar zcf "${item}.tar.gz" "${item}"
    openssl enc -aes-256-cbc -salt -in "${item}.tar.gz" -out "${item}.tar.gz.ssl"
    rm -f "${item}.tar.gz"
  else
    openssl enc -aes-256-cbc -salt -in "${item}" -out "${item}.ssl"
  fi
}

function ssldecrypt {
  item=$1

  if [ ! -r $item ]; then
    exit 1;
  fi

  openssl enc -d -aes-256-cbc -in "${item}" > "${item}.decrypted"
}

You can invoke them as:

user[~]% sslcrypt file.txt
enter aes-256-cbc encryption password:
Verifying - enter aes-256-cbc encryption password:
user[~]%
user[~]% ls -l file*
-rw------- 1 user group 668 13 gen 16.11 file.txt
-rw-rw-r-- 1 user group 688 19 feb 23.27 file.txt.ssl
user[~]%
user[~]% ssldecrypt file.txt.ssl
user[~]% ls -l file*
-rw------- 1 user group 668 13 gen 16.11 file.txt
-rw-rw-r-- 1 user group 688 19 feb 23.27 file.txt.ssl
-rw-rw-r-- 1 user group 668 19 feb 23.29 file.txt.ssl.decrypted

Use a good passphrase for strong security, but don’t forget it!

Advertisements

2 thoughts on “Crypt and decrypt files with OpenSSL from the command line

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s