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:
putenv("GNUPGHOME=/hsphere/local/home/<USERNAME>/.gnupg");

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) <someone@somewhere.com>' -o $outfile $infile";

*Note: The recipient, Someone (comment) <someone@somewhere.com>, 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 = "youremail@inthepublickeyring.com";
$message = "Encrypt me, I'm the secret";

//Set this to your .gnupg directory inside your home directory
putenv("GNUPGHOME=/hsphere/local/home/YOURUSERNAME/.gnupg");

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

//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);
@
unlink($infile);

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

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

echo
'<pre>';
echo
$output;
echo
'</pre>';

?>

Article Details
Article ID: 133
Created On: 17 May 2007 05:48 AM
 Back
 Login [Lost Password] 
Email:
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
 
 Search
 Article Options
Home | Register | Submit a Ticket | Knowledgebase | Downloads | Control Panel User's Guide | Server Status
Language: