How to use ssh-rsa public key to encrypt a text


So, the scenario is: Given I'm Bob, I want to encrypt some message for Alice. The only public key I have is her ssh-rsa like this:

ssh-rsa AAAAB3NzaC1yc2EAAAABIwAAAQEAyb+qaZLwgC7KAQJzYikf3XtOWuhlMXVv2mbTKa5dp0sHPRd2RaYnH8ZRkt7V8bjqct1IHGCuxI8xyoEp4at3FHe6j9RfWiarc1ldLUCmTtryI0GGpRs6Zpvqdtpcq/1NCIYtUQAvsImyEFCtqmB2suDo1ZSllZQ0x9TCKHdCANYIOeaniuFzR57POgE3vxk/r6PO24oy8BIWqxvi29r0n1LUigVBJ7CmMHuzb4/+i1v6PxV1Lqnj6osPP9GpXpsh8kLUCby/KcmcryWNdSP0esyCdDxkA5hlIuk8qL1vzsyPluUQuc0BEHu6nuw8WQlCF1mFFxcpJL+MhWEr01WIIw== sikachu@Sikachus-Notebook.local

So, is there a way to encrypt a string using this public key so she can use her private key from id_rsa (generated from ssh-keygen) to decrypt the message?

(I know that it's possible right away if you're using .pem key pair file. If you can show me how to convert this to the format that openssl supports, that'd be great as well!)


Best Answer

It's possible to convert your ssh public key to PEM format(that 'openssl rsautl' can read it):


ssh-keygen -f ~/.ssh/ -e -m PKCS8 >

Assuming 'myMessage.txt' is your message which should be public-key encrypted.

Then just encrypt your message with openssl rsautl and your converted PEM public-key as you would normally do:

openssl rsautl -encrypt -pubin -inkey -ssl -in myMessage.txt -out myEncryptedMessage.txt

The result is your encrypted message in 'myEncryptedMessage.txt'

To test your work to decrypt the with Alice' private key:

openssl rsautl -decrypt -inkey ~/.ssh/id_rsa -in myEncryptedMessage.txt -out myDecryptedMessage.txt