Skip to main content

Generating a GPG key to your GitHub


What is GPG

GPG (GNU Privacy Guard) is an open-source software used for encrypting and signing data. GPG uses asymmetric encryption technology where the cryptographic keys are divided into two parts: a public key and a private key. The public key is used to encrypt data and only the user holding the private key can decrypt it. The private key is used for digital signature which proves that the data indeed comes from a specified sender and has not been tampered with.

Why recommend to use GPG to protect your git commit

There is a risk of Git commit being impersonated because it does not have default authentication mechanisms. If someone knows your name and email address, they can impersonate your commits in the Git repository, which can damage your reputation or lead to improper behavior in your name.

To avoid this, you can use GPG signatures to authenticate Git commits.

Setup GPG in mac

Install GPG

brew install gnupg

Generate key pair

All step set to default

gpg --full-generate-key --expert

Please select what kind of key you want:
   (1) RSA and RSA
   (2) DSA and Elgamal
   (3) DSA (sign only)
   (4) RSA (sign only)
   (7) DSA (set your own capabilities)
   (8) RSA (set your own capabilities)
   (9) ECC (sign and encrypt) *default*
  (10) ECC (sign only)
  (11) ECC (set your own capabilities)
  (13) Existing key
  (14) Existing key from card
Your selection?

Export key

Check the exiting key

gpg --list-secret-keys --keyid-format LONG

gpg: checking the trustdb
gpg: marginals needed: 3  completes needed: 1  trust model: pgp
gpg: depth: 0  valid:   1  signed:   0  trust: 0-, 0q, 0n, 0m, 0f, 1u
sec   ed25519/XXXXXXXXXXXX 2023-05-28 [SC]
uid                 [ultimate] SpiffyEight77
ssb   cv25519/XXXXXXXXXXXX 2023-05-28 [E]

Export the public key

gpg --armor --export XXXXXXXXXXXX

And then past it into GitHub SSH and GPG keys setting.

Setting the environment to the shell

echo 'export GPG_TTY=$(tty)' >> ~/.zshrc && source ~/.zshrc

Allow git to use the GPG key for signing

git config --global user.signingkey XXXXXXXXXXXXX

git config --global commit.gpgsign true

Export for backup (optional)

To export the public and secret key for backup and please keep it in a safe place

gpg --armor --output gpg_pub_key.gpg --export XXXXXXXXXXX
gpg --armor --output gpg_sec_key.gpg --export-secret-keys XXXXXXXXXXX

Import GPG keys (optional)

gpg import <key-id>