Skip to content

Instantly share code, notes, and snippets.

@andrew-stclair
Last active February 28, 2023 23:34
Show Gist options
  • Save andrew-stclair/e81181b1656070e51eecb1d9f8f7e201 to your computer and use it in GitHub Desktop.
Save andrew-stclair/e81181b1656070e51eecb1d9f8f7e201 to your computer and use it in GitHub Desktop.
Use a GPG key for SSH authentication

Use a GPG key for SSH authentication

These steps have been tested on MacOS. Linux should be similar if not the same. Good luck on Windows

Why would i do this?

  • If you are already using a GPG key to sign git commits or packages, it's one less key to securely backup.
  • GPG keys can be stored on OpenPGP Smart Cards like the YubiKey

Create a GPG key

Skip this step if you already have one that supports authentication

  • Run the following command
gpg --expert --full-generate-key
  • Select what ever type you want to use, as long as that type supports Authentication

    I selected ECC (set your own capabilities) (Options below are specific to this type of key)

  • Make sure the Authenticate capability is selected

    I selected Sign Certify Authenticate

  • Select an eliptic curve you wish to use

    I selected Brainpool P-512 but you may want to use another

  • Set an expiry

  • Enter in your name, email, and a comment

  • Generate the key and set a passphrase if desired/required

Enable the GPG SSH agent

  • Run the following to add enable-ssh-support to ~/.gnupg/gpg-agent.conf
echo enable-ssh-support >> ~/.gnupg/gpg-agent.conf 

Define GPG keys for SSH authentication

you may want to tell gpg what keys to use for ssh authentication, this way you wont need to use ssh-add to add them

to do this, you will add the keygrip for your gpg key to ~/.gnupg/sshcontrol

  • Run the following to get the keygrip identifier for your gpg key
gpg2 -K --with-keygrip
  • Copy the keygrip (the hexadecimal string after Keygrip = from the above command) and send it to ~/.gnupg/sshcontrol
echo <keygrip> >> ~/.gnupg/sshcontrol

Use GPG Agent for select hosts (Option 1)

Tell SSH to use the GPG agent

  • Get the output from gpgconf --list-dirs agent-ssh-socket

  • Add the following to your ~/.ssh/config file, either add the whole section if it does not already exist, or append the IdentityAgent and AddKeysToAgent to another section

Host *
      IdentityAgent <gpgconf output>
      AddKeysToAgent yes

Start GPG Agent on login

add the following to the end of either your ~/.bashrc, ~/.zshrc (or equivalent) or ~/.profile

gpg-agent --daemon

OR Use the GPG Agent for all hosts (Option 2)

add the following to the end of either your ~/.bashrc, ~/.zshrc (or equivalent) or ~/.profile

gpg-agent --daemon > /dev/null 2>&1
export SSH_AUTH_SOCK=$(gpgconf --list-dirs agent-ssh-socket)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment