Friday, June 13, 2008

Using GnuPG Agent on the Console

After hunting around on the internet to find a definitive answer on how to use GnuPG's Agent with a remote console (it's easy if you have X installed, even easier than that if you use the awesome Seahorse application with GNOME -- but pretty awkward if you have neither of the above)

I think i've come up with a usable solution, that uses gpg-agent's --write-env-file variable & does some minimal extra checking to make sure it doesn't get killed accidently, as well as correctly exporting the GPG_TTY variable so applications like mutt and the package builder applications on the console get the key handling right.

In your .bash_profile file, you need to add the following code near the end:


# Invoke GnuPG-Agent the first time we login.
# If it exists, use this:
if test -f $HOME/.gpg-agent-info && \
kill -0 `cut -d: -f 2 $HOME/.gpg-agent-info` 2>/dev/null; then
GPG_AGENT_INFO=`cat $HOME/.gpg-agent-info | cut -c 16-`
GPG_TTY=`tty`
export GPG_TTY
export GPG_AGENT_INFO
else
# Otherwise, it either hasn't been started, or was killed:
eval `gpg-agent --daemon --no-grab --write-env-file $HOME/.gpg-agent-info`
GPG_TTY=`tty`
export GPG_TTY
export GPG_AGENT_INFO
fi


Save the file, then logout and re-login and you should find gpg-agent has been started correctly.

note: We use the "| cut -c 16-" in the first section in order to remove the duplicated GPG_AGENT_INFO= string from the output that causes errors like:


gpg-agent: can't connect to `/home/paul/.gnupg/S.gpg-agent': No such file or directory
gpg-agent: can't connect to the agent: invalid value