Signing Git commits

As part of my workflow, I regularly make commits to git repositories, be it GitHub or Azure Repos. I also realized how easy it is to spoof a commit in git. Having a signed commit is the best way to make sure the commits are coming from an authenticated and genuine source. This article will guide you through the steps to set up signed commits in git using gpg keys. This is tested on Ubuntu 18.04 and Ubuntu 20.04

Pre-Requisites

Before we get started, we need the below packages in our system to make this thing work.

  • build-essential

  • apt-transport-https

  • software-properties-common

  • ca-certificates

  • curl

  • git

  • gpg

  • gnupg

  • gpg-agent

  • pinentry-curses

Most packages would be already installed, just install any package that is missing from your system.

  • Generate GPG keys using the following command. When prompted for name and email address, make sure to use your Git/GitHub name and email address
gpg --full-generate-key
  • List the key using gpg --list-keys

  • Export the key using the below command. The public key needs to be imported into GitHub/Git

gpg --export --armor <email>
  • Configure Git to use your gpg keys
git config --global user.signingkey << YOUR KEY ID >>
git config --global commit.gpgsign true
  • Configure GPG to cache the password for your current session, else you will be prompted to unlock the key every time git tries to sign the commit.

  • Create a file ~/.gnupg/gpg-agent.conf and add the below lines

default-cache-ttl 86400
max-cache-ttl 86400
  • Create a file ~/.gnupg/gpg.conf and below lines to tell GPG to use agent for caching password
# Uncomment within config (or add this line)
# This tells gpg to use the gpg-agentuse-agent
use-agent
  • GPG might not be aware of which terminal to use for the password prompt. Add the below line in your ~/.profile or ~/.bashrc to make GPG aware of the terminal export GPG_TTY=$(tty)