Search code examples
c#encryptioncmdgnupg

GPG error usage: gpg [options] [filename] during gpg --decrypt


I try to decrypt my file using GPG command:

        FileInfo info = new FileInfo(@"C:\Users\***\Desktop\files\file.pgp");

        string decryptedFileName = info.FullName.Substring(0, info.FullName.LastIndexOf('.')) + "Dec.TXT";
        string encryptedFileName = info.FullName;

        string password = "pass";

        System.Diagnostics.ProcessStartInfo psi = new System.Diagnostics.ProcessStartInfo("cmd.exe");
        psi.CreateNoWindow = true;
        psi.UseShellExecute = false;
        psi.RedirectStandardInput = true;
        psi.RedirectStandardOutput = true;
        psi.RedirectStandardError = true;

        psi.WorkingDirectory = @"C:\Program Files (x86)\GNU\GnuPG";
        System.Diagnostics.Process process = System.Diagnostics.Process.Start(psi);

        //string sCommandLine = @"echo " + password + "|gpg.exe --passphrase-fd 0 --batch --verbose --yes --output " + decryptedFileName + @" --decrypt """ + encryptedFileName;
        string sCommandLine = @"gpg --output " + decryptedFileName + @" --decrypt """ + encryptedFileName;

        process.StandardInput.WriteLine(sCommandLine);

        process.StandardInput.Flush();
        process.StandardInput.Close();

        process.WaitForExit();

        string result = process.StandardOutput.ReadToEnd();
        string error = process.StandardError.ReadToEnd();
        process.Close(); 

Unfortunately, i get following error: "usage: gpg [options] [filename]\r\n" Any idea what can be wrong?


Solution

  • The error message indicates that the parameters passed are wrong. Either one of the two strings is unset, or there is a problem with escaping of special characters.

    Dump sCommandLine (or add a debugger breakpoint there), probably one of the two file names are empty or badly escaped. This should easily help you at finding which variable is causing the problem.

    You might also want to consider using a native OpenPGP library like BouncyCastle instead of calling the GnuPG binary from C#.