Globadis works

NetSec, hacking and other stuff

Encrypt and decrypt files with RSA (ssh) keys

2022-04-19 Globadis

Sometimes, I may need to send some file to some coworker over an insecure channel (e-mail) or have them download it directly from an insecure server.

As you can guess, it’s not something I enjoy, and I thoroughly avoided doing so most of the time, relying on USB sticks and physically meeting said coworker, or zipping the file in a password protected archive before sending it… But the latter requires sharing a secret, so in best case scenario we dig out the old Diffie Helmann KEP… Works out, but not ideal.

However, most of my coworkers being developers and using gitlab, I do have access to some public RSA (and ecdsa) keys, Gitlab offering publicly (duh !) the public keys of its users at the address “<username>.keys”.

So … Public/Private keys should be the perfect solution to my problem : I could encrypt the files with the public key, and only the user would be able to decrypt it with the associated private key. It is, after all, the whole point of asymmetric encryption.

Not so fast …

Alas, there’s a stone in that shoe : Most users (at least most of my users) use RSA keys, and RSA is meant to encrypt short messages only (traditionnally a shared secret, for latter symetric encryption), and thus the payload size is limited by the modulus of the key, rendering this scheme unsuitable for ecrypting files.

Well, if RSA is meant to encrypt a shared secret for latter symmetric encryption and no more, let’s use it exactly that way ! We can then :

  • Create a random key
  • Encrypt the file with a symmetric cypher using said private key (aes-256 is fine for this task)
  • Encrypt the random key with the public RSA key of the recipient
  • Send it all to said recipient for decryption.

The recipient then decrypt the secret key using its private RSA key, and is then able to decrypt the file contents using said secret, and voilĂ  !

Seems tedious, is it scriptable ?

Well, of course it is, and of course I did. You can find the rsaCrypt script on my github repository along with its documentation.

As I made it mainly to suit my peculiar needs, it can fetch the public key from gitlab only, and is using only the first available public RSA key found there. Adapting it to fetch keys from other platforms (such as github) should be no big deal, and though I probably won’t do it myself, pull requests will of course be duly considered.

What next ?

As I do have some cowokers using only ECC based keys (ecdsa mostly), I might consider adding the support for ECC-based keys in the script. The general path would remain quite similar, though this will need some adjustments (key derivation, here I come)