A step-by-step guide to generating a GPG key, configuring Git to use it for signing commits, adding the key to GitHub, verifying commit signatures, and setting up GPG agent for passphrase caching.
Generate a GPG Key
Open a terminal and run:
Follow the prompts to select the key type, key size (recommend 4096 bits for RSA), and expiration. Enter your name and email address.
Configure Git to Sign Commits with GPG Key
List GPG keys to find your key ID:
Look for the
sec
line followed by the key type and size, and then the key ID in this format:rsa4096/ABCDEFGH12345678 2021-01-01 [SC]
. The key ID in this example isABCDEFGH12345678
.Configure Git to use your GPG key:
You can now sign your commits using
git commit -S
.To sign all commits by default in all repositories, use:
Add Your GPG Key to GitHub
Via GitHub Web Interface
Export your public GPG key:
Copy the exported key (including the
-----BEGIN PGP PUBLIC KEY BLOCK-----
and-----END PGP PUBLIC KEY BLOCK-----
).Go to GitHub > Settings > SSH and GPG keys > New GPG key, paste your key, and save.
Via gh
CLI
Run to add your GPG key to GitHub:
Verify Commit Signature
To verify the signature of the latest commit, run:
Configure GPG Agent for Passphrase Caching
Edit
~/.gnupg/gpg-agent.conf
(create if it doesn’t exist):Add or modify the following lines:
default-cache-ttl 3600 max-cache-ttl 86400
Adjust the values according to your security and convenience needs.
Restart the GPG agent:
Stay in Your Terminal when Prompted for Passphrase
To avoid the passphrase prompt from opening a new window, add the following line to your shell configuration file (e.g., ~/.bashrc
, ~/.zshrc
):