Using git-crypt to store secrets in git

In this post I will show you how to store secrets in a git repository using git-crypt.

It goes without saying that secrets should not be committed to a git repository in plain text. They should be encrypted. git-crypt is a tool for that.

First of all, you will need GPG key set up. If you don’t have it:

  • install GnuPG and create a new key

    sudo apt install gnupg2
    gpg --quick-gen-key john.doe@something.com
    
  • export your key (gpg --export-secret-keys --armor john.doe@something.com >private-key.txt) and store it in a safe place for backup

Prepare git repository for storing secrets:

  • install git-crypt (on Ubuntu 18.04+ it is sudo apt install git-crypt)
  • go to your git repository and execute git-crypt init
  • then allow your user to access secrets of the repository: git-crypt add-gpg-user john.doe@something.com
  • create directory for storing secrets: mkdir secrets
  • enable encryption of this directory: echo 'secrets/** filter=git-crypt diff=git-crypt' >.gitattributes
  • unlock repository (decrypt all secrets in the repository): git-crypt unlock
  • create a new secret: echo hello >secrets/testsecret.txt
  • store changes: git add . && git commit -m "add test secret"
  • lock the repository (encrypt all the secrets): git-crypt lock
  • take a look inside of secrets/testsecret.txt and see that it is indeed encrypted
  • take a look at the history and see that the secret is not shown: git log -p secrets/testsecret.txt
    $ git log -p secrets/testsecret.txt
    commit f2609e2f099da28bca8cfa5285c8eca10c06bbbc (HEAD -> master, origin/master, origin/HEAD)
    Author: Your Name <you@example.com>
    Date:   Sun Jun 21 21:24:56 2020 +0000
    
        add test secret
    
    diff --git a/secrets/testsecret.txt b/secrets/testsecret.txt
    new file mode 100644
    index 0000000..fb4854e
    Binary files /dev/null and b/secrets/testsecret.txt differ
    
  • unlock repository again: git-crypt unlock
  • take a look inside of secrets/testsecret.txt and see that it is unencrypted now
  • take a look at the history and see that the secret is visible now: git log -p secrets/testsecret.txt
    $ git log -p secrets/testsecret.txt
    commit f2609e2f099da28bca8cfa5285c8eca10c06bbbc (HEAD -> master, origin/master, origin/HEAD)
    Author: Your Name <you@example.com>
    Date:   Sun Jun 21 21:24:56 2020 +0000
    
        add test secret
    
    diff --git a/secrets/testsecret.txt b/secrets/testsecret.txt
    new file mode 100644
    index 0000000..fb4854e
    --- /dev/null
    +++ b/secrets/testsecret.txt
    @@ -0,0 +1 @@
    +hello
    

When you push your changes to a remote repository it doesn’t matter if your local repository is locked or unlocked - in both cases only encrypted files will be transfered.

As you can see, git-crypt is quite easy to setup and use. I’ve been using it for storing secrets for about 4 years and never had problems with it. It works very well.