Examples
Getting Key Information
<?php
putenv('GNUPGHOME=/home/sender/.gnupg');
// create new GnuPG object
$gpg = new gnupg();
// throw exception if error occurs
$gpg->seterrormode(gnupg::ERROR_EXCEPTION);
// get list of keys containing string 'example'
try {
$keys = $gpg->keyinfo('example');
print_r($info);
} catch (Exception $e) {
echo 'ERROR: ' . $e->getMessage();
}
?>
Encrypt a Simple Mail
<?php
// set path to keyring directory
// set path to keyring directory
putenv('GNUPGHOME=/home/sender/.gnupg');
// create new GnuPG object
$gpg = new gnupg();
// throw exception if error occurs
$gpg->seterrormode(gnupg::ERROR_EXCEPTION);
// recipient's email address
$recipient = '[email protected]';
// plaintext message
$plaintext =
"Dear Dave,\n
The answer is 42.\n
John";
// find key matching email address
// encrypt plaintext message
// display and also write to file
try {
$gpg->addencryptkey($recipient);
$ciphertext = $gpg->encrypt($plaintext);
echo '<pre>' . $ciphertext . '</pre>';
file_put_contents('/tmp/ciphertext.gpg', $ciphertext);
} catch (Exception $e) {
die('ERROR: ' . $e->getMessage());
}
?>
Decryption The Mail
<?php
// set path to keyring directory
putenv('GNUPGHOME=/home/recipient/.gnupg');
// create new GnuPG object
$gpg = new gnupg();
// throw exception if error occurs
$gpg->seterrormode(gnupg::ERROR_EXCEPTION);
// recipient's email address
$recipient = '[email protected]';
// ciphertext message
$ciphertext = file_get_contents('/tmp/ciphertext.gpg');
// register secret key by providing passphrase
// decrypt ciphertext with secret key
// display plaintext message
try {
$gpg->adddecryptkey($recipient, 'guessme');
$plaintext = $gpg->decrypt($ciphertext);
echo '<pre>' . $plaintext . '</pre>';
} catch (Exception $e) {
die('ERROR: ' . $e->getMessage());
}
?>