Commit Like a Pro: Signing Your Commits with an RSA Key

Commit Like a Pro: Signing Your Commits with an RSA Key

Learn how to sign Git commit messages with an RSA key on macOS and Linux. Step-by-step guide for GPG setup, commit signing, and GitHub integration.

Signing your commit messages adds a layer of trust and authenticity to your contributions, especially in collaborative projects, as it helps prevent unauthorized changes. It ensures others that the changes were indeed made by you and not tampered with. In this guide, we will walk through setting up commit signing using an RSA key on both macOS and Linux. We’ll cover package managers such as dnf, apt, zypper, and pacman, which are used to install software on different Linux distributions, to help you set up the necessary tools.


Installing GPG

macOS

For macOS, you can use Homebrew to install GPG:

brew install gnupg

Linux

On Linux, the installation method depends on your distribution. Use the appropriate command below:

Fedora (dnf)

sudo dnf install gnupg

Ubuntu/Debian (apt)

sudo apt install gnupg

openSUSE (zypper)

sudo zypper install gpg2

Arch Linux (pacman)

sudo pacman -S gnupg

Generating and Using an RSA Key

  1. Generate an RSA Key

Run the following command to create a new RSA key:

gpg --full-generate-key
  • Select "RSA and RSA" when prompted for the key type.
  • Choose a key size (2048 or 4096 bits is recommended).
  • Set an expiration date for your key if desired.
  • Provide your name and email address when prompted.
  1. Export Your GPG Key

Find your key ID by listing your keys:

gpg --list-secret-keys --keyid-format=long

Export your public key:

gpg --armor --export <your-key-id>

Share this key with others or upload it to a key server for verification.

  1. Configure Git

Tell Git to use your GPG key:

git config --global user.signingkey <your-key-id>
git config --global commit.gpgsign true
  • The first command sets your GPG key as the default signing key for Git commits.
  • The second command ensures all commits are signed by default, enhancing security and trust.
  1. Test Signing

Make a test commit to verify everything is working:

git commit -S -m "Test commit"

Adding Your GPG Key to GitHub

As you can guess, this must not be Github. Any service may use the same scenario. Let's continue with the most popular one. To link your GPG key with your GitHub account:

  1. Copy your public key: Run the following command to output your public key:
gpg --armor --export <your-key-id>
  1. Add the key to GitHub:
  1. Verify your commits: Push a signed commit to GitHub and verify that it displays a "Verified" badge next to the commit, which appears on the commit details page in your repository.

By signing your commits with an RSA key, you bolster the security and credibility of your work. Whether you’re on macOS or Linux, this guide should help you get up and running with commit signing seamlessly.