Encrypted email script using GPG and PHP

#First grab the public key into a file for the GPG enabled email address and import it into a new keyring called public_key.gpg
mkdir .gnupg to add the keyring files.  Probably outside httpdocs would be a good idea!
gpg –no-default-keyring –keyring /var/www/vhosts/secure.mydomain.com/httpsdocs/mydomain.com/.gnupg/public_key.gpg  –import public_key

#you can list keys in the keyring by:
gpg –no-default-keyring –keyring /var/www/vhosts/secure.mydomain.com/httpsdocs/mydomain.com/.gnupg/pubring.gpg –list-keys

#you may need to add a level of trust if necessary
gpg –no-default-keyring –keyring /var/www/vhosts/secure.mydomain.com/httpsdocs/mydomain.com/.gnupg/pubring.gpg –edit D630A872

#the PHP script would then be something along the lines of:


//create a unique file name
$infile = tempnam(“/tmp”, “PGP.asc”);
$outfile = $infile.”.asc”;

$body=’test email';
//write form variables to email
$fp = fopen($infile, “w”);
fwrite($fp, $body);

//set up the gnupg command. Note: Remember to put E-mail address on the gpg keyring.
$command = “/usr/bin/gpg –keyring ‘/var/www/vhosts/secure.mydomain.com/httpsdocs/mydomain.com/.gnupg/pubring.gpg’ –always-trust -a –recipient ‘Test User <t
est@mydomain.com>’ –encrypt -o $outfile $infile”;

//execute the gnupg command
system($command, $result);

//delete the unencrypted temp file
if ($result==0) {
$fp = fopen($outfile, “r”);

if(!$fp||filesize ($outfile)==0) {
$result = -1;

else {
//read the encrypted file
$contents = fread($fp, filesize ($outfile));
//delete the encrypted file

//send the email
mail (‘test@mydomain.com’, ‘encrypted’, $contents, ‘test@mydomain.com’);

print “<html>Thank you for your information. Your encrypted E-Mail has been sent.</html>”;

You can leave a response, or trackback from your own site.

Leave a Reply