Howto to Encrypt Selected Files in a Git Repository
- I’d like to store my homelan configuration in Git, and I have been slowly working towards this.
- I’d like to have the repository public so that I can refer people to it for examples of working configurations for particular apps.
- I’d like to be able to safely store files which have confidential information in them (email addresses, passwords etc).
I spent a bit of time playing with
git-crypt yesterday, and it seems to provide a fairly simple solution for this. So I figured I’d share what I came up with.
All critique welcome.
git-crypt(Homebrew or Apt)
git-crypt export-key /tmp/gc.key
Add patterns to
.gitattributes for the files you want to be encrypted on commit (make sure you don’t encrypt any
.git files!), eg.
.env filter=git-crypt diff=git-crypt
*.sqlite3 filter=git-crypt diff=git-crypt
You should now have a repository where you can choose which files will be encrypted with the
.gitattributes file. Have a play with the below commands and push changes to your remote. Make sure things are encrypting as you expect.
git-crypt unlock /tmp/gc.key
Setting Up the Bitwarden CLI
- Install the Bitwarden CLI (Homebrew or manually install for Debian)
bw config server https://vaultwarden.example.com/(only required if self-hosting Bitwarden/Vaultwarden)
Using the Bitwarden CLI
Have a play with the below commands and make sure it’s working as you expect:
bw generate --passphrase --words 4
bw list items --search google --pretty
bw get password reddit.com
bw get item 28cd6f56-6395-4d15-ab29-34a64e14b9de
bw get totp facebook.com
Using Bitwarden to Store the Encryption Key
I’m using a symmetric encryption key (the same key encrypts and decrypts). You can use PGP to create asymmetric keys for
git-crypt, but since it's just me, I wanted to keep things simple.
For testing, it’s fine to have the encryption key on my filesystem (eg.
/tmp/gc.key), but I don’t want to do that in production. The key is also a binary file, so I can’t add it to the password field in Bitwarden. To store the password in Bitwarden, I’m going to convert it to text using the base64 utility.
base64 -i /tmp/gc.key
- Create a new login item in Bitwarden and Name it something simple (eg.
- Paste the base64 text into the Password field for git-crypt-homelan and Save.†
bw get password git-crypt-repo
If the final
bw command prints out the base64 text you pasted in earlier, you’re all set.
† Be careful that you don’t get any extra spaces when you paste the text into the Password field.
Putting it All Together
You can now safely unlock your repository on any host without having to copy your secret key around.
- Check that files are encrypted as you expect.
bw get password git-crypt-repo | base64 -d | git-crypt unlock -
And now check that
git-crypt has unencrypted files as you expect.
Congratulations, you’re done.