You may remember in our previous articles, we learned how to commit changes in our project to Git. We also learned how to add tags to various commits in order to mark special milestones. Now we’re going to learn how to “sign” tags and commits with GPG.
Signing commits and tags is a way of verifying that a certain commit or tag has been verified by a certain user. This can be part of a contribution policy or as a protective measure to make sure that a commit is coming from a legitimate source.
Before you can sign tags and commits, you must make sure you have a GPG (or GnuPG) key available. This key is installed on your computer, and you can use it to sign and encrypt emails or to encrypt and decrypt files. In the example below, we will use this key to sign our tags and commits.
How to Add a GPG Key to Your User Configuration
In order to use the GPG key on your computer, you will need to add it to the config file. You may remember in the article on adding files to Git, we configured our username and email address we wanted to use for Git. We are going to follow a similar procedure here to add our key.
First, make sure you have a key ready to use.
Here is the output of the above command:
The key you will want to use for signing is your public key labelled “pub” above.
In order to add your key to the Git configuration, open your terminal app and run this command with the numbers following the forward slash after “pub”:
How to Sign Commits
Signing commits is easy. All we need to do is add the -S
option to the git commit
command.
- Open your project via command line or SSH
- Navigate to the project directory
- Use the
git commit
with the following options:
The -a
option adds changes to the staging index automatically, the -S
options signs the commit with your GPG key, and the -m
option allows you to put your commit message in quotes following the command.
The output of the above command will look similar to this:
How to Sign Tags
It’s easy to sign tags with the addition of the -s
option to the git tag
command. Remember that the tag will be assigned to the most recent commit.
- Open your project via command line or SSH
- Navigate to the project directory
- Enter the following command:
After you have signed your tag, you can view it later with the git show
command:
Well done! You now know how to sign tags and commits in Git using GPG keys.