GPG Keys as Environment Variables


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!


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.


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


thanks! would never figured this out. you can use a one liner on mac:

gpg -a --export-secret-keys <fingerprint> | cat -e | sed 's/\$/\\n/g' | pbcopy

(pbcopy copies the stdin to the clipboard)

and add it as env var and use it:

- run:
    name: import GPG key
    command: echo -e "$GPG_KEY" | gpg --import

btw, if you use a passphrase on your private key, the decryption can be done like this:

- run:
    name: decrypt secrets
    command: gpg --no-tty --batch --passphrase "$GPG_PASSPHRASE" --pinentry-mode loopback --output secrets.env --decrypt secrets.env.gpg
1 Like
closed #5

This topic was automatically closed 10 days after the last reply. New replies are no longer allowed.