How to encrypt a string with my SSH pubkey?

5,673

Here is one way to do that:

First of all you should install the latest versions of OpenSSL and OpenSSH.

Before we can encrypt the plaintext with our public key, we must export our public key into a PEM format suitable for OpenSSL's consumption

openssl rsa -in ~/.ssh/id_rsa -pubout ~/.ssh/id_rsa.pub.pem

then you can encrypt:

cat plain.txt | openssl rsautl -encrypt -pubin -inkey ~/.ssh/id_rsa.pub.pem > cipher.txt
  • rsautl: RSA Utility
  • -encrypt: key indicates we are encrypting from plaintext to cipher text
  • -pubin: flag indicates we are loading a public key from -inkey [public key file].

and for decrypt:

cat cipher.txt | openssl rsautl -decrypt -inkey ~/.ssh/id_rsa
Share:
5,673

Related videos on Youtube

pepite
Author by

pepite

Updated on September 18, 2022

Comments

  • pepite
    pepite 3 months

    If I only have an SSH pubkey, how can I encrypt an ex.: IP address (so a short string), only using the ssh pubkey?

    For decryption, the other party would have the pair of the pubkey, so the private key, with which it can decrypt the string.

  • pepite
    pepite almost 6 years
    although it sometimes request for ssh password many times.. any ide for that?
  • Wissam Roujoulah
    Wissam Roujoulah almost 6 years
    @ccpizza take a look here stackoverflow.com/questions/30056762/…
  • Bolwerk
    Bolwerk almost 4 years
    In my case, I didn't actually stream to cipher.txt. I actually piped to base64, and used that hash to store my password in my PERL script. Decryption is with a command like $pass=echo "$password_hash" | base64 -d | openssl rsautl -decrypt -inkey /home/myhomedirectory/.ssh/id_rsa