Programming Tutorials

Decrypting files using GnuPG (GPG) via PHP

By: Darrell Brogdon in PHP Tutorials on 2011-01-24  

Decrypting an encrypted file with PHP and GnuPG can be a bit more complex than encrypting, since you are required to provide a GnuPG passphrase. The solution to having to type the passphrase every time the script is run lies in a handy little gpg switch called --passphrase-fd. This switch tells GnuPG to accept the passphrase from a file descriptor, which means that you can echo the passphrase and pipe the output to gpg, as seen in the following example.

<?php 
$gpg = '/usr/bin/gpg';
$passphrase = 'My secret pass phrase.';
$encrypted_file = 'foo.gpg';
$unencrypted_file = 'foo.txt';
echo shell_exec("echo $passphrase | $gpg --passphrase-fd 0 -o $unencrypted_file -d $encrypted_file");
?>

This script tells gpg to accept the passphrase from STDIN (indicated by the 0 following the switch) and decrypt the information into a file named "foo.txt".

As with encrypting information, you can leave off the -oswitch to gpg and let the decrypted data be captured inside a variable.

It should be noted that the -o switch should always come before the -d switch.






Add Comment

* Required information
1000

Comments

No comments yet. Be the first!

Most Viewed Articles (in PHP )

Function to convert strings to strict booleans in PHP

break out of an if() block in PHP

Exception in module wampmanager.exe at 000F15A0 in Windows 8

All possible substrings in a String in PHP

PHP ./configure RESULTING IN __rcp_thread_destroy@GLIBC_2_2_3_... AND UNRESOLVED REFERENCES WITH ORACLE OCI8

History and origin of PHP

use() in PHP

Decrypting files using GnuPG (GPG) via PHP

PHP Warning: Unknown(): Unable to load dynamic library '/usr/local/php4/lib/php/extensions/no-debug ......

How to make one else for two ifs in PHP

Setting cookies in PHP

Function to return number of digits of an integer in PHP

Cannot load /usr/local/apache/libexec/libphp4.so into server: ld.so.1:......

Convert a hex string into a 32-bit IEEE 754 float number in PHP

Installing PHP with Apache 2.x on HP UX 11i and configuring PHP with Oracle 9i

Latest Articles (in PHP)