Automate encryption with GPG

Privacy

Privacy

This blogpost requires some familiarity with GPG.

Today I want to share the scripts for running GPG in the batch (unattended) mode. You can have a password on the keys if you want, but since this is the automated mode, you may want to use keys without a password. Irrespective of whether or not you use a password – use a separate set of keys that you will not use for anything that not batch processed. The scripts are primarily for Linux. If you need them for Windows, please read this and post any problems you face in comments section, and I will help.

The script for encryption is here:

#! /bin/sh
GNUPGHOME='/apps/gpg/'
export GNUPGHOME
gpg --batch -r <reciepient> --output $2 --passphrase-fd 3 --sign --encrypt $1 3</apps/gpg/passph

The first line shows the location of the shell – please change it according to where the shell is on your system. The second line has the location of the folder where the keys are located – the pubring.gpg and secring.gpg. In the last line, replace <reciepient> with the name on the reciepient key. The /apps/gpg/passph points to the location of the file containing the passphrase. The script will both sign and encrypt the file – change this to suit your needs. The script expects the name of the input file and the name of the output files as parameters in that order.

The script for decryption is here:

#! /bin/sh
GNUPGHOME='/apps/gpg/'
export GNUPGHOME
gpg --batch --passphrase-fd 3 --status-fd 1 --decrypt $1 3</apps/gpg/passph | grep '\[GNUPG:\] GOODSIG'
if [ $? -eq 0 ]; then
  gpg --batch --passphrase-fd 3 --output $2 --decrypt $1 3</apps/gpg/passph
fi

The first three lines are similar. Line 4 just checks if the file has a valid signature. If you want to skip this step remove lines 4, 5 and 7. No effort is made to see who signed the file. In my scenario, I could control the people who could sign by having only those public keys in the repository, and the repository could only be written to by ‘root’.

Please post comments in case of questions, concerns.

Share

―――――――――――X――――――――――

About the Author

18 Responses to “ Automate encryption with GPG ”

  1. Hi,
    I am working on decryting a pgp file using GnuPG.I want to do the same in a .NET C# Console Application.
    I am facing some problem,when i try to decrypt it prompts for the PassPhrase.I tried to pass the Passphrase from the application but its not working.I want to decrypt the file,stream the dataout.My code is below.If you can kindly help me on this.Here i manually put the passphrase & then i get the result in the Temp string variable.

    ——————-
    using System;
    using System.Collections.Generic;
    using System.Text;
    using System.Diagnostics;
    using System.IO;
    using System.Threading; // for Thread class

    namespace ConsoleApplication3
    {
    class Program
    {
    static void Main(string[] args)
    {

    string passphrase = “$Trans@RtA09″;

    Process myProcess = new Process();
    StreamWriter sw;
    StreamReader sr;
    StreamReader err;

    ProcessStartInfo myProcessStartInfo = new ProcessStartInfo(@”C:\gnupg\gpg.exe”);
    myProcessStartInfo.Arguments = “–decrypt C:/Transfer/test.gpg”;
    myProcessStartInfo.RedirectStandardError = true;
    myProcessStartInfo.RedirectStandardInput = true;
    myProcessStartInfo.RedirectStandardOutput = true;
    myProcessStartInfo.UseShellExecute = false;

    myProcess.StartInfo = myProcessStartInfo;

    myProcess.Start();
    sw = myProcess.StandardInput;
    sr = myProcess.StandardOutput;
    err = myProcess.StandardError;

    sw.AutoFlush = true;
    if (passphrase != null && passphrase != “”)
    {
    sw.WriteLine(passphrase);
    }

    sw.Close();
    String Temp = sr.ReadToEnd();
    Temp += err.ReadToEnd();
    }

    }
    —————————————–

  2. Hi,Thanks for replying.
    I tried,but no Luck :(
    below is the update code which i am using now.

    —————————————————————-
    using System;
    using System.Collections.Generic;
    using System.Text;
    using System.Diagnostics;
    using System.IO;
    using System.Threading; // for Thread class

    namespace ConsoleApplication3
    {
    class Program
    {
    static void Main(string[] args)
    {

    // string passphrase = “$Trans@RtA09″;

    Process myProcess = new Process();
    StreamReader sr;
    StreamReader err;

    ProcessStartInfo myProcessStartInfo = new ProcessStartInfo(@”C:\gnupg\gpg.exe”);
    // myProcessStartInfo.Arguments = “–decrypt C:/Transfer/test.gpg”;
    myProcessStartInfo.Arguments = “–batch –passphrase-fd 1 –-decrypt C:/Transfer/test.gpg < C:/Transfer/passph.txt”;
    myProcessStartInfo.RedirectStandardError = true;
    //myProcessStartInfo.RedirectStandardInput = true;
    myProcessStartInfo.RedirectStandardOutput = true;
    myProcessStartInfo.UseShellExecute = false;

    myProcess.StartInfo = myProcessStartInfo;

    myProcess.Start();
    sr = myProcess.StandardOutput;
    err = myProcess.StandardError;

    String Temp = sr.ReadToEnd();
    Temp += err.ReadToEnd();

    }

    }
    }

    ———————————————–
    If you know of any other approach of doing this in windows application environment?I mean decrypting the pgp file,by passing passPhrase from application,so it doesn’t prompt. and finally reading the output of the decrypting file.

    Thanks Again.

  3. Hi Hardeep,

    Do i need to write “-batch” in the command?

  4. Some of the options are appearing in the blog with a single dash – however, everywhere there should be a double dash. So there should be two dashes before batch, and two dashes before password-fd.

    Can you redirect the output from the gpg command and show what it says?

    Otherwise, try the batch process approach that I suggested.

  5. @User

    What I prefer to do, instead of calling GPG directly from the code is to create a batch file/shell script, and call the script from code. That is the best approach however, try changing this:

    myProcessStartInfo.Arguments = “–decrypt C:/Transfer/test.gpg”;

    to:

    myProcessStartInfo.Arguments = “–batch –-decrypt C:/Transfer/test.gpg”;

    Also, you will need to keep the passphrase blank with this approach. If it doesnt work you will need to do this:

    myProcessStartInfo.Arguments = “–batch –passphrase-fd 1 –-decrypt C:/Transfer/test.gpg <c:/Transfer/passph.txt”;

    Here the file c:/Transfer/passph.txt should contain the passphrase. Let me know what happens. YMMV (because you are on Windows).

  6. try this…

    try
    {
    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\\GNU\\GnuPG”;

    System.Diagnostics.Process process = System.Diagnostics.Process.Start(psi);
    // actually NEED to set this as a local string variable
    // and pass it – bombs otherwise!
    string sCommandLine = “echo ” + _passphrase +
    “| gpg.exe –passphrase-fd 0 -o \”" +
    outputFileNameFullPath + “\” –decrypt \”" +
    @”C:\Program Files\GNU\GnuPG\test.txt.gpg” + “\”";
    process.StandardInput.WriteLine(sCommandLine);
    process.StandardInput.Flush();
    process.StandardInput.Close();
    process.WaitForExit();
    process.Close();
    }

  7. Really insightful posts here. Nice info on GPG

  8. Greetings,

    need short (or longer) info. Since im no programmer, i need to know is it possible to do this:

    1. receive pgp txt file with passphrase inside
    2. decrypt the txt, “read” (remember) pass
    3. download (sFTP) another encrypted file
    4. decrypt it with gnupg
    5. call external decrypt application (command promt app) and pass some parameters to this app (paramters like pssphrase that is inside txt in step 1., decrypt file)

    well, that’s about it.

    If there’s anything missing that i haven’t stated, please let me know so i can update.

    I repeat, i’m not programmer, and code is not my game :-) . Just need info can it be done following the steps above.

    Tnx in advance.

  9. Yes, its possible. The only possible snag is the external application – what parameters it supports and how well it works. If you need a coder, maybe you can post a bid on rentacoder.com.

  10. Hi,
    I am running encryption in a SSIS package similar to above and it works well. The problem I have is if I pass in the full path to the file (such as “\\server\C$\Data\File\FileToEncrypt.txt”), this whole string becomes the filename of the encrypted file. When the other company decrypts the file, the filename is “\\server\C$\Data\Files\FileToEncrypt.txt”, instead of just “FileToEncrypt.txt”. Has anyone else had this problem? Do you know how to get around it? Is there a parameter to use for the directory path?

    Any help would be most appreciated. Thanks!!

  11. I have never faced this problem… sorry

  12. For anyone who may have the problem I had, a work around is to copy the file from the directory to the desktop (ie just to the file name with no path – by default it goes to the desktop). Then encrypt it from there (ie just pass in the same file name with no path). This worked for me.

    Cheers!!

  13. Thank you
    Nice info on GPG

  14. -bash-3.2$ gpg –batch –passphrase-fd 1 –output test.txt –decrypt test.txt.gpg 1</app/gpg/gpg_passph
    gpg: CAST5 encrypted data
    gpg: encrypted with 1 passphrase
    gpg: decryption failed: bad key

    I have copied passphrase in gpg_passph document. still I am getting above error.

    Did you ever come across the same?

    Thank you.

  15. @Suresh not sure why this is failing. Does it work when the batch mode is not used and a password is entered manually? Please try that. If it still doesnt work, the key may be bad.

  16. When tried to execute the first code of this page for encrypting it shows an error like ” cannot open /aaps/gpg/passph: No such file” Can some one help me?

  17. As explained in the writeup, you need to create a file containing the passphrase. The /apps/gpg/passph is a reference to this file. You need to replace this with a reference to a file where you have put the password. Since you have not created this file, the script is unable to find the reference.

  18. You look at this blog, you’ll find clear examples of how to do that.
    http://www.systemdeveloper.info/2013/11/decrypt-files-encrypted-with-gnupg-from.html

Leave a Reply

You can use these XHTML tags: <a href="" title=""> <abbr title=""> <acronym title=""> <blockquote cite=""> <code> <em> <strong>

Subscribe without commenting