[Git] How to sign git commits using GitHub and GPG keys
by Riley MacDonald, November 17, 2017

GPG stands for GNU Privacy Guard. GitHub now supports GPG keys and commit signing. This means you can configure GitHub to verify commits are coming from verified sources and reject them otherwise. I ran into a few issues setting this up. This post explains my configuration using OSX.

Install GPG using Homebrew
The following command installs the required gpg applications (gnupg: The GNU Privacy Guard suite of programs and gpg-agent: Secret key management for GnuPG). It also installs pinentry-mac which saves your gpg password choice to the OSX keychain (so you won’t need to enter a password each time you commit).

$ brew install gnupg gpg-agent pinentry-mac

Generate a new GPG key

$ gpg --gen-key

Add the GPG key to your local git configuration
Print the gpg key that was just generated to your prompt. Copy it and add it to your ~/.gitconfig.

# Print the secret keys
$ gpg --list-secret-keys
/Users/the.user/.gnupg/pubring.kbx
-----------------------------------------
sec   rsa2048 xxxx-xx-xx [SC] [expires: xxxx-xx-xx]
      ABDCDxxxxxxxxxxxxxxxxxxxxxxxxABCD
uid           [xxxx] User Name <user.name@email.com>
ssb   rsa2048 xxxx-xx-xx [E] [expires: xxxx-xx-xx]
 
# Copy the ABCDxxxx... key and provide it below
git config --global user.signingkey [secret-key-ABCD...]

Copy the key to the clipboard for GitHub
The following command will copy the gpg key for GitHub to your clipboard.

gpg --armor --export | pbcopy

Go to your GitHub profile settings “SSH and GPG keys Section”. Click “Add new GPG Key” and paste into the field. The key should start with -----BEGIN PGP PUBLIC KEY BLOCK----- and end with -----END PGP PUBLIC KEY BLOCK-----.

Potentially Optional: Export GPG_TTY
Initially I was unable to sign any commits. I would receive the following:

$ git commit -S -m "test"
error: gpg failed to sign the data fatal: 
failed to write commit object

To resolve this issue I needed to export GPG_TTY. I added the following to my ~/.bash_profile:

export GPG_TTY=$(tty)

Signing your commits
You can now sign your commits using one of the two following options. I chose to provide the -S argument instead of enabling commit.gpgsign because I’m not sure I want to sign every commit by default.

Option 1: Use the -S argument to enable signing for single commits:

git commit -S -m "Signed commit"

Optional 2: Or enable signing for every commit using:

git config --global commit.gpgsign true
Open the comment form

Leave a comment:

Comments will be reviewed before they are posted.

User Comments:

How to update GnuPG gpg key passwords - Riley MacDonald on 2018-02-08 15:08:11 said:
[…] an earlier post I described how to sign your git commits using GnuPG. This post describes how to update the gpg key […]