How to Set Up Commit and Tag Signing in Git Using GPG and SSH

Signing commits and tags ensures that the changes are genuinely made by you. This is an essential step for project security and transparency. In this article, I will guide you through configuring automatic commit and tag signing in Git and show you how to separate configurations for personal and work projects.


Main Git Configuration File

The main configuration file, ~/.gitconfig, defines general settings for all repositories. Here, you can specify your username, enable mandatory signing for commits and tags, and include additional configuration files for specific project groups.

Here’s an example of a basic configuration file:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
# ~/.gitconfig
[user]
  name = John Smith

[commit]
  gpgsign = true

[tag]
  gpgSign = true

[includeIf "gitdir:~/Personal/"]
  path = ~/Personal/.gitconfig

[includeIf "gitdir:~/Work/"]
  path = ~/Work/.gitconfig

With the [includeIf] directives, Git will automatically apply the appropriate configuration based on the repository’s location.


Configuration for Personal Projects

If you use SSH for signing in personal projects, the setup looks like this. In the configuration file ~/Personal/.gitconfig, you specify your personal email, set the signing format to ssh, and provide a command that allows Git to find the appropriate key in the ssh-agent.

1
2
3
4
5
6
7
8
9
# ~/Personal/.gitconfig
[user]
  email = [email protected]

[gpg]
  format = ssh

[gpg "ssh"]
  defaultKeyCommand = sh -c "ssh-add -L | awk '$3~/^personal@a\\.com$/{print \"key::\"$0}'"

This configuration ensures that Git uses the key already added to the ssh-agent, simplifying the signing process.


Configuration for Work Projects

For work projects, GPG is often used. In the configuration file ~/Work/.gitconfig, you define your work email and the GPG key ID to be used for signing.

If you don’t have a GPG key yet, you can create one using the following command:

1
gpg --full-gen-key

To get the key ID, run:

1
gpg --list-keys

Here’s an example configuration file for work projects:

1
2
3
4
5
6
7
# ~/Work/.gitconfig
[user]
  email = [email protected]
  signingKey = 35C1A64CD7FC0AB6EB66756B2445463C3234ECE1

[gpg]
  format = openpgp

This configuration ensures that commits and tags in work repositories are signed using the specified GPG key.


With these configurations, Git will automatically use the appropriate signing key depending on the repository. This helps maintain order and transparency when working with commits and tags.

Licensed under Apache License, Version 2.0
Last updated on Dec 10, 2024 14:01 +0200
All rights reserved
Built with Hugo
Theme Stack designed by Jimmy