If you ever happen to deal with GPGME and PHP, or if you just want to encrypt and decrypt with the power of GnuPG, this code might help you!

Note that this technique makes use of public and private keys, which increases encryption security. You should create your own keys separately.

Also, note that we are trying to let PHP to use GnuPG, which requires to write a few files to the $GNUPGHOME folder, known as user keys. They are created automagically in the background. Let your web server write to that folder and make 100% sure that it is not accessible via web (do not put it under your /var/www folder!). The $GNUPGHOME folder must be a regular folder (not /tmp) that belongs to the actual web server user (i.e: www-data), your server setup might be different, so it is up to you to setup everything correctly.

Let’s see the code:


    putenv("GNUPGHOME=/home/" . getenv('USER'));

    $publickey = file_get_contents('/path/to/publickey');
    $passphrase = "whatever the key is for your private key";
    $privatekey = file_get_contents('/path/to/privatekey');
    $text = "This is the text you want to encrypt";

    $gpg = new gnupg();
    echo "gpg->init RTV = <br/><pre>\n";
    echo "</pre>\n";

    $importedkey = $gpg->import($publickey);
    echo "gpg->import IMPORTEDKEY = <br/><pre>\n";
    echo "</pre>\n";

    $rtv = $gpg->addencryptkey($importedkey['fingerprint']);
    echo "gpg->addencryptkey RTV = <br /><pre>\n";
    echo "</pre>\n";

    $enc = $gpg->encrypt($text);
    echo "gpg->encrypt ENC = <br /><pre>\n";
    echo "Encrypted Data: " . $enc . "<br/>";
    echo "</pre>\n";

    $gpg = new gnupg();

    $importedkey = $gpg->import($decryptkey);
    echo "gpg->import IMPORTEDKEY = <br /><pre>\n";
    echo "</pre>\n";

    $rtv = $gpg->adddecryptkey($importedkey['fingerprint'], $passphrase);
    echo "gpg->adddecryptkey RTV = <br /><pre>\n";
    echo "</pre>\n";

    $plaintext = "";
    $dec = $gpg->decrypt($enc);
    echo "gpg->decrypt DEC = <br /><pre>\n";
    echo "</pre>\n";

    if ($dec == $text) {
      echo "GnuPG decrypt success!\n";