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:
-----BEGIN PUBLIC KEY-----
MIIBIDANBgkqhkiG9w0BAQEFAAOCAQ0AMIIBCAKCAQEAkq1lZYUOJH2Yeq5IG/TfB3vFbRcc6fSxrwuADNuS10ftI9Nd5lsVKiU+T/NkDQ42I8DMVyjrrFS/bfBUoH1DeyhDVMXvCyfRYNtQdhq0zKMs7l1bmmeBoTiXEyOnjst0LTNzdjY6huvWilACCiU+DeRUvZr73VZty/YoAZsHA4GdnTqyLHnusN/k0r6KaTagUxZl26Wkj2J2sIw+3XIMczmPHO0p4bpynEKmKF3tr7bqBPe6s8azQMElibCAA8jTUs45RvHYtdKajmTxfETIQa8a54ZzZ54dApo0yFXOb2LRgk8H5awk5dUNfcX88FoYDWD/RigJEd3F5Y1unaZXJwIBIw==
-----END PUBLIC KEY-----
Encrypt
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.
Decrypt
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.