Networking, Security, Linux


Encrypting Files using an RSA Public Key

This posts looks at how to encrypt files with RSA using the OpenSSL command. It also shows how RSA public keys can be retrieved from SSH and TLS servers

Rohan MolloyRohan Molloy

Obtaining a public key from a remote server

First, let's obtain the public key of a running SSH server.
The ssh-keyscan utility is used for this, with the -t flag specifying RSA key. We also need to convert it into a suitable format, this involves two things. First, stripping the hostname field added by ssh-keygen,
then using ssh-keygen to convert to the standard pkcs8 format

Encrypting a file against a public key

With the exception of very small files (less than ~2kb), RSA cannot be used directly for encryption. Instead,
RSA is used to encrypt/decrypt a shared passphase, used for a subsequent symmetric algorithm such as AES-256.

With that in mind, let's make a function to directly encrypt a small file using RSA

Putting it together

For this demo, I have a Docker containing running SSH.
It has a local ncat server that decrypts incoming requests using its RSA public key.

$ Get-SSHPublicKey $peer > $
# SSH-2.0-OpenSSH_6.7p1 Debian-5+deb8u8
$ Encrypt-WithRSA $ <<< "Hello World" | cat >/dev/tcp/$peer/2222
$ docker logs ssh-demo
[ ok ] Starting OpenBSD Secure Shell server: sshd.
Hello World

Rohan Molloy

View Comments