Encrypt a File on Linux Using OpenSSL

LockIt is possible to encrypt a file for secure transmission or backup using a strong cryptographic algorithm on Linux. We do that using OpenSSL:

Encrypting an Existing File

The command to encrypt is very simple:

openssl enc -aes256 -in myfile.txt -out myfile.txt.enc -salt

Let’s look at what all this means:

  • enc means to use symmetric ciphers. These are ciphers where there is only one secret key that is needed to decrypt the data. In this case that key is your password.
  • -aes256 is the short form for the algorithm AES 256 bit in CBC mode. For a list of other algorithms run “man enc”.
  • -in and -out are the input file and the encrypted output file respectively
  • -salt tells it to use salt when encrypting. This protects you from dictionary attacks and the man page recommends you use it.

When you run the above command OpenSSL will prompt you for a password to encrypt the file with.

Decrypting a File

Decryption is similarly very easy:

openssl enc -aes256 -in myfile.txt.enc -out myfile.txt.decrypted -d

The main difference here is the -d switch which tells it to decrypt the input file. You will be prompted to enter the correct password for it to decrypt properly.

Compressing and Encrypting a File

If you want to compress and encrypt in one go you can do that too:

tar -cz /path/to/file/or/dir | openssl enc -aes256 -salt -e > compressed_and_encrypted.tgz.enc

Here we’re using tar to create a compressed archive which is piped to openssl for encryption and finally the encrypted file is written to disk.

Leave a Reply

Your email address will not be published. Required fields are marked *