Obtaining a public key from a remote server
First, let's obtain the public key of a running SSH server.
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 > $peer.pub.pem # 172.17.0.2:22 SSH-2.0-OpenSSH_6.7p1 Debian-5+deb8u8 $ Encrypt-WithRSA $peer.pub.pem <<< "Hello World" | cat >/dev/tcp/$peer/2222 $ docker logs ssh-demo [ ok ] Starting OpenBSD Secure Shell server: sshd. Hello World