Search code examples
c#processgnupg

GnuPG Encryption is not working with Process error Code 2


I have the below code where this encryption code works fine (creating encrypted file) when it is called through Command Prompt and the same is not working when it is in Console Application.

var destFilePath = @"D:\test.gpg";
var recipient = "test@test.com";
var sourceFilePath = @"D:\test.txt";
var proc = new Process
           {
                StartInfo = new ProcessStartInfo
                {
                    FileName = "cmd.exe",
                    Arguments = string.Format("gpg2 --output {0} --encrypt --recipient {1} {2}",
                                                destFilePath, recipient, sourceFilePath),
                    UseShellExecute = false,
                    RedirectStandardError = true,
                    RedirectStandardInput = true,
                    RedirectStandardOutput = true,
                    CreateNoWindow = true,
                    WorkingDirectory = @"C:\Program Files (x86)\GNU\GnuPG"
                }
            };

            proc.Start();
            proc.WaitForExit();
            int rc = proc.ExitCode;
            proc.Close();
            Console.WriteLine(rc.ToString());
            Console.ReadKey();

which is returning error code 2 in the ExitCode

Any Ideas would help!


Solution

  • from GPG Error Code 2:

    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

    its been a while since i used GPG but the order of arguments is normally not important as long as they are named

    which would give you something like this

    FileName = "gpg2.exe",
    Arguments = $"--output {destFilePath} --encrypt --yes --always-trust --recipient {recipient} {sourceFilePath}",
    

    note: that's C#6 formatting which is slightly easier to read