Can I encrypt a message (string) using a public key at the command prompt? Also, how can I decrypt the result afterwards?


Another option is openssl:

# generate a 2048-bit RSA key and store it in key.txt
openssl genrsa -out key.txt 2048

# encrypt "hello world" using the RSA key in key.txt
echo "hello world" | openssl rsautl -inkey key.txt -encrypt >output.bin

# decrypt the message and output to stdout
openssl rsautl -inkey key.txt -decrypt <output.bin
  • +1 for openssl since it's more commonly installed than gpg is – Doug Harris Aug 10 '09 at 14:08
  • This is perfect - works on Mac, Alpine, anything... good work! – Jeremy Iglehart Oct 19 '18 at 23:32
  • yeah how about an example not using a file but an argument? – Alexander Mills May 23 '19 at 18:34
  • Only works for ~240 bytes of data, which many 'messages' exceed, and uses pkcs1-v1_5 which if adversary can get you to decrypt chosen ciphertexts allow Bleichenbacker attack. – dave_thompson_085 Oct 28 '20 at 2:47

If you have gpg installed, this is an industrial-strength encryption method.

gpg --encrypt -r recipient@example.com >tempfile

Type data at the console and press Ctrl+D to end the text. This will give you encrypted data in tempfile. To decrypt:

gpg --decrypt <tempfile

You will need the passphrase for recipient@example.com to decrypt the message.

  • 1
    ok, so if the passphrase needs to be inputted interactively, how to do it non-interactively? How do this non-interactively? – Alexander Mills May 23 '19 at 18:35
  • 1
    gpg --encrypt -r recipient@example.com >tempfile gpg: error retrieving 'recipient@example.com' via WKD: No data gpg: recipient@example.com: skipped: No data gpg: [stdin]: encryption failed: No data ( I am on a mac) – Alexander Mills May 23 '19 at 18:36
  1. Generate a private/public key pair

    $ openssl genrsa -out rsa_key.pri 2048; openssl rsa -in rsa_key.pri -out rsa_key.pub -outform PEM -pubout
  2. Encrypt the string using public key, and store in a file

    $ echo "stockexchange.com" | openssl rsautl -encrypt -inkey rsa_key.pub -pubin -out secret.dat
  3. Un-encrypt using private key

    $ string=`openssl rsautl -decrypt -inkey rsa_key.pri -in secret.dat `; echo $string
  • This adds almost nothing to the 8-year-earlier answer, and has the same problems. – dave_thompson_085 Oct 28 '20 at 2:51

man crypt(1)


crypt implements a one-rotor machine designed along the lines of the German Enigma, but with a 256-element rotor. Methods of attack on such machines are widely known, thus crypt provides minimal security.

But it's OK for demonstration purposes.

  • "Oracle Solaris 10 8/11 Information Library" – Sebas Jan 26 '17 at 9:12

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy