Signing Git Commits with GPG

GPG (GNU Privacy Guard) Setup and Usage Guide

What is GPG?

GPG (GNU Privacy Guard) is a cryptographic tool that allows users to encrypt and sign data, providing authentication and integrity verification. It is commonly used for secure email communication and verifying the authenticity of Git commits.


Installing GPG

MacOS

On MacOS, install GPG using Homebrew:

brew install gnupg

After installation, verify it with:

gpg --version

Windows

On Windows, install GPG by downloading Gpg4win from https://gnupg.org/download/. After installation, verify it by opening a command prompt and running:

gpg --version

Generating a New GPG Key

To create a new GPG key for signing Git commits, run:

gpg --full-generate-key

Follow the prompts:

  • Key type: Select RSA and RSA (default)

  • Key size: Enter 4096 for maximum security

  • Expiration: Choose a duration (e.g., 1y for one year)

  • User ID: Provide your real name and email address

  • Passphrase: Enter a secure passphrase to protect your key

After generation, list your keys with:

Find the newly created key and note the key ID, which appears as:


Configuring Git to Sign Commits

Set Your GPG Key in Git

Replace XXXXXXXXXXXXXXXX with your actual key ID:

Enable automatic signing of commits:

To verify your configuration:

Export Your Public Key

To use the GPG key for GitHub or other services, export it:

Copy the output and add it to GitHub → Settings → SSH and GPG keys → New GPG Key (GitHub Link).


Testing GPG Signing with Git

To test your setup, create and sign a commit:

If successful, GitHub will display a "Verified" label next to the commit.


Additional GPG Commands

Listing GPG Keys

To list your keys:

To list secret (private) keys:

Backing Up Your GPG Key

To back up your private key:

Store this file securely.

To back up your public key:

Importing a GPG Key

To import a key from a file:

Revoking a GPG Key

If a key is compromised or lost, revoke it:

Then, import the revocation certificate:


Troubleshooting

Check if the GPG Agent is Running

If you encounter issues signing commits, restart the GPG agent:

Ensure Git is Using the Correct GPG Program

Run:

For GPG version 2.x, set:

Manually Sign a File to Test GPG

If successful, this generates a signed file testfile.txt.asc.


Conclusion

Setting up GPG for Git signing ensures the integrity and authenticity of commits. By following this guide, developers can securely sign commits and contribute to repositories with verified identities.

Last updated