14.11. Encrypting Email with GPG

Problem

You want to send encrypted email messages. For example, you take orders on your web site and need to send an email to your factory with order details for processing. By encrypting the email message, you prevent sensitive data such as credit card numbers from passing over the network in the clear.

Solution

Encrypt the body of the email message with GNU Privacy Guard (GPG) before sending it:

$message_body = escapeshellarg($message_body);
$gpg_path     = '/usr/local/bin/gpg';
$sender       = 'web@example.com';
$recipient    = 'ordertaker@example.com';
$home_dir     = '/home/web';
$user_env     = 'web';

$cmd = "echo $message_body | HOME=$home_dir USER=$user_env $gpg_path " .
       '--quiet --no-secmem-warning --encrypt --sign --armor ' .
       "--recipient $recipient --local-user $sender";

$message_body = `$cmd`;

mail($recipient,'Web Site Order',$message_body);

The email message can be decrypted by GPG, Pretty Good Privacy (PGP) or an email client plug-in that supports either program.

Discussion

PGP is a popular public key encryption program; GPG is an open-source program based on PGP. Because PGP in encumbered by a variety of patent and control issues, it’s often easier to use GPG.

The code in the Solution invokes /usr/local/bin/gpg to encrypt the message in $message_body. It uses the private key belonging to $sender and the public key belonging to $recipient. This means that only $recipient can decrypt the email message and when she does, she knows the message came from ...

Get PHP Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.