How do I use gpg-agent as with ssh-agent+ssh-add?

I decided to have a look at this again and found out how it works. GPG uses the terminology "cache" for storing passwords. Two constraints can be imposed on the maximum storage time:

  • The time to keep a passphrase since the key was initially added.
  • The time to keep a passphrase since it was last accessed.

In addition, two variations exist for both constraints, one for GPG keys and one for SSH keys (if support was enabled).

The relevant manual page entries from gpg-agent(1):

   --default-cache-ttl n
          Set  the  time a cache entry is valid to n seconds.  The default
          is 600 seconds.

   --default-cache-ttl-ssh n
          Set the time a cache entry used for SSH keys is valid to n  sec‐
          onds.  The default is 1800 seconds.

   --max-cache-ttl n
          Set the maximum time a cache entry is valid to n seconds.  After
          this time a cache entry will be expired  even  if  it  has  been
          accessed recently.  The default is 2 hours (7200 seconds).

   --max-cache-ttl-ssh n
          Set the maximum time a cache entry used for SSH keys is valid to
          n seconds.  After this time a cache entry will be  expired  even
          if  it has been accessed recently.  The default is 2 hours (7200
          seconds).

Passphrases are always cached (in memory, not on disk! Verified with a git repo of $HOME), so there is no explicit need for ssh-add. For example, signing dummy data triggers the cache already:

$ echo | gpg -s >/dev/null
(passphrase requested
$ echo | gpg -s >/dev/null
(signing proceeds without asking for passphrase)

To make permanent changes to the cache settings of gpg-agent, edit ~/.gnupg/gpg-agent.conf` and add something like:

default-cache-ttl  60     # Expire GPG keys when unused for 1 minute
max-cache-ttl     600     # Expire GPG keys after 10 minutes since addition

I have tried to enable SSH agent support by specifying enable-ssh-support, but this makes the gpg-agent ask you for another key to encrypt the key, and then stores your private key in ~/.gnupg/private-keys.d/. No go for me, I'll stick to a dual ssh-agent / gpg-agent approach then.

Some bonus tips:

  • SSH agent's equivalent of max-cache-ttl-ssh can be specified when adding the key, for example: ssh-add -t 600 ~/.ssh/id_rsa
  • To prevent storing the GPG passphrase in the agent, disable the agent. In newer GPG versions the option --no-use-agent is ignored, but you can prevent the agent from being used by clearing the related environment-variable. Some ways to do so:

    echo | GPG_AGENT_INFO= gpg -s         # temporary
    export GPG_AGENT_INFO=; echo | gpg -s # until the current shell is closed