To complete the examples below that use proc_open to encrypt a string using GPG, here is a decrypt function:
<?php
function gpg_decrypt($string, $secret) {
$homedir = ''; $tmp_file = '/tmp/gpg_tmp.asc' ; file_put_contents($tmp_file, $string);
$text = '';
$error = '';
$descriptorspec = array(
0 => array("pipe", "r"), 1 => array("pipe", "w"), 2 => array("pipe", "w") );
$command = 'gpg --homedir ' . $homedir . ' --batch --no-verbose --passphrase-fd 0 -d ' . $tmp_file . ' ';
$process = proc_open($command, $descriptorspec, $pipes);
if (is_resource($process)) {
fwrite($pipes[0], $secret);
fclose($pipes[0]);
while($s= fgets($pipes[1], 1024)) {
$text .= $s;
}
fclose($pipes[1]);
while($s= fgets($pipes[2], 1024)) {
$error .= $s . "\n";
}
fclose($pipes[2]);
}
file_put_contents($tmp_file, '');
if (preg_match('/decryption failed/i', $error)) {
return false;
} else {
return $text;
}
}
?>