Bidhu Bhusan Patra
Bidhu Bhusan Patra

Reputation: 31

PGP encryption from PHP

If I run the command

gpg -e -r [email protected] my_secret_file.txt

from unix command prompt, it is working fine. But when I try to use the same command using PHP, it's not working :

$gpg = '/usr/bin/gpg';
$recipient = '[email protected]';
$secret_file = 'secret_file.txt';

echo shell_exec("$gpg -e -r $recipient $secret_file");

Please guide me for a solution.

Upvotes: 2

Views: 5091

Answers (3)

Antony P.
Antony P.

Reputation: 143

You can see the error by using the following command:

$output = exec("$gpg -e -r $recipient $secret_file 2>&1", $out); 
echo "<pre>$output</pre>";

this will guide you.

possible problem to look at:

  • the file you are trying to encrypt is not in the right path..
  • GnuPG is trying to write to the /root/.gnupg directory with "apache" as a user. Obvisouly this is not possible unless you change you access rights to this dir (not recommended).
  • you don't have the right access to the GnuPG root dir (where ever it is)
  • you don't have WRITE in the dir apache is trying to create the new file..

Let me know what your code outputs and I'll be able to help. I ran into this already, it is tedious.

Upvotes: 0

Carlos Campderr&#243;s
Carlos Campderr&#243;s

Reputation: 22982

Apart from permission issues as Demento suggests, it is also possible that the user the script runs as is not the same as when you work in the command line, and this user does not have the public key of [email protected], so it cannot encrypt the file for him. So... which user runs this script? Assuming it's www-data, if you do

carlos@server:~$ su - www-data
(insert www-data's password or do sudo su - www-data if sudo it's available)
www-data@server:~$ gpg --list-keys

do you see the key for [email protected]?

Upvotes: 3

Demento
Demento

Reputation: 4297

I tried your example on my machine and it works like expected. The result is an additional file in the local directory named secret_file.txt.gpg, encrypted for [email protected]. This confirms that your actual script is fine and there might be other issues present.

You will not see any output from the script itself, the encrypted file is generated in silence. The echo in the last line of your program does nothing, because gpg does not generate any output if there are no problems. You should take a look at the manual of shell_exec.

If the file is not created on your machine, it might be a permission issue. If you do not call the script from the command line but from a web application, the webserver user needs the appropriate permissions on the file system to create a new file.

Upvotes: 2

Related Questions