gpg-agent

gpg-agent is a background daemon that caches GPG passphrases, securely manages access to private keys, and can also be used as a replacement for ssh-agent, allowing GPG keys to be used for SSH authentication.

Configuration

The gpg-agent configuration file is located at ~/.gnupg/gpg-agent.conf.

default-cache-ttl
time a cache entry is valid after the last use. This timer resets on key use.
max-cache-ttl
maximum time a cache entry is valid. This timer counts from the first unlock.
enable-ssh-support
makes gpg-agent take the role of ssh-agent.
default-cache-ttl-ssh / max-cache-ttl-ssh
SSH-specific cache TTLs.
pinentry-program
points to the program that will be used for passphrase input.
# cache passwords for 2 hours (7200 seconds) after last use
default-cache-ttl 7200

# force a password prompt after 8 hours (28800 seconds) max
max-cache-ttl 28800

# enable gpg-agent to act as ssh-agent
enable-ssh-support

# set ssh ttls
default-cache-ttl-ssh 7200
max-cache-ttl-ssh 28800

# set pinentry-tty as password input program
pinentry-program /usr/bin/pinentry-tty

It is required to specify the GPG_TTY variable, so you have to add the following to .bashrc (or similar):

export GPG_TTY=$(tty)

To apply changes, just kill the agent. It will restart automatically:

gpgconf --kill gpg-agent

Using gpg-agent as ssh-agent

After adding enable-ssh-support, you must also configure some environment variables. The following should be appended to .bashrc (or similar).

# unset default ssh-agent variable to avoid conflicts
unset SSH_AGENT_PID

# point ssh to the gpg-agent socket
export SSH_AUTH_SOCK=$(gpgconf --list-dirs agent-ssh-socket)

Test the integration with the following command:

ssh-add -l

Adding SSH keys to gpg-agent

Add existing key

Note: the following commands require gpg-agent to be configured in place of the default ssh-agent.

ssh-add ~/.ssh/id_ed25519 # the file can be deleted. gpg-agent controls it now.

Using GPG key to authenticate in SSH

You must have an Authentication subkey [A]. Look for its keygrip and add it to ~/.gnupg/sshcontrol.

# list keys with keygrip
gpg --list-keys --with-keygrip

# append keygrip to sshcontrol
echo $KEYGRIP >> ~/.gnupg/sshcontrol

# print the public key to be used as authorized key
gpg --export-ssh-key $KEY_ID