GPG Keys as Environment Variables


#1

So, as it turns out I needed to decrypt a few files I’ve uploaded into my GitHub project using gpg (a popular encryption protocol & utility).

It turns out, though, that inserting a multi-variable string into an environment variable, and then trying to echo it into a file during the build process does not play well with gpg - I kept getting:

gpg: no valid OpenPGP data found.
gpg: Total number processed: 0

When trying to gpg --import file with my file (which is just an echo of the environment variable containing the gpg key).

Turns out, it was a newline chraracter (\n) thing. What solved it for me was (on Mac):

  1. First echo out the original key with $ instead of \n (meaning, wherever there’s a newline character, give me $). This can be done with cat -e PRIVATE_GPG_KEY.asc.
  2. Copy the output into a text editor, and replace all occurences of $ with \n.
  3. Insert that whole thing into an environment variable in CircleCI. I’ve called mine GPG_KEY.
  4. When you want to call it, first do echo -e $GPG_KEY > PRIVATE_GPG_KEY.asc.
  5. And then you can import it as usual: gpg --import PRIVATE_GPG_KEY.asc, and decrypt your files with gpg --decrypt ENCRYTED_FILE > DECRYPTED FILE.

Hope this helps someone!


#2

Good work. I was pondering the other day whether base64 encoding/decoding would work for the same purpose - I wonder if control characters would be converted into something screen-printable, without newlines.


#3

Actually tried doing it the base64 way, and gpg complained. A lot.