Signing Git commits using GPG

Installation

To sign git commits on macOS, we need to install gpg and pinentry-mac (for storing passphrase in keychain).

$ brew install gpg pinentry-mac

Setup GPG

Run the following command to set pinentry-mac as pinentry-program in ~/.gnupg/gpg-agent.conf:

$ echo "pinentry-program $(brew --prefix)/bin/pinentry-mac" >> ~/.gnupg/gpg-agent.conf

Add the following line to ~/.gnupg/gpg.conf:

use-agent

Generate a GPG key

$ gpg --full-generate-key

Follow the instruction here: Generating a new GPG key

Confirm GPG is working

$ echo "hello world" | gpg --clearsign

We can restart gpg agent if needed:

$ gpgconf --kill gpg-agent
$ gpgconf --launch gpg-agent

Set GPG signing key in Git

List all the keys:

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

In the output find out the Key ID with the following format (assuming we picked RSA and 4096 bits key size when generating GPG key):

...
sec rsa4096/{KEY-ID}
...

Tell git which key to use:

$ git config --global user.signingkey {KEY-ID}

To sign all commits automatically:

$ git config --global commit.gpgsign true

To sign all tags automatically:

$ git config --global tag.forceSignAnnotated true

Add GPG key to GitHub

Print the GPG key:

$ gpg --armor --export {KEY-ID}

Copy the GPG key, beginning with -----BEGIN PGP PUBLIC KEY BLOCK----- and ending with -----END PGP PUBLIC KEY BLOCK-----, and add it to GitHub SSH and GPG keys Settings.

References