Encrypt and decrypt a file using SSH keys

If you have someone’s public SSH key, you can use OpenSSL to safely encrypt a file and send it to them over an insecure connection (i.e. the internet). They can then use their private key to decrypt the file you sent.

If you encrypt/decrypt files or messages on more than a one-off occasion, you should really use GnuPGP as that is a much better suited tool for this kind of operations. But if you already have someone’s public SSH key, it can be convenient to use it, and it is safe.

There is a limit to the maximum length of a message – i.e. size of a file – that can be encrypted using asymmetric RSA public key encryption keys (which is what SSH keys are). For this reason, we’ll actually generate a 256 bit key to use for symmetric AES encryption and then encrypt/decrypt that symmetric AES key with the asymmetric RSA keys. This is how encrypted connections usually work, by the way.

Encrypt a file using a public SSH key

Generate the symmetric key (32 bytes gives us the 256 bit key):

$ openssl rand -out secret.key 32

You should only use this key this one time, by the way. If you send something to the recipient at another time, don’t reuse it.

Encrypt the file you’re sending, using the generated symmetric key:

$ openssl aes-256-cbc -in secretfile.txt -out secretfile.txt.enc -pass file:secret.key

In this example secretfile.txt is the unencrypted secret file, and secretfile.txt.enc is the encrypted file. The encrypted file can be named whatever you like.

Encrypt the symmetric key, using the recipient’s public SSH key:

$ openssl rsautl -encrypt -oaep -pubin -inkey <(ssh-keygen -e -f recipients-key.pub -m PKCS8) -in secret.key -out secret.key.enc

Replace recipients-key.pub with the recipient’s public SSH key.

Delete the unencrypted symmetric key, so you don’t leave it around:

$ rm secret.key

Now you can send the encrypted secret file (secretfile.txt.enc) and the encrypted symmetric key (secret.key.enc) to the recipient. It is even safe to upload the files to a public file sharing service and tell the recipient to download them from there.

Decrypt a file encrypted with a public SSH key

First decrypt the symmetric.key:

$ openssl rsautl -decrypt -oaep -inkey ~/.ssh/id_rsa -in secret.key.enc -out secret.key

The recipient should replace ~/.ssh/id_rsa with the path to their secret key if needed. But this is the path to where it usually is located.

Now the secret file can be decrypted, using the symmetric key:

$ openssl aes-256-cbc -d -in secretfile.txt.enc -out secretfile.txt -pass file:secret.key

Again, here the encrypted file is secretfile.txt.enc and the unencrypted file will be named secretfile.txt

There are 17 comments

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.