Encrypt your sensitive data in command line under Linux

Do you store your passwords, PIN codes, bank account information, SSN or other sensitive data in the text file at your hard drive? Hope not. But it's very difficult to hold all that stuff in memory. Instead it would be nice to encrypt it. One option could be to choose utility like TrueCrypt, but it implies mounting volumes, having a bunch of files and not forgetting to unmount volumes. Instead I suggest having sensitive data encrypted in command line easily like encr filename and decr filename. For this purpose let's take a look at GPG and OpenSSL utilities.

The GNU Privacy Guard

To encrypt your data with GPG you can use either keypair or passphrase. I'm gonna show here keypair way. If you need encrypt using only passphrase, refer to man page for gpg, you are interested in -c option.

To generate new key execute command:

gpg --gen-key

Tool will ask you several questions in interactive mode. If you don't know that to answer, select default answer. Don't left passphrase empty. You will also be asked to input your email address. Please specify the same email while encryption:

echo "Sensitive data" | gpg -e -r email@example.com -o ~/cipher

The string "Sensitive data" will be encrypted using your key and written to file ~/cipher. If you need to encrypt the multiline text, skip echo command (start with gpg -e...), run command, input your text and finally press Ctrl+D to finish input.

To decrypt text run:

gpg -d ~/cipher

You will see your encrypted text.


Alternative way could be to use OpenSSL.

First of all let's generate private key:

mkdir ~/.openssl
chmod 700 ~/.openssl
openssl genrsa -out ~/.openssl/my.private 4096
chmod 600 ~/.openssl/my.private

To encrypt string:

echo "Sensitive data" | openssl rsautl -inkey ~/.openssl/my.private -encrypt > ~/cipher

To decrypt string:

openssl rsautl -inkey ~/.openssl/my.private -decrypt < ~/cipher
Tagged as : Linux