GnuPG Encryption with PHP (on Ubuntu with Pecl)

Posted on April 13th, 2013 in General by Brandon

Instructions for Getting this working on Ubuntu 12.04 and more modern systems than my previous post

Install the required system and pecl packages:

  # apt-get install gnupg  libgpgme11 libgpgme11-dev
  # pecl install gnupg
  # echo extension=gnupg.so > /etc/php5/conf.d/gnupg.ini
  # apache2ctl restart

Generate a Private key

 # gpg --homedir /path/to/your/directory --gen-key

On a virtual machine, if that stalls for a while, you may have to generate some “randomness” somehow. Try one of these commands in a separate session, according to this bug report:

 # find / -type f | xargs grep blahblahblha
 # tcpdump -i any > /dev/null

At this point, you should have a working GPG key in the home directory you specified. You can list your secret keys with the command:

  # gpg --homedir /path/to/your/directory -K

You’ll then want to export the key with the command:

 # gpg --homedir /path/to/your/directory --export-secret-key --armour

You’ll want to copy that secret key to another machine. DON’T LOSE IT or you won’t be able to decrypt anything. Once you’ve got it safely stored somewhere, you want to delete it from your web server:

 #  gpg --homedir /path/to/your/directory --delete-secret-key your@address.com

You can then make sure that the public key is still there. It is what you’ll need to encrypt messages:

 # gpg --homedir /path/to/your/directory -k

Finally, you’ll need the fingerprint for the key to refer to it within your PHP code.

 # gpg --homedir /path/to/your/directory --fingerprint
pubring.gpg
-------------
pub   2048R/5BB54E26 2013-04-14 [expires: 2023-04-12]
      Key fingerprint = AAAA BBBB CCCC DDDD EEEE  FFFF 0000 1111 2222 3333
uid                  Your Name <your@address.com>
sub   2048R/2EF4937A 2013-04-14 [expires: 2023-04-12]

You can then use the gnupg pecl functions to encrypt a messages:

<?php
$CONFIG['gnupg_home'] = '/var/www/.gnupg';
$CONFIG['gnupg_fingerprint'] = 'FA451EE9877270EF1CFA99CE048A613921CCC3D6';

$data = 'this is some confidential information';

$gpg = new gnupg();
putenv("GNUPGHOME={$CONFIG['gnupg_home']}");
$gpg->seterrormode(GNUPG_ERROR_SILENT);
$gpg->addencryptkey($CONFIG['gnupg_fingerprint']);
$encrypted =  $this->gpg->encrypt($data);
echo "Encrypted text: \n$encrypted\n";

// Now you can store $encrypted somewhere.. perhaps in a MySQL text or blob field.

// Then use something like this to decrypt the data.
$passphrase = 'Your_secret_passphrase';
$gpg->adddecryptkey($CONFIG['gnugp_fingerprint'], $passphrase);
$decrypted = $gpg->decrypt($encrypted);

echo "Decrypted text: $decrypted";
?>

Post a comment

Please copy the string LBVuNL to the field below: