Signing git commits with GPG on macOS for GitHub/GitLab

First, install GnuPG in order to create the keys for signing the git commits. Also install pinentry-mac which git/gpg requires later for displaying the passphrase dialog in order to decrypt your keys.

brew install gnupg pinentry-mac

Create a GPG key-pair:

gpg --full-gen-key

GPG will ask your for some more information. Use RSA/RSA (1) for the key kind, 4096 for the keysize, an expiration date for the keys, a name and email (this should be the same as the name and email you are using for your git commits). Feel free to also provide a comment for the key.

GPG will then ask you for a passphrase for the key. You will have to enter this passphrase again later, for signing commits.

Have a look at the list of key available:

gpg --list-secret-keys --keyid-format LONG

You should see the key you just generated, something similar to this:

sec   rsa4096/7FBDFC15C64A7A2C 2017-08-23 [SC]
      DC27153249AE8A79217C1C4C7FBDFC15C64A7A2C
uid              [ ultimativ ] Philipp Hoffmann <mail@philipphoffmann.de>
ssb   rsa4096/C7078828D2EA554B 2017-08-23 [E]

The sec line contains the key we need to configure for git (in my case this is 7FBDFC15C64A7A2C).
Configure git to use the GPG key for signing:

git config --global user.signingkey 7FBDFC15C64A7A2C

The last thing we need to do before we can sign commits, is to tell GPG to use pinentry-mac (which we installed earlier) in order to ask for the keys passphrase. Add the following line to ~/.gnupg/gpg-agent.conf:

pinentry-program /usr/local/bin/pinentry-mac

According to the documentation this is enough in order to sign your commits by adding the -S parameter whenever you create a commit.

git commit -S -m "..."

However, I found that after doing the above steps, git would reject every commit with the following error message:

error: gpg failed to sign the data
fatal: failed to write commit object

In my case (macOS Sierra 10.12.6) the solution was to add the following line to ~/.zshrc (or what have you):

export GPG_TTY=$(tty)

Now we should be able to create signed commits.
In order to display your commits as "Verified" in e.g. GitHub or GitLab you need to add the public key to your profile. You can print the public key to the console using:

gpg --armor --export DC27153249AE8A79217C1C4C7FBDFC15C64A7A2C

Note that this is the key ID from my example, make sure use yours (gpg --list-secret-keys --keyid-format LONG like above). The ID is in the line, after the line starting with sec.
Copy the key and add it to your GitHub/GitLab profile. Every signed commit you push should now be marked as "Verified".

One last hint: It is a bit cumbersome to always add the -S parameter for signing commits. Since git 2.0 there is a config setting for enabling git to sign all commits automatically:

git config --global commit.gpgsign true