Use ssh keys to encrypt and decrypt messages

Encryption with RSA Key Pairs

During the Thanksgiving holiday I wondered, “how hard would it be to encrypt and decrypt files with my SSH key?” Encryption is the purpose of public/private RSA key pairs, after all.

With `openssl`, it’s not too hard.

(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 "Yo test!!" > clear.txt

Before we can encrypt the text file with our public key, we must export our public key into a PEM format suitable for OpenSSL.

openssl rsa -in ~/.ssh/id_rsa -pubout > ~/.ssh/id_rsa.pub.pem
 
cat ~/.ssh/id_rsa.pub.pem

It should look something like this:

-----BEGIN PUBLIC KEY-----
xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx-----END PUBLIC KEY-----

Encrypt

cat plain.txt | openssl rsautl -encrypt -pubin -inkey ~/.ssh/id_rsa.pub.pem > encrypted.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 encrypted with `cat encrypted.txt`.

You should see non readable stuff.

Decrypt

cat encrypted.txt | openssl rsautl -decrypt -inkey ~/.ssh/id_rsa

“Yo test!!”

Voila`! We’re back to clear text.

 

Leave a Reply

Your email address will not be published. Required fields are marked *