Quick steps to automagically encrypt/decrypt files while pushing/pulling with git.

Installations

  1. We will use git-crypt to encrypt/decrypt files. Read more about git-crypt here.

    brew install git-crypt
    
    Code Snippet 1: Install git-crypt
  2. Install gpg

    brew install gpg
    
    Code Snippet 2: Install gpg

Setup git-crypt for your github repository

Clone your repository or cd into the folder where you have already cloned your repository. Initialise git-crypt in the folder.

git-crypt init
Code Snippet 3: Initialise git-crypt

It will create a .git-crypt folder which is used to store the generated security information.

Encrypting your files

git-crypt uses .gitattributes to identify the files to encrypt. It mainly uses the two operations: filter and diff

  • filter is used to invoke git-crypt to encrypt/decrypt while pushing/pulling the specified files
  • diff is used to invoke git-crypt while trying to diff the specified files

A sample .gitattributes file is shown below.

name-of-the-file-to-be-encrypted filter=git-crypt diff=git-crypt
name-of-the-second-file-to-be-encrypted filter=git-crypt diff=git-crypt
.
.
Code Snippet 4: Sample .gitattributes file

Create a .gitattributes file in your repo. Ensure that you update .gitattributes with the name of file to be encrypted. Now, update the to-be encrypted files and do git add, git commit & git push. Visit your github repo on your browser, to view the encrypted files. You can also use git-crypt status to quickly check the status of all the files.

If any of your git commands fail due to git-crypt, please refer to this github issue.

Providing a regex pattern instead of a file name will invoke git-crypt and encrypt all the matching files.

Saving your encryption settings

You can export your encryption key with git-crypt.

git-crypt export-key ./path-of-file-to-store-key
Code Snippet 5: Export your secret

Cloning to a new folder

If you clone your repo to a new folder, you will find that the files are not decrypted. To get your files back, unlock your repo with the exported key from the previous step.

git-crypt unlock ./path-of-file-to-store-key
Code Snippet 6: Unlock your github repo with the secret key