Using git-crypt to encrypt secrets in a Git repository

You should never store secrets in you Git repositories. So, what do you do?

One option is to use git-crypt. It will automatically decrypt files in your local repository, and encrypt them in the remote repository (GitHub etc.).

Let’s see how it works. I assume you are on a Linux machine, and know about Git.

If you just want to see an encrypted file in a Git repository, you can go to my repository

Create a demo repository and try out git-crypt

Install the needed packages on your own machine.: apt-get install git-crypt gpg

Create a new Git repository somewhere like github

Clone the repository: git clone git@gitlab.com:me/git-crypt-demo.git

Enter the repository: cd git-crypt-demo

Initialize git-crypt in the repository: git-crypt init

A symetric key will be generated here: .git/git-crypt/keys/default

Create a base64 encoded version of your key. Store it somewhere safe (Like a password manager): cat .git/git-crypt/keys/default | base64 > git-grypt.key

Create file ‘secret.txt’ with the text ‘my secret txt’: echo "my secret txt" > secret.txt

Create file .gitattributes with a filter matching our secret file. This will tell git-crypt to encrypt the file: echo "secret.txt filter=git-crypt diff=git-crypt" > .gitattributes

Let’s see the status: git-crypt status

You should see something (very) similar to this:

not encrypted: .gitattributes
    encrypted: secret.txt
not encrypted: README.md

Looks good. secret.txt is (to be) encrypted.

Add the git-crypt config, and the file holding our secret to the repo: git add .gitattributes secret.txt

Commit the changes to the repo: git commit -a -m "Added encrypted secret"

Push to the remote: git push

Go to the webinterface for the repository, and look at the file ‘secret.txt’. The content should be encrypted.

Testing backed up key

Clone the repo again (To a different dir this time): git clone git@gitlab.com:me/git-crypt-demo.git

The file secret.txt should be encrypted (Because the key is not in this dir): cat secret.txt

Make dir for the key: mkdir -p .git/git-crypt/keys

Put your base64 encoded backed up key in file git-crypt.key

Decode the key, and save it as the default key in git-crypt: cat git-grypt.key | base64 -d > .git/git-crypt/keys/default

Use the key to decrypt the encrypted file(s) in the repo: git-crypt unlock .git/git-crypt/keys/default

You should now be able to see you decrypted secret: cat secret.txt