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

Note that this technique makes use of public and private keys, which increases encryption security. You will require to create your 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, know as user keys. They are created automagically in the background, just let your web server write to that folder, and make 100% that it is not accessible via web (do not put it under your /var/www folder!). The $GNUPGHOME folder should 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 set it up correctly.

Let’s see the code:

    <?php

    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";
    var_dump($res);
    echo "</pre>\n";

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

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

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

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

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

If you happen to have any issue report it in a comment.

Blessings!