Support Center » Knowledgebase » Programming and Scripting » GnuPG and PHP

GnuPG and PHP

Customers that would like to use GnuPG will need to know a few details about running GnuPG before they start using it:

Generating Keys

To generate a key, you will need to create a .gnupg folder, giving permissions for write access:
mkdir .gnupg
chmod 777 .gnupg
Next is to generate a key (follow the options filling out all details):
gpg --gen-key
To make sure that your key was successfully saved, type:
gpg --list-keys

Set the permissions for the .gnupg directory

cd .gnupg
chmod 604 random_seed
chmod 644 pubring.gpg
chmod 644 trustdb.gpg

Move away the secring.gpg off the server into a secure place (e.g. your PC). Make sure this file doesn't reside on the web server as it contains your private key that can be used to decrypt the message.

Using the GPG Command in PHP

You will need to state where the GnuPG key ring is saved:

In your scripts, you will also need to use the full path to the GnuPG bin file:
$command = "/usr/local/bin/gpg  -a --always-trust --batch --no-secmem-warning -e -r 'Someone (comment) <>' -o $outfile $infile";

*Note: The recipient, Someone (comment) <>, will need to be the same user you generated a key for.

Example of a PHP script setup to use GPG

// $pgpuser should be loaded in your public key ring so gnupg can find the correct key
$pgpuser = "";
$message = "Encrypt me, I'm the secret";

//Set this to your .gnupg directory inside your home directory

//create a unique file name
$infile = tempnam("/tmp", "PGP.asc");
$outfile = "$infile.asc";
$fp = fopen($infile, "w");
fwrite($fp, $message);

//this command encrypts the message - note the -e parameter to gpg.
$command = "/usr/local/bin/gpg -a --always-trust --batch --no-secmem-warning -e -r $pgpuser -o $outfile $infile";

//execute the gnupg command
exec($command, $output, $result);
$output = implode("\n", $output);

if (
$result == 0) {
    $fp = fopen($outfile, "r");
$fp||filesize ($outfile)==0) {
$result = -1;
    } else {
$output = fread ($fp, filesize ($outfile));

if (
$result != 0) {
"There's an error: <br>";



Article Details
Article ID: 133
Created On: 17 May 2007 05:48 AM
 Login [Lost Password] 
Remember Me:
Please note that the login and password to the support area is NOT the same as your hosting control panel login and password
 Article Options
Home | Register | Submit a Ticket | Knowledgebase | Downloads | Control Panel User's Guide | Server Status