Clicky

Harry R. Schwartz

Software engineer, nominal scientist, gentleman of the internet. Member, ←Hotline Webring→.


Automatically Signing Your Git Commits

Published 01 Nov 2014. Tags: beards, computer-science, security.

Lately there’s been a lot of interest in PGP over at thoughtbot, most recently exemplified by Caleb’s great blog post and an internal keysigning party.

I thought I’d join in by describing how you can automatically sign all of your git commits with your GPG key.

Signing your git commits is good practice. It unambiguously identifies you as the author of a commit. It’s not difficult to forge an email address on a commit, but forging a GPG signature is effectively impossible. If you’re looking for more motivation to sign your commits, try reading this horror story.

I’m going to assume that you’ve already got a GPG key set up and working; see Caleb’s blog post above if you don’t.

First, determine your key’s ID:

$ gpg --list-secret-keys
/Users/hrs/.gnupg/secring.gpg
-----------------------------
sec   4096R/25AE721B 2014-01-30
uid                  Harry R. Schwartz <hello@harryrschwartz.com>
uid                  Harry R. Schwartz <harry@thoughtbot.com>
ssb   4096R/49D82DA6 2014-01-30

Your ID is on the sec line: mine is 25AE721B.

Next, tell git which key to use by setting signingkey in your .gitconfig . Here’s an excerpt from my config:

[user]
  name = Harry Schwartz
  email = hello@harryrschwartz.com
  signingkey = 25AE721B

You can now sign your commits! As of version 1.7.9, git commit accepts the -S option to attach a signature to your commits. So, for example:

$ git commit -S -m "My fancy signed commit"

This prompts me for my GPG passphrase and commits my code with a signature.

git log doesn’t display signatures by default, but you can force it to with the --show-signature option:

$ git log --show-signature
commit 949a3dc31152fd3bfa83355d48d3078b55f0b11c
gpg: Signature made Sat Nov  1 18:07:44 2014 EDT using RSA key ID 25AE721B
gpg: Good signature from "Harry R. Schwartz <harry@thoughtbot.com>"
gpg:                 aka "Harry R. Schwartz <hello@harryrschwartz.com>"
Author: Harry Schwartz <hello@harryrschwartz.com>
Date:   Sat Nov 1 18:07:44 2014 -0400

    My fancy signed commit

Cool! But this is still a little unstable, since now you need to remember to add that -S option every time you commit. That’s unlikely to happen.

There are two solutions to this problem. Prior to git 2.0, you’d have to add aliases to your .gitconfig… something like:

[alias]
  amend = commit -S --amend
  cm = commit -S -m
  commit = commit -S

However, since git 2.0, that’s now unnecessary! Instead, you can configure the way the commit command works by adding the following snippet to your .gitconfig:

[commit]
  gpgsign = true

Boom, problem solved. All my commits are now signed. Nice!

To see exactly which changes I made, check the commit to my dotfiles.