gitsecuritygit-crypt

How to use git-crypt with multiple keys


According to the man page:

git-crypt supports multiple keys per repository, allowing you to share different files with different sets of collaborators.

This is what I'm trying to accomplish. I only want certain collaborators to get access to certain parts of my code.

I want to be able to control who can access which file. Everyone using a common key isn't good for me because I want someone to be able to access file #1 but not file #2, and I want someone else to be able to access file #2 but not file #1.


Solution

  • I found the answer here:

    In addition to the implicit default key, git-crypt supports alternative keys which can be used to encrypt specific files and can be shared with specific GPG users. This is useful if you want to grant different collaborators access to different sets of files.

    To generate an alternative key named KEYNAME, pass the -k KEYNAME option to git-crypt init as follows:

    git-crypt init -k KEYNAME

    To encrypt a file with an alternative key, use the git-crypt-KEYNAME filter in .gitattributes as follows:

    secretfile filter=git-crypt-KEYNAME diff=git-crypt-KEYNAME

    To export an alternative key or share it with a GPG user, pass the -k KEYNAME option to git-crypt export-key or git-crypt add-gpg-user as follows:

    git-crypt export-key -k KEYNAME /path/to/keyfile

    git-crypt add-gpg-user -k KEYNAME GPG_USER_ID

    To unlock a repository with an alternative key, use git-crypt unlock normally. git-crypt will automatically determine which key is being used.

    A few notes:

    Use the -k option, not the --key-name option. I know the man page says they're the same, but they're not. Sometimes (I couldn't figure out why) the --key-name option is ignored, and you'll end up using the default key without any error messages.

    Also, I found that setting up access by adding GPG users is easier than sharing the symmetric key. This is because git-crypt will use the default key whenever you enter a command it doesn't quite understand, and you have no way of knowing which key you just encrypted the data with unless you push the changes, transfer the key to another computer, and test to see which key works.

    But if you add collaborators' public keys via GPG, you can easily see who has been added to which key using this command:

    pushd .git-crypt/keys/KEYNAME/0; for file in *.gpg; do echo "${file} : " && git log -- ${file} | sed -n 9p; done; popd
    

    This will print out a list of collaborators who have been added to KEYNAME. If only git-crypt would display success/failure messages, I would have solved this problem a lot sooner. But once I figured out how to view which user was being added to which key, I finally began understanding how git-crypt works, and was able to set everything up the right way.