Sep 19, 2018

How to Encrypt & Decrypt Files Using OpenSSL

Encrypt a File

$ openssl enc -aes-256-cbc -salt -in file.txt -out file.txt.enc
opensslOpenSSL command line tool
encEncoding with Ciphers
-aes-256-cbcThe encryption cipher to be used
-saltAdds strength to the encryption
-inSpecifies the input file
-outSpecifies the output file.

Without the -salt option it is possible to perform efficient dictionary attacks on the password and to attack stream cipher encrypted data.

The -salt option should ALWAYS be used if the key is being derived from a password.

When the salt is being used the first eight bytes of the encrypted data are reserved for the salt: it is generated at random when encrypting a file and read from the encrypted file when it is decrypted.

Decrypt a File

$ openssl enc -aes-256-cbc -d -in file.txt.enc -out file.txt
-dDecrypts data
-inSpecifies the data to decrypt
-outSpecifies the file to put the decrypted data in

If you are creating a BASH script, you may want to set the password in non interactive way, using -k option.

Encrypt a file using a supplied password:
$ openssl enc -aes-256-cbc -salt -in file.txt -out file.txt.enc -k secret
Decrypt a file using a supplied password:
$ openssl enc -aes-256-cbc -d -in file.txt.enc -out file.txt -k secret