GnuPG allows to encrypt and sign your data and communication, features a versatile key management system as well as access modules for all kinds of public key directories.
- 1 Installation
- 2 Environment variables
- 3 Configuration file
- 4 Basic keys management
- 5 Encrypt and decrypt
- 6 gpg-agent
- 7 Keysigning parties
- 8 Smartcards
- 9 Troubleshooting
- 10 = gpg hanged for all keyservers (when trying to receive keys)
- 11 See also
This will also install
/usr/bin/pinentry, which by default points to
$GNUPGHOME is used by GnuPG to point to the directory where all configuration files are stored. By default
$GNUPGHOME is not set and your
$HOME is used instead, thus you will find a
~/.gnupg directory right after the install. You may change this default setting by putting this line in one of your regular startup files:
GPG_AGENT_INFO used to locate the gpg-agent. Consists of 3 colon delimited fields:
- path to Unix Domain Socket
- PID of gpg-agent
- protocol version set to 1
GPG_AGENT_INFO=/tmp/gpg-eFqmSC/S.gpg-agent:7795:1. When starting the gpg-agent, this variable is set to the correct value.
GPG_AGENT_INFOhas been completely removed and the variable is ignored. Instead, a Unix domain socket with fixed name
$GNUPGHOME/S.gpg-agentis used. The agent is also started on demand by all tools requiring services from the agent.
~/.gnupg/gpg.conf. If you want to change the default location, either run gpg this way
$ gpg --homedir path/to/file or use
Append in this file any long options you want. Do not write the two dashes, but simply the name of the option and required arguments. You will find a skeleton file
Following is a basic configuration file:
default-key name # useful in case you manage several keys and want to set a default one keyring file # will add file to the current list of keyrings trustdb-name file # use file instead of the default trustdb homedir dir # set the name of the gnupg home dir to dir instead of ~/.gnupg display-charset utf-8 # bypass all translation and assume that the OS uses native UTF-8 encoding keyserver name # use name as your keyserver no-greeting # suppress the initial copyright message armor # create ASCII armored output. Default is binary OpenPGP format
If you want to setup some default options for new users, put configuration files in
/etc/skel/.gnupg/. When the new user is added in system, files from here will be copied to its GnuPG home directory. There is also a simple script called addgnupghome which you can use to create new GnuPG home directories for existing users:
# addgnupghome user1 user2
This will add the respective
/home/user2/.gnupg and copy the files from the skeleton directory to it. Users with existing GnuPG home directory are simply skipped.
Basic keys management
<user-id>is required in a command, it can be specified with your key ID, fingerprint, a part of your name or email address, etc. GnuPG is flexible on this.
Set stronger algorithms to be used first:
personal-digest-preferences SHA512 cert-digest-algo SHA512 default-preference-list SHA512 SHA384 SHA256 SHA224 AES256 AES192 AES CAST5 ZLIB BZIP2 ZIP Uncompressed personal-cipher-preferences TWOFISH CAMELLIA256 AES 3DES
Generate a private key by typing in a terminal:
$ gpg --full-gen-key
--full-gen-keyoption is available since -2.1.0.
--expertfor getting alternative ciphers available (like ECC Elliptic Curve)
You will be asked several questions. In general, most users will want both a RSA (sign only) and a RSA (encrypt only) key. A keysize of 2048 is sufficient. Using 4096 "gives us almost nothing, while costing us quite a lot."
While having an expiration date for subkeys is not technically necessary, it is considered good practice. A period of a year is generally good enough for the average user. This way even if you lose access to your keyring, it will allow others to know that it is no longer valid. Note that you can extend the expiry date after key creation without having to re-issue a new key.
Manage your key
- Running the
gpg --edit-key <user-id>command will present a menu which enables you to do most of your key management related tasks. Following is an example to set your expiration date:
$ gpg --edit-key <user-id> > key number > expire yyyy-mm-dd > save > quit
Some useful commands:
> passwd # change the passphrase > clean # compact any user ID that is no longer usable (e.g revoked or expired) > revkey # revoke a key > addkey # add a subkey to this key > expire # change the key expiration time
- Generate an ASCII version of your public key (e.g. to distribute it by e-mail):
$ gpg --armor --output public.key --export <user-id>
- Register your key with a public PGP key server, so that others can retrieve your key without having to contact you directly:
$ gpg --keyserver pgp.mit.edu --send-keys <key-id>
- Sign and encrypt for user Bob
$ gpg -se -r Bob file
- make a clear text signature
$ gpg --clearsign file
If you plan to use the same key across multiple devices, you may want to strip out your master key and only keep the bare minimum encryption subkey on less secure systems.
First, find out which subkey you want to export.
$ gpg -K
Select only that subkey to export.
$ gpg -a --export-secret-subkeys [subkey id]! > /tmp/subkey.gpg
At this point you could stop, but it is most likely a good idea to change the passphrase as well. Import the key into a temporary folder.
$ gpg --homedir /tmp/gpg --import /tmp/subkey.gpg $ gpg --homedir /tmp/gpg --edit-key <user-id> > passwd > save $ gpg --homedir /tmp/gpg -a --export-secret-subkeys [subkey id]! > /tmp/subkey.altpass.gpg
At this point, you can now use
/tmp/subkey.altpass.gpg on your other devices.
If you have set your subkeys to expire after a set time, you can create new ones. Do this a few weeks in advance to allow others to update their keyring.
- Create new subkey (repeat for both signing and encrypting key)
$ gpg --edit-key <user-id> > addkey
And answer the following questions it asks (see previous section for suggested settings).
- Save changes
- Update it to a keyserver.
$ gpg --keyserver pgp.mit.edu --send-keys <user-id>
- Import a public key to your public key ring:
$ gpg --import public.key
- Import a private key to your secret key ring:
$ gpg --import private.key
- Import key from a key server (if '--keyserver' is omitted, the default is used):
$ gpg --keyserver pgp.mit.edu --recv-keys <keyid>
- Keys in your public key ring:
$ gpg --list-keys
- Keys in your secret key ring:
$ gpg --list-secret-keys
Encrypt and decrypt
When encrypting or decrypting it is possible to have more than one private key in use. If this occurs you need to select the active key. This can be done by using the option
-u <user-id> or by using the option
--local-user <user-id>. This causes the default key to use to be replaced by wanted key.
To encrypt a file, use:
$ gpg --encrypt -o secret.tar.gpg secret.tar
- If you want to change recipient this can be done by the option
- You can use gnupg to encrypt your sensitive documents, but only individual files at a time. If you want to encrypt directories or a whole file-system you should consider using TrueCrypt or EncFS, though you can always tarball various files and then encrypt them.
To decrypt a file, use:
$ gpg --decrypt secret.tar.gpg
You will be prompted to enter your passphrase.
Encrypt a password
It can be useful to encrypt some password, so it will not be written in clear on a configuration file. A good example is your email password.
First create a file with your password. You need to leave one empty line after the password, otherwise gpg will return an error message when evaluating the file.
$ gpg -e -a -r <user-id> your_password_file
-e is for encrypt,
-a for armor (ASCII output),
-r for recipient user ID.
You will be left with a new
gpg-agent is mostly used as daemon to request and cache the password for the keychain. This is useful if GnuPG is used from an external program like a mail client. It can be activated by adding following line in
This tells GnuPG to use the agent whenever it needs the password. However, the agent needs to be already running. To autostart it, add the following entry to your
.bash_profile. Remember to change the envfile path if you changed your
envfile="$HOME/.gnupg/gpg-agent.env" if [[ -e "$envfile" ]] && kill -0 $(grep GPG_AGENT_INFO "$envfile" | cut -d: -f 2) 2>/dev/null; then eval "$(cat "$envfile")" else eval "$(gpg-agent --daemon --enable-ssh-support --write-env-file "$envfile")" fi export GPG_AGENT_INFO # the env file does not contain the export statement export SSH_AUTH_SOCK # enable gpg-agent for ssh
Log out of the session and log back in. Check if gpg-agent is activated:
$ pgrep gpg-agent
gpg-agent can be configured via
~/.gnupg/gpg-agent.conf file. The configuration options are listed in
man gpg-agent. For example you can change cache ttl for unused keys:
$ /usr/lib/gnupg/gpg-preset-passphrase --preset XXXXXX
where XXXX is the keygrip. You can get its value when running
gpg --with-keygrip -K. Passphrase will be stored until
gpg-agent is restarted. If you set up
default-cache-ttl value, it will take precedence.
Reload the agent
After changing the configuration, reload the agent by piping the
RELOADAGENT string to
$ echo RELOADAGENT | gpg-connect-agent
The shell should print
Finally, the agent needs to know how to ask the user for the password. This can be set in the gpg-agent configuration file.
The default uses a gtk dialog. There are other options - see
info pinentry. To change the dialog implementation set
pinentry-program configuration option:
# PIN entry program # pinentry-program /usr/bin/pinentry-curses # pinentry-program /usr/bin/pinentry-qt4 # pinentry-program /usr/bin/pinentry-kwallet pinentry-program /usr/bin/pinentry-gtk-2
/usr/bin/pinentry-kwalletyou have to install the package.
After making this change, reload the gpg-agent.
Start gpg-agent with systemd user
It is possible to use the Systemd/User facilities to start the agent.
Create a systemd unit file:
[Unit] Description=GnuPG private key agent IgnoreOnIsolate=true [Service] Type=forking ExecStart=/usr/bin/gpg-agent --daemon --homedir=%h/.config/gnupg ExecStop=/usr/bin/pkill gpg-agent Restart=on-abort [Install] WantedBy=MyTarget.target
- You may need to set some environment variables for the service, for example
GNUPGHOME. See systemd/User#Environment variables for details.
- if your gnupg home directory is ~/.gnupg, there is no need to specify its path
gpg -agentwill not use standard socket, but rather listen for a socket name
S.gpg-agentlocated in your gnupg home directory. We can thus forget any script to read an environment file and get the path of the random socket created in
To ensure your gpg-agent is running and listening to connection, simply run this command:
$ gpg-connect-agent. If your settings are valid, you will be on a prompt (enter bye and quit to close connection and leave)
Starting with GnuPG 2.1.0 the use of gpg-agent and pinentry is required; this may break backwards compatibility for passphrases piped in from STDIN using the
--passphrase-fd 0 commandline option. In order to have the same type of functionality as the older releases two things must be done:
First, edit the gpg-agent configuration to allow loopback pinentry mode:
Restart the gpg-agent process if it is running to let the change take effect.
Second, either the application needs to be updated to include a commandline parameter to use loopback mode like so:
$ gpg --pinentry-mode loopback ...
...or if this is not possible, add the option to the configuration:
To allow users to validate keys on the keyservers and in their keyrings (i.e. make sure they are from whom they claim to be), PGP/GPG uses a so-called "Web of Trust". There are many hacker events targeted to maintain this Web of Trust are held, including keysigning parties.
For an easier process of signing keys and sending signatures to the owners after a keysigning party, you can use the tool caff. It can be installed from the AUR with the packageAUR or bundled together with other useful tools in the package AUR. Either way, there will be a lot of dependencies installing from the AUR. Alternatively you can install them from CPAN with
cpanm Any::Moose cpanm GnuPG::Interface
pcscd.servicehas to be running.
GnuPG uses scdaemon as an interface to your smartcard reader, please refer to the man page for details.
GnuPG only setups
If you do not plan to use other cards but those based on GnuPG, you should check the
reader-port parameter in
~/.gnupg/scdaemon.conf. The value '0' refers to the first available serial port reader and a value of '32768' (default) refers to the first USB reader.
GnuPG together with OpenSC
If you are using any smartcard with an opensc driver (e.g.: ID cards from some countries) you should pay some attention to GnuPG configuration. Out of the box you might receive a message like this when using
gpg: selecting openpgp failed: ec=6.108
By default, scdaemon will try to connect directly to the device. This connection will fail if the reader is being used by another process. For example: the pcscd daemon used by OpenSC. To cope with this situation we should use the same underlying driver as opensc so they can work well together. In order to point scdaemon to use pcscd you should remove
~/.gnupg/scdaemon.conf, specify the location to
libpcsclite.so library and disable ccid so we make sure that we use pcscd:
pcsc-driver /usr/lib/libpcsclite.so card-timeout 5 disable-ccid
man scdaemon if you do not use OpenSC.
Not enough random bytes available
When generating a key, gpg can run into this error:
Not enough random bytes available. Please do some other work to give the OS a chance to collect more entropy!
To check the available entropy, check the kernel parameters:
A healthy Linux system with a lot of entropy available will have return close to the full 4,096 bits of entropy. If the value returned is less than 200, the system is running low on entropy.
To solve it, remember you do not often need to create keys and best just do what the message suggests (e.g. create disk activity, move the mouse, edit the wiki - all will create entropy). If that does not help, check which service is using up the entropy and consider stopping it for the time. If that is no alternative, see Random number generation#Faster alternatives.
pinentry, you must have the proper permissions of the terminal device (e.g.
/dev/tty1) in use. However, with su (or sudo), the ownership stays with the original user, not the new one. This means that pinentry will fail, even as root. The fix is to change the permissions of the device at some point before the use of pinentry (i.e. using gpg with an agent). If doing gpg as root, simply change the ownership to root right before using gpg:
chown root /dev/ttyN # where N is the current tty
and then change it back after using gpg the first time. The equivalent is likely to be true with
ttyis not enough.
Agent complains end of file
The default pinentry program is pinentry-gtk-2, which needs a DBus session bus to run properly. See General troubleshooting#Session permissions for details.
Alternatively, you can use
pinentry-qt. See GnuPG#Pinentry.
KGpg configuration permissions
There have been issues with
~/.gnupg/ options. One issue might be a result of a deprecated options file, see the bug report.
Another user reported that KGpg failed to start until the
~/.gnupg folder is set to
drwxr-xr-x permissions. If you require this work-around, ensure that the directory contents retain
-rw------- permissions! Further, report it as a bug to the developers.
Conflicts between gnome-keyring and gpg-agent
While the Gnome keyring implements a GPG agent component, as of GnuPG version 2.1, GnuPG ignores the
GPG_AGENT_INFO environment variable, so that Gnome keyring can no longer be used as a GPG agent.
mutt and gpg
To be asked for your GnuPG password only once per session as of GnuPG 2.1, see this forum thread.
"Lost" keys, upgrading to gnupg version 2.1
gpg --list-keys fails to show keys that used to be there, and applications complain about missing or invalid keys, some keys may not have been migrated to the new format.
Please read GnuPG invalid packet workaround. Basically, it says that there is a bug with keys in the old
secring.gpg files, which have now been superseded by the new
pubring.kbx file and the
private-keys-v1.d/ subdirectory and files. Your missing keys can be recovered with the following commnads:
$ cd $ cp -r .gnupg gnupgOLD $ gpg --export-ownertrust > otrust.txt $ gpg --import .gnupg/pubring.gpg $ gpg --import-ownertrust otrust.txt $ gpg --list-keys
= gpg hanged for all keyservers (when trying to receive keys)
If gpg hanged with a certain keyserver when trying to receive keys, you might need to kill dirmngr in order to get access to other keyservers which are actually working, otherwise it might keeping hanging for all of them.