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. The following tutorial assumes you've setup RSA private/public keys for ssh/git/github/etc.

(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." > plain.txt

Before we can encrypt the plaintext with our public key, we must export our public key into a PEM format suitable for OpenSSL's consumption.

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

It should look something like this:

-----END PUBLIC KEY-----


cat plain.txt \
 | openssl rsautl \
     -encrypt \
     -pubin -inkey ~/.ssh/id_rsa.pub.pem \
 > cipher.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 cipher.txt`. You should see fully encrypted gibberish.


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

"Hello, world."

Boom! We're back to plaintext.

If you actually wanted to trade encrypted messages, PGP is the much "friendlier" and accepted system for doing so. This manual, command-line method of encryption is a neat demo nonetheless.