Did you know you can sign your code in Git using a GPG key? A lot of programmers don't know they can sign their Git commits using a signature created by themselves.
Introduction
You can use any name or email when you create a Git commit, but you can't sign a commit with a GPG key that doesn't belong to you.
What is GPG?
The GNU Privacy Guard is an implementation of the OpenPGP standard and allows you to encrypt and sign your data and communications.
This is fully integrated with Git and you can automatically sign your code with it.
You can create a GPG key following this guide in GitHub. Remember that you should register it in GitHub, or GitLab.
Should I sign every commit?
There is a discussion about this, because Linus Torvalds says that when you're signing a Git tag 🏷️, you're validating all the commits in the release, signed or not. If you automatically sign every commit in the repository, the source of the signature loses its sense.
On the other hand, some Linux distros, like Arch Linux, uses Arch User (Git) Repositories made by users to build non-official supported packages. I mean, if you're compiling and installing a package via another user's instructions maybe you like the idea of the authors signing their work. ⚠️
I personally like the idea of signing my open source contributions, because that's a proof of my work. Anyway, if you use GitHub to squash your commits before merging a pull request, GitHub replaces all your commits, signed or not, by a commit made by itself and signed with the GitHub GPG key. The same happens when you create code releases via the GitHub web interface.
How to sign a Git commit?
First, get your key ID and copy it.
gpg --list-secret-keys --keyid-format=long
Then, tell Git your GPG key.
git config --global user.signingkey 3AA5C34371567BD2
Now, you can sign using the -S
argument
git commit -S -am <your_commit_message>
and it's done! 🚀
💡 To sign every commit automatically you can use the following configuration without needing the -S
flag:
git config --global commit.gpgsign true
How to sign a Git tag?
When you create a tag locally you should add the --sign
argument.
git tag --sign <tag_name>
Also, you can turn on this using the following Git configuration setting:
git config --global tag.gpgsign true
💡 If you only want to apply this for the repository in the current directory, remove the --global
argument.
Conclusion
If you work in the open source world it's a really good practice to sign your releases using a GPG key. If your work is consumed from a branch instead of a Git tag, perhaps you should sign every commit.
And, if you work in a closed source repository, you can add a rule in your CI/CD tools to only allow releases with specific GPG keys.