Git commit signing adds a layer of authenticity to each commit by embedding a cryptographic signature. This signature helps verify that commits come from a trusted source, which is particularly valuable in open-source projects or any project where verifying the author’s identity is crucial. In this chapter, we’ll explore why commit signatures matter, how to generate and verify them, and practical tips for incorporating them into your Git workflow.
Commit signing requires a cryptographic key, commonly generated using GPG (GNU Privacy Guard) or SSH. GPG is more frequently used for commit signing.
sudo apt install gpg
brew install gnupg
Generating a GPG Key Once GPG is installed, generate a new GPG key to use with Git.
gpg --full-generate-key
gpg --list-secret-keys --keyid-format LONG
Associating the GPG Key with Git Once you have your GPG key, tell Git to use it for signing commits.
gpg --list-secret-keys --keyid-format LONG
Look for the key ID, typically displayed as a 16-character string.
Configure Git to use this key:
git config --global user.signingkey
Enabling Commit Signing by Default To ensure all commits are signed automatically, set the following configuration:
git config --global commit.gpgSign true
Creating a Signed Commit To sign a commit, use the -S
flag with git commit
:
git commit -S -m "Your commit message"
If you’ve set up GPG with a passphrase, you may be prompted to enter it.
Verifying a Signed Commit To verify a commit’s signature, use:
git log --show-signature
In the commit history, Git will display a message confirming whether the signature is valid, along with the key used.
Verifying All Commits in a Repository To verify all commit signatures in a repository’s history, use:
git log --show-signature
You can configure a Git repository to reject unsigned commits or commits from unverified sources.
For example, in GitHub, you can enforce signed commits as a branch protection rule:
git verify-commit
Commandgit verify-commit
explicitly verifies the signature of a specific commit. Useful in automated scripts or CI pipelines:
git verify-commit
export GPG_TTY=$(tty)
Keep your private key secure, as it verifies your identity in the commit history.
Enable a passphrase for your GPG key, which prevents unauthorized use if your key is compromised.
Encourage or require collaborators to sign their commits to maintain a trustworthy history.
Verifying commit signatures adds an essential layer of security and authenticity to a Git repository. With signed commits, project maintainers and collaborators can confidently track contributions and changes, knowing they are from verified sources. Happy coding !❤️