How to Use GPG Signing for Git Commits
To use
gpg signing for commits, first generate a GPG key and add it to your Git config with git config --global user.signingkey <key-id>. Then enable commit signing by running git config --global commit.gpgsign true, so all your commits are signed automatically.Syntax
Here is how you configure Git to sign commits with your GPG key:
git config --global user.signingkey <key-id>: Sets the GPG key ID Git will use to sign commits.git config --global commit.gpgsign true: Enables automatic signing of all commits.git commit -S -m "message": Signs a single commit explicitly if auto-signing is off.
bash
git config --global user.signingkey <key-id> git config --global commit.gpgsign true git commit -S -m "Your commit message"
Example
This example shows generating a GPG key, configuring Git to use it, and making a signed commit.
bash
# Generate a new GPG key (follow prompts) gpg --full-generate-key # List your GPG keys and copy the key ID gpg --list-secret-keys --keyid-format LONG # Configure Git to use your GPG key KEY_ID=YOUR_KEY_ID_HERE git config --global user.signingkey $KEY_ID # Enable automatic signing of commits git config --global commit.gpgsign true # Make a signed commit git commit -S -m "Add signed commit example"
Output
gpg (GnuPG) 2.2.27
...
sec rsa4096/ABCDEF1234567890 2024-06-01 [SC]
uid Your Name <you@example.com>
...
[master 1a2b3c4] Add signed commit example
1 file changed, 1 insertion(+)
Common Pitfalls
Common mistakes when using GPG signing for commits include:
- Not setting the
user.signingkeyin Git, so Git doesn't know which key to use. - Forgetting to enable
commit.gpgsign, so commits are unsigned by default. - Using a GPG key without uploading the public key to a key server or Git hosting service, causing verification failures.
- Not configuring your Git email to match the GPG key's email, which can cause signature warnings.
bash
## Wrong: No signing key set git config --global commit.gpgsign true # Commit will fail to sign if no key is set ## Right: Set signing key and enable signing git config --global user.signingkey ABCDEF1234567890 git config --global commit.gpgsign true
Quick Reference
| Command | Purpose |
|---|---|
| gpg --full-generate-key | Create a new GPG key |
| gpg --list-secret-keys --keyid-format LONG | Show your GPG keys and IDs |
| git config --global user.signingkey | Set your GPG key for Git commits |
| git config --global commit.gpgsign true | Enable automatic commit signing |
| git commit -S -m "message" | Sign a single commit explicitly |
Key Takeaways
Generate a GPG key and configure Git with your key ID using user.signingkey.
Enable automatic commit signing with commit.gpgsign set to true.
Ensure your Git email matches your GPG key email to avoid signature warnings.
Upload your public GPG key to key servers or Git hosting services for verification.
Use git commit -S to sign individual commits if auto-signing is disabled.