Search code examples
phpencryptionexecpgpgnupg

How to encrypt a string with GnuPG?


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.


Solution

  • 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).