GPG Error Code 2

GPG is always returning 2 at the result. My code is as follows

$cmd = "/usr/bin/gpg -a --recipient $to -e -o $outfile $infile";

Where outfile is the file where the encrypted data will be written and infile is the unencrypted data.

I don’t know why this is happening. Can anyone please tell me what’s wrong. Thanks.

Here is Solutions:

We have many solutions to this problem, But we recommend you to use the first solution because it is tested & true solution that will 100% work for you.

Solution 1

GPG is asking whether you want to continue on with the encryption using an unsigned key. Since no user can input Y it produces an error.

To fix this put the following switches

--yes and --always-trust

Solution 2

See this message:

It appears to be a permission problem. gpg is trying to access a directory that it can’t have access to, so it fails with a fatal error. (error code 2)

You can fix that by specifying a homedir directive with a directory writable by gpg. Like this:

$cmd = "/usr/bin/gpg -a --recipient $to -e -o $outfile $infile --homedir /path/to/dir";

Information from man gpg:

–homedir directory
Set the name of the home directory to directory

If this option is not used it defaults to
“~/.gnupg”. It does not make sense to
use this in a options file. This also
overrides the environment variable

Solution 3

You also might want to concider adding key to trusted keys list:

gpg.exe --edit-key KEY_NAME
5 (level of trust)

I’ve had some problems of --always-trust parameter not functioning properly on XP windows, this helped me solve the problem.

Solution 4

I had the same problem, but for the decoding command

At first and general, you can get the error message by redirecting stderr to stdout.

$cmd = "/usr/bin/gpg -a --recipient $to -e -o $outfile $infile 2>&1";

Then you can modify gpg’s parameters to suit your needs. Because I had a files encrypted with a key with pass phrase I had to add several parameters.

I started with

gpg  -o $out -d $path

But it complained, that it can not open tty, then with –no-tty it outputs some other errors and finally the command for decoding files with key with pass phrase is

gpg --batch --passphrase $pass_phrase --no-tty -o $outfile -d $path_to_encoded_file

I hope this helps someone.

Note: Use and implement solution 1 because this method fully tested our system.
Thank you 🙂

All methods was sourced from or, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply