How can I encrypt a string in the shell?

Solution 1:

Another option is openssl:

# generate a 2048-bit RSA key and store it in key.txt
openssl genrsa -out key.txt 2048

# encrypt "hello world" using the RSA key in key.txt
echo "hello world" | openssl rsautl -inkey key.txt -encrypt >output.bin

# decrypt the message and output to stdout
openssl rsautl -inkey key.txt -decrypt <output.bin

Solution 2:

If you have gpg installed, this is an industrial-strength encryption method.

gpg --encrypt -r [email protected] >tempfile

Type data at the console and press Ctrl+D to end the text. This will give you encrypted data in tempfile. To decrypt:

gpg --decrypt <tempfile

You will need the passphrase for [email protected] to decrypt the message.