3

How can I encrypt a given string using gpg from command line? I have the public key stored in a file called pubkey.pub I thought I could simply do it with something like that.

gpg --import "path/to/pubkey.pub" --encrypt "my string to encrypt"

But this won't work.

Background: I have to use the PHP exec command to encrypt given text, because I don't have the PHP module itself installed on the server.

Jens Erat
  • 37,523
  • 16
  • 80
  • 96
YeppThat'sMe
  • 1,812
  • 6
  • 29
  • 45

1 Answers1

5

gpg reads from stdin while encrypting, thus run

echo "my string to encrypt" | gpg --encrypt

gpg --import imports key material to GnuPG's keystore, where it remains; thus you only have to call it once (and it is a rather slow operation, as it might trigger updating your trust database).

Jens Erat
  • 37,523
  • 16
  • 80
  • 96
  • Here is an easy-to-remember command to encrypt, sign and echo as ascii in the terminal: `echo "my string to encrypt" | gpg -aes` Note: you can add a space in the beginning so that the private data is not added to bash history. – Jonathan Cross Apr 16 '17 at 13:30
  • 2
    If you want to prevent it being visible to other users, please be aware that for the (although likely short) time GnuPG is running, other users will be able to read the string. If you want to prevent that, better use `gpg -aes < – Jens Erat Apr 16 '17 at 14:45