• Linux
  • FreeBSD
  • Networking
  • Python
  • AWS
  • WebDev
  • About Us

How to encrypt/decrypt file using OpenSSL

Written by
Linux Leave a Comment

OpenSSL can be used to encrypt/decrypt the files and can also be used to secure the communication channels .

I touched a file file.txt

To encrypt the file :

openssl enc -aes-256-cbc -in file.txt -out file.txt.enc

Now to decrypt the file file.enc:

openssl enc -aes-256-cbc -d -in file.enc -out file.txt

The encryption requires a password and the same password will be asked to decrypt the file.

But the password input form the command line makes it hard to run from a cronjob or from a automation script . So we can use a passphrase to use it with the openssl command .

export PASS=test123
openssl enc -aes-256-cbc -in file.txt -out file.enc -pass env:PASS

Now to decrypt :

export PASS=test123
openssl enc -aes-256-cbc -d -in file.enc -out file.txt -pass env:PASS

You can also use the -k flag to provide password along with the command:

openssl enc -aes-256-cbc -in file.txt -out file.enc -k password

You use the same while decrypting:

openssl enc -aes-256-cbc -d -in test.enc -out test.txt -k password

You migtht get the below error with these and might be problem if the command goes part of a script .

*** WARNING : deprecated key derivation used.
Using -iter or -pbkdf2 would be better.

You can adjust your encryption type to avoid this error:

openssl aes-256-cbc -salt -pbkdf2 -in backups.tar.gz -out backups.tar.gz.enc -k password

To decrypt:

openssl aes-256-cbc -d -salt -pbkdf2 -in backups.tar.gz.enc -out backups.tar.gz

© Copyright 2020.TechieNix. All Rights Reserved.