How to encrypt a message or file using Openssl
With openssl
, it’s not too hard. The following tutorial assumes you’ve setup RSA private/publicc.
Note: If you’re on OSX, you should install the latest versions of OpenSSL and OpenSSH with Homebrew.
First, let’s start with our plaintext file:
# echo "Hello world" > test.txt
Encrypt with Public key
# cat test.txt | openssl rsautl -encrypt -pubin -inkey ~/.ssh/id_rsa.pub > encryted-file.txt
The important command in the pipeline is openssl
. The first argument passed to openssl
is the OpenSSL command you are running. It has a wide variety of commands covering a wide range of cryptographic functionality. For our purposes, we’re doing public/private RSA encryption, so we’re using the RSA Utility, or rsautl
, command. Next, the -encrypt
key indicates we are encrypting from plaintext to cipher text, and finally the -pubin
flag indicates we are loading a public key from -inkey [public key file]
.
Print the contents of the ciphertext with cat encryted-file.txt
. You should see fully encrypted gibberish.
Decrypt with the Private key
cat encryted-file.txt | openssl rsautl -decrypt -inkey ~/.ssh/id_rsa
"Hello, world."