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):

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:

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:

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

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

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:

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:

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

There are 9 comments

I love comments that bring new insights, shares ideas and experiences, and most of all: corrects my mistakes. For support questions, there are other fora, like Stack Overflow, Server Fault and the WordPress support forum.

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