Monday, 23 July 2012

Encrypting files using SSH Keypairs and OpenSSL

There are a number of reasons why you don't want to do this, go and use GPG or something similar to perform your encryption. 

That said, if you're in a situation where you have a secret that needs securing before transmission to a specific party and the only credential for the recipient you have is their SSH Public Key then read on...

To start with you're going to need OpenSSL and SSH installed, we need SSH to convert the keys and we'll perform the actual encryption using OpenSSL.

Use SSH to convert the normal public key into something more usable by OpenSSL:

ssh-keygen -f -e -m pkcs8 > id_rsa.pub8

Use OpenSSL to encrypt 'secrets.txt' using the public key:
openssl rsautl -encrypt -inkey id_rsa.pub8 -pubin -in secrets.txt -out secrets.ssl

The recipient of the file can decrypt it using their corresponding private key:
openssl rsautl -decrypt -inkey id_rsa -in secrets.ssl -out secrets.txt

Voila! Simple public key encryption using SSH keys.

Be aware that we are doing direct RSA encryption here, which means you can only encrypt very small amounts of data. Anything bigger will typically use a symmetric algorithm like AES for encryption and use RSA to protect the AES key.

No comments:

Post a Comment