Difference between revisions of "GnuPG"

From ArchWiki
Jump to: navigation, search
m (Fix minor formatting issue)
(pinentry: works fine in gnupg-2.1.12-2)
 
(333 intermediate revisions by 72 users not shown)
Line 1: Line 1:
[[Category:Security]]
+
[[Category:Encryption]]
GnuPG can be used to sign and encrypt files or mails.
+
[[es:GnuPG]]
 +
[[ja:GnuPG]]
 +
[[ru:GnuPG]]
 +
[[zh-cn:GnuPG]]
 +
{{Related articles start}}
 +
{{Related|pacman/Package signing}}
 +
{{Related|Disk encryption}}
 +
{{Related|List of applications/Security#Encryption, signing, steganography}}
 +
{{Related articles end}}
 +
 
 +
According to the [http://www.gnupg.org official website]:
 +
 
 +
:GnuPG is a complete and free implementation of the OpenPGP standard as defined by RFC4880 (also known as PGP). 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. GnuPG, also known as GPG, is a command line tool with features for easy integration with other applications. A wealth of frontend applications and libraries are available. Version 2 of GnuPG also provides support for S/MIME and Secure Shell (ssh).
  
 
== Installation ==
 
== Installation ==
  
[[pacman|Install]] {{Pkg|gnupg}}, available in the [[official repositories]].
+
[[Install]] the {{Pkg|gnupg}} package.
  
==Environment Variables==
+
This will also install {{Pkg|pinentry}}, a collection of simple PIN or passphrase entry dialogs which GnuPG uses for passphrase entry. Which ''pinentry'' dialog is used is determined by the symbolic link {{ic|/usr/bin/pinentry}}, which by default points to {{ic|/usr/bin/pinentry-gtk-2}}.
* {{ic|$GNUPGHOME}} is used by {{ic|GnuPGP}} to point to the directory where all configuration files are stored. By default {{ic|$GNUPGHOME}} isn't set and your {{ic|$HOME}} is used instead, thus you will find a {{ic|~/.gnupg}} directory right after the install. You may change this default setting by putting this line in one of your regular [[Startup_files|startup files]]
+
export GNUPGHOME="/path/to/gnupg/directory"
+
{{Note| by default, the gnupg directory has a particular [[Permissions]] set to ''600''. Only the owner of the directory has permission to read and write (''r'',''w''). This is for security purposes and should not be changed. In case this directory or any file inside it does not follow this security measure, you will get warnings about unsafe file and home directory permissions.}}
+
* {{ic|GPG_AGENT_INFO}} used to loacte the pgp-agent. Consists of 3 colon delimited fields:
+
**1. path to Unix Domain Socket
+
**2. PID of gpg-agent
+
**3. protocol version set to 1
+
E.g : {{ic|GPG_AGENT_INFO=/tmp/gpg-eFqmSC/S.gpg-agent:7795:1}}. When starting the gpg-agent, this variable is set to the correct value.
+
  
==Configuration file==
+
If you want to use a graphical frontend or program that integrates with GnuPG, see [[List of applications/Security#Encryption, signing, steganography]].
Default is {{ic|~/.gnupg/gpg.conf}}. If you want to change the default location, either run gpg this way {{ic|$ gpg --homedir ''path/to/file''}} or use {{ic|$GNUPGHOME}} variable.
+
  
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 {{ic|usr/share/gnupg/gpg-conf.skel}}.
+
== Configuration ==
Following is a basic configuration file:
+
 
{{hc|~/.gnupg/gpg.conf|
+
=== Directory location ===
default-key ''name''            # useful in case you manage several keys and want to set a default one
+
{{ic|$GNUPGHOME}} is used by GnuPG to point to the directory where its configuration files are stored. By default {{ic|$GNUPGHOME}} is not set and your {{ic|$HOME}} is used instead; thus, you will find a {{ic|~/.gnupg}} directory right after installation.
keyring ''file''                # will add ''file'' to the current list of keyrings
+
 
trustdb-name ''file''          # use ''file'' instead of the default trustdb
+
To change the default location, either run gpg this way {{ic|$ gpg --homedir ''path/to/file''}} or set {{ic|GNUPGHOME}} in one of your regular [[startup files]].
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
+
=== Configuration files ===
keyserver ''name''             # use ''name'' as your keyserver
+
 
no-greeting                # suppress the initial copyright message
+
The default configuration files are {{ic|~/.gnupg/gpg.conf}} and {{ic|~/.gnupg/dirmngr.conf}}.
armor                      # create ASCII armored output. Default is binary OpenPGP format
+
 
 +
By default, the gnupg directory has its [[permissions]] set to {{ic|700}} and the files it contains have their permissions set to {{ic|600}}. Only the owner of the directory has permission to read, write, and access the files. This is for security purposes and should not be changed. In case this directory or any file inside it does not follow this security measure, you will get warnings about unsafe file and home directory permissions.
 +
 
 +
Append to these files any long options you want. Do not write the two dashes, but simply the name of the option and required arguments. You will find skeleton files in {{ic|/usr/share/gnupg}}. These files are copied to {{ic|~/.gnupg}} the first time gpg is run if they do not exist there. Other examples are found in [[#See also]].
 +
 
 +
Additionally, [[pacman]] uses a different set of configuration files for package signature verification. See [[Pacman/Package signing]] for details.
 +
 
 +
=== Default options for new users ===
 +
 
 +
If you want to setup some default options for new users, put configuration files in {{ic|/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 {{ic|/home/user1/.gnupg}} and {{ic|/home/user2/.gnupg}} and copy the files from the skeleton directory to it. Users with existing GnuPG home directory are simply skipped.
 +
 
 +
== Usage ==
 +
 
 +
{{Note|Whenever a ''{{ic|<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.
 
}}
 
}}
  
== Basic keys management ==
+
=== Create key pair ===
  
=== Create key ===
+
Generate a key pair by typing in a terminal:
  
* Set stronger algorithms to be used first:
+
  $ gpg --full-gen-key
  #  printf "\npersonal-digest-preferences SHA512\ncert-digest-algo SHA512\ndefault-preference-list SHA512 SHA384 SHA256 SHA224 AES256 AES192 AES CAST5 ZLIB BZIP2 ZIP Uncompressed" >> ~/.gnupg/gpg.conf
+
  
* Generate a private key by typing in a terminal:
+
{{Tip|Use the {{ic|--expert}} option for getting alternative ciphers like [[wikipedia:Elliptic_curve_cryptography|ECC]].}}
# gpg --gen-key
+
  
You will be asked several questions. In general, most users will want both a RSA (sign only) and a RSA (encrypt only) key. It is advised t use a keysize of 4096 bits (default is 2048).
+
The command will prompt for answers to several questions. For general use most people will want:
  
While having an expiration date for subkeys isn't 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.
+
* the RSA (sign only) and a RSA (encrypt only) key.
 +
* a keysize of the default value (2048). A larger keysize of 4096 "gives us almost nothing, while costing us quite a lot"[https://www.gnupg.org/faq/gnupg-faq.html#no_default_of_rsa4096].
 +
* an expiration date. A period of a year is good enough for the average user. This way even if access is lost to the keyring, it will allow others to know that it is no longer valid. Later, if necessary, the expiration date can be extended without having to re-issue a new key.
 +
* your name and email address. You can add multiple identities to the same key later (''e.g.'', if you have multiple email addresses you want to associate with this key).
 +
* ''no'' optional comment. Since the semantics of the comment field are [https://lists.gnupg.org/pipermail/gnupg-devel/2015-July/030150.html not well-defined], it has limited value for identification.
 +
* [[Security#Choosing_secure_passwords|a secure passphrase]].
  
=== Manage your key ===
+
{{Note|The name and email address you enter here will be seen by anybody who imports your key.}}
* Running the {{ic|gpg --edit-key ''key ID''}} or {{ic|gpg --edit-key ''User_name_uid''}} 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_name_uid''
+
=== List keys ===
  > key ''number''
+
 
  > expire ''yyyy-mm-dd''
+
To list keys in your public key ring:
  > save
+
 
  > quit
+
  $ gpg --list-keys
 +
 
 +
To list keys in your secret key ring:
 +
 
 +
$ gpg --list-secret-keys
 +
 
 +
=== Export your public key ===
 +
 
 +
gpg's main usage is to ensure confidentiality of exchanged messages via public-key cryptography. With it each user distributes the public key of their keyring, which can be be used by others to encrypt messages to the user. The private key must ''always'' be kept private, otherwise confidentiality is broken. See [[w:Public-key cryptography]] for examples about the message exchange.
 +
 
 +
So, in order for others to send encrypted messages to you, they need your public key.
 +
 
 +
To generate an ASCII version of your public key (''e.g.'' to distribute it by e-mail):
 +
 
 +
  $ gpg --output ''public.key'' --armor --export ''<user-id>''
 +
 
 +
Alternatively, or in addition, you can [[#Use a keyserver]] to share your key.
 +
 
 +
{{Tip|Add {{ic|--no-emit-version}} to avoid printing the version number, or add the corresponding setting to your configuration file.}}
 +
 
 +
=== Import a public key ===
 +
 
 +
In order to encrypt messages to others, as well as verify their signatures, you need their public key. To import a public key with file name {{ic|''public.key''}} to your public key ring:
 +
 
 +
  $ gpg --import ''public.key''
 +
 
 +
Alternatively, [[#Use a keyserver]] to find a public key.
 +
 
 +
=== Use a keyserver ===
 +
 
 +
You can register your key with a public PGP key server, so that others can retrieve your key without having to contact you directly:
 +
 
 +
$ gpg --send-keys ''<key-id>''
 +
 
 +
To find out details of a key on the keyserver, without importing it, do:
 +
 
 +
$ gpg --search-keys ''<key-id>''
 +
 
 +
To import a key from a key server:
 +
 
 +
  $ gpg --recv-keys ''<key-id>''
 +
 
 +
{{Warning|Anyone can send keys to a keyserver, so you should not trust that the key you download actually belongs to the individual listed. You should verify the authenticity of the retrieved public key by comparing its fingerprint with one that the owner published on an independent source, such as their own blog or website, or contacting them by email, over the phone or in person. Using multiple authentication sources will increase the level of trust you can give to the downloaded key. See [[Wikipedia:Public key fingerprint]] for more information.}}
 +
 
 +
{{Tip|
 +
* Adding {{ic|keyserver-options auto-key-retrieve}} to {{ic|gpg.conf}} will automatically fetch keys from the key server as needed.
 +
* An alternative key server is {{ic|pool.sks-keyservers.net}} and can be specified with {{ic|keyserver}} in {{ic|dirmngr.conf}}.; see also [[wikipedia:Key server (cryptographic)#Keyserver examples]].
 +
* You can connect to the keyserver over [[Tor]] using {{ic|--use-tor}}. {{ic|hkp://jijrk5u4osbsr34t5.onion}} is the onion address for the sks-keyservers pool. [https://gnupg.org/blog/20151224-gnupg-in-november-and-december.html See this GnuPG blog post] for more information.
 +
* You can connect to a keyserver using a proxy by setting the {{ic|http_proxy}} environment variable and setting {{ic|honor-http-proxy}} in {{ic|dirmngr.conf}}. Alternatively, set {{ic|http-proxy ''host[:port]''}} in {{ic|dirmngr.conf}}, overriding the {{ic|http_proxy}} environment variable.}}
 +
 
 +
=== Encrypt and decrypt ===
 +
 
 +
You need to [[#Import a public key]] of a user before encrypting (options {{ic|--encrypt}} or {{ic|-e}}) a file or message to that recipient (options {{ic|--recipient}} or {{ic|-r}}).
 +
 
 +
To encrypt a file with the name ''doc'', use:
 +
 
 +
  $ gpg --recipient ''<user-id>'' --encrypt ''doc''
 +
 
 +
To decrypt (option {{ic|--decrypt}} or {{ic|-d}}) a file with the name ''doc.gpg'' encrypted with your public key, use:
 +
 
 +
$ gpg --output ''doc'' --decrypt ''doc.gpg''
 +
 
 +
''gpg'' will prompt you for your passphrase and then decrypt and write the data from ''doc.gpg'' to ''doc''. If you omit the {{ic|-o}} ({{ic|--output}}) option, ''gpg'' will write the decrypted data to stdout.
 +
 
 +
{{Tip|
 +
* Add {{ic|--armor}} to encrypt a file using ASCII armor (suitable for copying and pasting a message in text format)
 +
* Use {{ic|-R ''<user-id>''}} or {{ic|--hidden-recipient ''<user-id>''}} instead of {{ic|-r}} to not put the recipient key IDs in the encrypted message. This helps to hide the receivers of the message and is a limited countermeasure against traffic analysis.
 +
* Add {{ic|--no-emit-version}} to avoid printing the version number, or add the corresponding setting to your configuration file.
 +
* You can use gnupg to encrypt your sensitive documents by using your own user-id as recipient, but only individual files at a time, though you can always tarball various files and then encrypt the tarball. See also [[Disk encryption#Available methods]] if you want to encrypt directories or a whole file-system.}}
 +
 
 +
== Key maintenance ==
 +
 
 +
=== Backup your private key ===
 +
 
 +
To backup your private key do the following:
 +
 
 +
$ gpg --export-secret-keys --armor ''<user-id>'' > ''privkey.asc''
 +
 
 +
Note that ''gpg'' release 2.1 changed default behaviour so that the above command enforces a passphrase protection, even if you deliberately chose not to use one on key creation. This is because otherwise anyone who gains access to the above exported file would be able to encrypt and sign documents as if they were you ''without'' needing to know your passphrase.
 +
 
 +
{{Warning|The passphrase is usually the weakest link in protecting your secret key. Place the private key in a safe place on a different system/device, such as a locked container or encrypted drive. It is the only safety you have to regain control to your keyring in case of, for example, a drive failure, theft or worse.}}
 +
 
 +
To import the backup of your private key:
 +
$ gpg --allow-secret-key-import --import ''privkey.asc''
 +
 
 +
=== Edit your key ===
 +
 
 +
Running the {{ic|gpg --edit-key ''<user-id>''}} command will present a menu which enables you to do most of your key management related tasks.
  
Some useful commands:
+
Some useful commands in the edit key sub menu:
 
  > passwd      # change the passphrase
 
  > passwd      # change the passphrase
 
  > clean        # compact any user ID that is no longer usable (e.g revoked or expired)
 
  > clean        # compact any user ID that is no longer usable (e.g revoked or expired)
 
  > revkey      # revoke a key
 
  > revkey      # revoke a key
 
  > addkey      # add a subkey to this 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):
+
Type {{ic|help}} in the edit key sub menu for more commands.
$ gpg --armor --output public.key --export 'Your Name'
+
  
* Register your key with a public PGP key server, so that others can retrieve your key without having to contact you directly:
+
{{Tip|If you have multiple email accounts you can add each one of them as an identity, using {{ic|adduid}} command. You can then set your favourite one as {{ic|primary}}.}}
$ gpg  --keyserver pgp.mit.edu --send-keys ''Key Id''
+
  
* Sign and encrypt for user Bob
+
=== Exporting subkey ===
$ gpg se -r Bob ''file''
+
  
* make a clear text signature
+
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.
  $ gpg --clearsign ''file''
+
 
 +
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
 +
 
 +
{{Warning|If you forget to add the !, all of your subkeys will be exported.}}
 +
 
 +
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
 +
 
 +
{{Note|You will get a warning that the master key was not available and the password was not changed, but that can safely be ignored as the subkey password was.}}
 +
 
 +
At this point, you can now use {{ic|/tmp/subkey.altpass.gpg}} on your other devices.
  
 
=== Rotating subkeys ===
 
=== Rotating subkeys ===
Line 77: Line 205:
 
{{Warning|'''Never''' delete your expired or revoked subkeys unless you have a good reason. Doing so will cause you to lose the ability to decrypt files encrypted with the old subkey. Please '''only''' delete expired or revoked keys from other users to clean your keyring.}}
 
{{Warning|'''Never''' delete your expired or revoked subkeys unless you have a good reason. Doing so will cause you to lose the ability to decrypt files encrypted with the old subkey. Please '''only''' delete expired or revoked keys from other users to clean your keyring.}}
  
If you have set your subkeys to expire after a set time, you will have to create new ones. Do this a few weeks in advanced to allow others to update their keyring.
+
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)
+
{{Note|You do not need to create a new key simply because it is expired. You can extend the expiration date.}}
  # gpg --edit-key 'Your Name'
+
 
  # addkey
+
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).
 
And answer the following questions it asks (see previous section for suggested settings).
  
* Save changes
+
Save changes
  # save
+
 
 +
  > save
 +
 
 +
Update it to a keyserver.
  
* Update it to a keyserver.
+
  $ gpg --keyserver pgp.mit.edu --send-keys ''<user-id>''
  # gpg --keyserver pgp.mit.edu --send-keys ''Key Id''
+
  
 
{{Note|Revoking expired subkeys is unnecessary and arguably bad form. If you are constantly revoking keys, it may cause others to lack confidence in you.}}
 
{{Note|Revoking expired subkeys is unnecessary and arguably bad form. If you are constantly revoking keys, it may cause others to lack confidence in you.}}
  
=== Import key ===
+
== Signatures ==
  
* Import a public key to your public key ring:
+
Signatures certify and timestamp documents. If the document is modified, verification of the signature will fail. Unlike encryption which uses public keys to encrypt a document, signatures are created with the user's private key. The recipient of a signed document then verifies the signature using the sender's public key.
# gpg --import public.key
+
  
* Import a private key to your secret key ring:
+
=== Sign a file ===
# gpg --import private.key
+
  
=== List keys ===
+
To sign a file use the {{ic|--sign}} or {{ic|-s}} flag:
  
* Keys in your public key ring:
+
  $ gpg --output ''doc.sig'' --sign ''doc''
# gpg --list-keys
+
  
* Keys in your secret key ring:
+
The above also encrypts the file and stores it in binary format.
# gpg --list-secret-keys
+
  
== Basic usage ==
+
=== Clearsign a file or message ===
  
You can use gnupg to encrypt your sensitive documents, but only individual files at a time.
+
To sign a file without compressing it into binary format use:
  
For example, to decrypt a file, use:
+
  $ gpg --clearsign ''doc''
# gpg -d secret.tar.gpg
+
  
You'll be prompted to enter your passphrase.
+
This wraps the document into an ASCII-armored signature, but does not modify the document.
  
If you want to encrypt directories or a whole file-system you should consider using [[TrueCrypt]], though you can always tarball various files and then encrypt them.
+
=== Make a detached signature ===
  
=== Symmetric Encryption ===
+
To create a separate signature file to be distributed separately from the document or file itself, use the {{ic|--detach-sig}} flag:
 +
 
 +
  $ gpg --output ''doc.sig'' --detach-sig ''doc''
 +
 
 +
This method is often used in distributing software projects to allow users to verify that the program has not been modified by a third part.
 +
 
 +
=== Verify a signature ===
 +
 
 +
To verify a signature use the {{ic|--verify}} flag:
 +
 
 +
  $ gpg --verify ''doc.sig''
 +
 
 +
where {{ic|''doc.sig''}} is the signature you wish to verify.
 +
 
 +
To verify and decrypt a file at the same time, use the {{ic|--decrypt}} flag as you normally would in decrypting a file.
 +
 
 +
If you are verifying a detached signature, both the file and the signature must be present when verifying. For example, to verify Arch Linux's latest iso you would do:
 +
 
 +
  $ gpg --verify ''archlinux-<version>-dual.iso.sig''
 +
 
 +
where {{ic|''archlinux-<version>-dual.iso''}} must be located in the same directory.
  
 
== gpg-agent ==
 
== gpg-agent ==
  
{{Ic|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 {{ic|~/.gnupg/gpg.conf}}:
+
''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.
use-agent
+
  
This tells GnuPG to use the agent whenever it needs the password. However, the agent needs to run already. To autostart it, create the following file and make it executable, and remember to change the envfile path if you changed your $GNUPGHOME:
+
Starting with GnuPG 2.1.0 the use of ''gpg-agent'' is required. ''gpg-agent'' is started on-demand by the GnuPG tools, so there is usually no reason to start it manually.
{{hc|/etc/profile.d/gpg-agent.sh|2=<nowiki>
+
if [ $EUID -ne 0 ] ; then
+
    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
+
fi
+
</nowiki>}}
+
  
If you don't want gpg-agent to autostart for all users or just want to keep user daemons in the users own configuration files you can add the following entry to your {{Ic|.xinitrc}}:
+
=== Configuration ===
eval $(gpg-agent --daemon) &
+
  
Log out of your Xsession and log back in. Check if {{Ic|gpg-agent}} is activated
+
gpg-agent can be configured via {{ic|~/.gnupg/gpg-agent.conf}} file. The configuration options are listed in {{ic|man gpg-agent}}. For example you can change cache ttl for unused keys:
# pgrep agent
+
  
==== Pinentry ====
+
{{hc|~/.gnupg/gpg-agent.conf|
 +
default-cache-ttl 3600
 +
}}
  
Finally, the agent needs to know how to ask the user for the password. This can be set in {{ic|~/.gnupg/gpg-agent.conf}}
+
{{Tip|To cache your passphrase for the whole session, please run the following command:
 +
$ /usr/lib/gnupg/gpg-preset-passphrase --preset XXXXXX
  
The default uses a gtk dialog. To change it to ncurses or qt, set the following in the above file
+
where XXXX is the keygrip. You can get its value when running {{ic|gpg --with-keygrip -K}}. Passphrase will be stored until {{ic|gpg-agent}} is restarted. If you set up {{ic|default-cache-ttl}} value, it will take precedence.
 +
}}
  
pinentry-program /usr/bin/pinentry-curses
+
=== Reload the agent ===
  
or
+
After changing the configuration, reload the agent using ''gpg-connect-agent'':
  
  pinentry-program /usr/bin/pinentry-qt4
+
  $ gpg-connect-agent reloadagent /bye
  
For more options see {{Ic|man gpg-agent}} and {{ic|info pinentry}}.
+
The command should print {{ic|OK}}.
  
== Keysigning Parties ==
+
=== pinentry ===
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". To build this Web of Trust, many hacker events include keysigning parties.
+
  
The [https://en.wikipedia.org/wiki/Zimmermann%E2%80%93Sassaman_key-signing_protocol Zimmermann-Sassaman] key-signing protocol is a way of making these very effective.  [http://www.cryptnet.net/fdp/crypto/keysigning_party/en/keysigning_party.html Here] you'll find a How-To-article.
+
Finally, the agent needs to know how to ask the user for the password. This can be set in the gpg-agent configuration file.
  
=== Caff ===
+
The default uses a gtk dialog. There are other options - see {{ic|info pinentry}}. To change the dialog implementation set {{ic|pinentry-program}} configuration option:
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 package {{AUR|caff-svn}} or bundled together with other useful tools in the package {{AUR|signing-party-svn}}.
+
{{hc|~/.gnupg/gpg-agent.conf|
Either way, there will be a lot of dependencies installing from the AUR. Alternatively you can install them with
+
cpanm Any:Moose
+
cpanm GnuPG::Interface
+
  
To send the signatures to their owners you need a working [https://en.wikipedia.org/wiki/Message_transfer_agent MTA]. If you don't have already one, install [[SSMTP]].
+
# PIN entry program
 +
# pinentry-program /usr/bin/pinentry-curses
 +
# pinentry-program /usr/bin/pinentry-qt
 +
# pinentry-program /usr/bin/pinentry-kwallet
 +
 
 +
pinentry-program /usr/bin/pinentry-gtk-2
 +
}}
 +
 
 +
{{Tip|For using {{ic|/usr/bin/pinentry-kwallet}} you have to install the {{Pkg|kwalletcli}} 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:
 +
 
 +
{{hc|~/.config/systemd/user/gpg-agent.service|2=
 +
[Unit]
 +
Description=GnuPG private key agent
 +
IgnoreOnIsolate=true
 +
 
 +
[Service]
 +
Type=forking
 +
ExecStart=/usr/bin/gpg-agent --daemon
 +
Restart=on-abort
 +
 
 +
[Install]
 +
WantedBy=default.target
 +
}}
 +
 
 +
{{Note|If you use non-default value for the [[#GNUPGHOME]] environment variable, you need to pass it to the service. See [[systemd/User#Environment variables]] for details.}}
 +
 
 +
=== Unattended passphrase ===
 +
 
 +
Starting with GnuPG 2.1.0 the use of gpg-agent and pinentry is required, which may break backwards compatibility for passphrases piped in from STDIN using the {{ic|--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:
 +
 
 +
{{hc|1=~/.gnupg/gpg-agent.conf|2=
 +
allow-loopback-pinentry
 +
}}
 +
 
 +
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:
 +
 
 +
{{hc|1=~/.gnupg/gpg.conf|2=
 +
pinentry-mode loopback
 +
}}
 +
 
 +
{{Note|The upstream author indicates setting {{ic|pinentry-mode loopback}} in {{ic|gpg.conf}} may break other usage, using the commandline option should be preferred if at all possible. [https://bugs.g10code.com/gnupg/issue1772]}}
 +
 
 +
=== SSH agent ===
 +
 
 +
''gpg-agent'' has OpenSSH agent emulation. If you already use the GnuPG suite, you might consider using its agent to also cache your SSH keys.  Additionally, some users may prefer the PIN entry dialog GnuPG agent provides as part of its passphrase management.
 +
 
 +
To start using GnuPG agent for your SSH keys, enable SSH support in the {{ic|~/.gnupg/gpg-agent.conf}} file:
 +
 
 +
{{hc|~/.gnupg/gpg-agent.conf|
 +
enable-ssh-support
 +
}}
 +
 
 +
Next, make sure that ''gpg-agent'' is always started. Use either the [[#Start gpg-agent with systemd user|systemd user service]] or add the following to your {{ic|.bashrc}} file:
 +
 
 +
{{hc|~/.bashrc|<nowiki>
 +
# Start the gpg-agent if not already running
 +
if ! pgrep -x -u "${USER}" gpg-agent >/dev/null 2>&1; then
 +
  gpg-connect-agent /bye >/dev/null 2>&1
 +
fi
 +
</nowiki>}}
 +
 
 +
Then set {{ic|SSH_AUTH_SOCK}} so that SSH will use ''gpg-agent'' instead of ''ssh-agent'':
 +
 
 +
{{hc|~/.bashrc|<nowiki>
 +
# Set SSH to use gpg-agent
 +
unset SSH_AGENT_PID
 +
if [ "${gnupg_SSH_AUTH_SOCK_by:-0}" -ne $$ ]; then
 +
  export SSH_AUTH_SOCK="${HOME}/.gnupg/S.gpg-agent.ssh"
 +
fi
 +
</nowiki>}}
 +
 
 +
Also set the GPG TTY and refresh the TTY in case user has switched into an X session. Example:
 +
 
 +
{{Expansion|Not clear why this is necessary (even tha man page does not explain it).}}
 +
 
 +
{{hc|~/.bashrc|<nowiki>
 +
# Set GPG TTY
 +
export GPG_TTY=$(tty)
 +
 
 +
# Refresh gpg-agent tty in case user switches into an X session
 +
gpg-connect-agent updatestartuptty /bye >/dev/null
 +
</nowiki>}}
 +
 
 +
Once ''gpg-agent'' is running you can use ''ssh-add'' to approve keys, following the same steps as for [[SSH keys#ssh-agent|ssh-agent]]. The list of approved keys is stored in the {{ic|~/.gnupg/sshcontrol}} file. Once your key is approved, you will get a ''pinentry'' dialog every time your passphrase is needed. You can control passphrase caching in the {{ic|~/.gnupg/gpg-agent.conf}} file. The following example would have ''gpg-agent'' cache your keys for 3 hours:
 +
 
 +
{{hc|~/.gnupg/gpg-agent.conf|
 +
default-cache-ttl-ssh 10800
 +
}}
  
 
== Smartcards ==
 
== Smartcards ==
GnuPG uses scdaemon as an interface to your smartcard reader, please refer to {{Ic|scdaemon}} man page for details.
 
  
=== GnuPG only setups===
+
GnuPG uses ''scdaemon'' as an interface to your smartcard reader, please refer to the [[man page]] for details.
 +
 
 +
=== GnuPG only setups ===
 +
 
 +
{{Note| To allow scdaemon direct access to USB smarcard readers the optional dependency {{Pkg|libusb-compat}} have to be installed}}
 +
 
 
If you do not plan to use other cards but those based on GnuPG, you should check the {{Ic|reader-port}} parameter in {{ic|~/.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.
 
If you do not plan to use other cards but those based on GnuPG, you should check the {{Ic|reader-port}} parameter in {{ic|~/.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 ===
+
=== GnuPG with PSCD-Lite ===
 +
 
 +
{{Note|{{Pkg|pcsclite}} and {{Pkg|ccid}} have to be installed, and the contained [[systemd#Using units|systemd]] service {{ic|pcscd.service}} has to be running, or the socket {{ic|pscd.socket}} has to be listening.}}
 +
 
 +
PSCD-Lite is a daemon which handles access to smartcard (SCard API). If GnuPG's scdaemon fails to connect the smartcard directly (e.g. by using its integrated CCID support), it will fallback and try to find a smartcard using the PSCD-Lite driver.
 +
 
 +
==== Always use PSCD-Light ====
  
 
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 {{Ic|gpg --card-status}}
 
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 {{Ic|gpg --card-status}}
Line 186: Line 432:
 
  gpg: selecting openpgp failed: ec=6.108
 
  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.
+
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 {{Ic|reader-port}} from {{ic|~/.gnupg/scdaemon.conf}}, specify the location to {{ic|libpcsclite.so}} library and disable ccid so we make sure that we use pcscd:
In order to point scdaemon to use pcscd you should remove {{Ic|reader-port}} from {{ic|~/gnupg/scdaemon.conf}}, specify the location to libpcsclite.so library and disable ccid so we make sure that we use pcscd.
+
 
+
{{hc|~/.gnupg/scdaemon.conf|<nowiki>
{{hc|~/scdaemon.conf|<nowiki>
+
pcsc-driver /usr/lib/libpcsclite.so
pcsc-driver /usr/lib/libpcsclite.so  
+
 
card-timeout 5
 
card-timeout 5
 
disable-ccid
 
disable-ccid
Line 196: Line 441:
  
 
Please check {{Ic|man scdaemon}} if you do not use OpenSC.
 
Please check {{Ic|man scdaemon}} if you do not use OpenSC.
 +
 +
== Tips and tricks ==
 +
 +
=== Different algorithm ===
 +
 +
You may want to use stronger algorithms:
 +
 +
{{hc|~/.gnupg/gpg.conf|
 +
...
 +
 +
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
 +
}}
 +
 +
In the latest version of GnuPG, the default algorithms used are SHA256 and AES, both of which are secure enough for most people. However, if you are using a version of GnuPG older than 2.1, or if you want an even higher level of security, then you should follow the above step.
 +
 +
=== 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.
 +
 +
Then run:
 +
 +
$ gpg -e -a -r ''<user-id>'' ''your_password_file''
 +
 +
{{ic|-e}} is for encrypt, {{ic|-a}} for armor (ASCII output), {{ic|-r}} for recipient user ID.
 +
 +
You will be left with a new {{ic|''your_password_file''.asc}} file.
 +
 +
=== Revoking a key ===
 +
 +
{{Warning|
 +
*Anybody having access to your revocation certificate can revoke your key, rendering it useless.
 +
*Key revocation should only be performed if your key is compromised or lost, or you forget your passphrase.}}
 +
 +
Revocation certificates are automatically generated for newly generated keys, although one can be generated manually by the user later. These are located at {{ic|~/.gnupg/openpgp-revocs.d/}}. The filename of the certificate is the fingerprint of the key it will revoke.
 +
 +
To revoke your key, simply import the revocation certificate:
 +
 +
$ gpg --import ''<fingerprint>''.rev
 +
 +
Now update the keyserver:
 +
 +
$ gpg --keyserver subkeys.pgp.net --send ''<userid>''
 +
 +
=== Change trust model ===
 +
 +
By default GnuPG uses the [[Wikipedia::Web of Trust|Web of Trust]] as the trust model. You can change this to [[Wikipedia::Trust on First|Trust on First]] Use by adding {{ic|1=--trust-model=tofu}} when adding a key or adding this option to your GnuPG configuration file. More details are in [https://lists.gnupg.org/pipermail/gnupg-devel/2015-October/030341.html this email to the GnuPG list].
 +
 +
=== Hide all recipient id's ===
 +
 +
By default the recipient's key ID is in the encrypted message. This can be removed at encryption time for a recipient by using {{ic|hidden-recipient ''<user-id>''}}. To remove it for all recipients add {{ic|throw-keyids}} to your configuration file. This helps to hide the receivers of the message and is a limited countermeasure against traffic analysis. (Using a little social engineering anyone who is able to decrypt the message can check whether one of the other recipients is the one he suspects.)  On the receiving side, it may slow down the decryption process because all available secret keys must be tried (''e.g.'' with {{ic|--try-secret-key ''<user-id>''}}).
 +
 +
=== Using caff for keysigning parties ===
 +
 +
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 he [[Wikipedia::Web of Trust|Web of Trust]]. Keysigning parties allow users to get together in physical location to validate keys. The [[Wikipedia:Zimmermann–Sassaman key-signing protocol|Zimmermann-Sassaman]] key-signing protocol is a way of making these very effective. [http://www.cryptnet.net/fdp/crypto/keysigning_party/en/keysigning_party.html Here] you will find a how-to article.
 +
 +
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 package {{AUR|caff-svn}} or bundled together with other useful tools in the package {{AUR|signing-party-svn}}{{Broken package link|{{aur-mirror|signing-party-svn}}}}.
 +
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
 +
 +
To send the signatures to their owners you need a working [[Wikipedia:Message transfer agent|MTA]]. If you do not have already one, install [[msmtp]].
  
 
== Troubleshooting ==
 
== Troubleshooting ==
  
=== Su ===
+
=== 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:
 +
cat /proc/sys/kernel/random/entropy_avail
 +
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]].
 +
 
 +
=== su ===
 +
 
 +
When using {{Ic|pinentry}}, you must have the proper permissions of the terminal device (e.g. {{Ic|/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:
  
When using {{Ic|pinentry}}, you must have the proper permisions of the terminal device (e.g. {{Ic|/dev/tty1}}) in use. However, with {{Ic|su}} (or {{Ic|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
 
  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 {{Ic|/dev/pts/}}.
 
  
{{Note|being part of the group {{Ic|tty}} '''does not''' seem to alleviate the issue, at least as root. (Please confirm with non-superusers)}}
+
and then change it back after using gpg the first time. The equivalent is likely to be true with {{Ic|/dev/pts/}}.
 +
 
 +
{{Note|The owner of tty ''must'' match with the user for which pinentry is running. Being part of the group {{Ic|tty}} '''is not''' enough.}}
  
 
=== Agent complains end of file ===
 
=== 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.
+
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 the qt pinentry.
+
Alternatively, you can use {{ic|pinentry-qt}}. See [[#pinentry]].
  
# ln -sf /usr/bin/pinentry-qt4 /usr/bin/pinentry
+
=== KGpg configuration permissions ===
  
=== Configuration permissions ===
+
There have been issues with {{Pkg|kdeutils-kgpg}} being able to access the {{ic|~/.gnupg/}} options. One issue might be a result of a deprecated ''options'' file, see the [https://bugs.kde.org/show_bug.cgi?id=290221 bug] report.
  
GnuPG needs the correct permissions on the ~/.gnupg folder and its contents to function correctly (KGpg have shown to not work on a default setup).
+
Another user reported that ''KGpg'' failed to start until the {{ic|~/.gnupg}} folder is set to {{ic|drwxr-xr-x}} permissions. If you require this work-around, ensure that the directory contents retain {{ic|-rw-------}} permissions! Further, report it as a bug to the [https://bugs.kde.org/buglist.cgi?quicksearch=kgpg developers].
  
The ~/.gnupg folder needs drwxr-xr-x
+
=== Conflicts between gnome-keyring and gpg-agent ===
  
It's contents all need -rw------- except for its folders which all needs drwx------ (x on folders make its contentfiles readable).
+
{{Accuracy|See [[#GPG_AGENT_INFO]]}}
 +
 
 +
While the Gnome keyring implements a GPG agent component, as of GnuPG version 2.1, GnuPG ignores the {{ic|GPG_AGENT_INFO}} environment variable, so that Gnome keyring can no longer be used as a GPG agent.
 +
 
 +
However, since version 0.9.6 the package {{Pkg|pinentry}} provides the {{Ic|pinentry-gnome3}} program. You may set the following option in your {{Ic|gpg-agent.conf}} file
 +
  pinentry-program /usr/bin/pinentry-gnome3
 +
in order to make use of that pinentry program.
 +
 
 +
Since version 0.9.2 all pinentry programs can be configured to optionally save a passphrase with libsecret. For example, when the user is asked for a passphrase via {{Ic|pinentry-gnome3}}, a checkbox is shown whether to save the passphrase using a password manager. Unfortunately, the package {{Pkg|pinentry}} does not have this feature enabled (see {{Bug|46059}} for the reasons). You may use {{AUR|pinentry-libsecret}} as a replacement for it, which has support for libsecret enabled.
 +
 
 +
=== mutt and gpg ===
 +
 
 +
To be asked for your GnuPG password only once per session as of GnuPG 2.1, see [https://bbs.archlinux.org/viewtopic.php?pid=1490821#p1490821 this forum thread].
 +
 
 +
=== "Lost" keys, upgrading to gnupg version 2.1 ===
 +
 
 +
When {{ic|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 [http://jo-ke.name/wp/?p=111 GnuPG invalid packet workaround]. Basically, it says that there is a bug with keys in the old {{ic|pubring.gpg}} and {{ic|secring.gpg}} files, which have now been superseded by the new {{ic|pubring.kbx}} file and the {{ic|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.
 +
 
 +
=== Smartcard not detected ===
 +
 
 +
Your user might not have the permission to access the smartcard which results in a {{ic|card error}} to be thrown, even though the card is correctly set up and inserted.
 +
 
 +
One possible solution is to add a new group {{ic|scard}} including the users who need access to the smartcard.
 +
 
 +
Then use an [[Udev#Writing_udev_rules|udev]] rule, similar to the following:
 +
{{hc|/etc/udev/rules.d/71-gnupg-ccid.rules|<nowiki>
 +
ACTION=="add", SUBSYSTEM=="usb", ENV{ID_VENDOR_ID}=="1050", ENV{ID_MODEL_ID}=="0116|0111", MODE="660", GROUP="scard"
 +
</nowiki>}}
 +
One needs to adapt VENDOR and MODEL according to the {{ic|lsusb}} output, the above example is for a YubikeyNEO.
  
 
== See also ==
 
== See also ==
  
 +
* [https://gnupg.org/ GNU Privacy Guard Homepage]
 +
* [https://fedoraproject.org/wiki/Creating_GPG_Keys Creating GPG Keys (Fedora)]
 +
* [https://wiki.debian.org/Subkeys OpenPGP subkeys in Debian]
 
* [http://blog.sanctum.geek.nz/series/linux-crypto/ A more comprehensive gpg Tutorial]
 
* [http://blog.sanctum.geek.nz/series/linux-crypto/ A more comprehensive gpg Tutorial]
 +
* [https://help.riseup.net/en/security/message-security/openpgp/gpg-best-practices gpg.conf recommendations and best practices]
 +
* [https://github.com/ioerror/torbirdy/blob/master/gpg.conf Torbirdy gpg.conf]
 +
* [https://www.reddit.com/r/GPGpractice/ /r/GPGpractice - a subreddit to practice using GnuPG.]

Latest revision as of 10:56, 17 May 2016

According to the official website:

GnuPG is a complete and free implementation of the OpenPGP standard as defined by RFC4880 (also known as PGP). 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. GnuPG, also known as GPG, is a command line tool with features for easy integration with other applications. A wealth of frontend applications and libraries are available. Version 2 of GnuPG also provides support for S/MIME and Secure Shell (ssh).

Installation

Install the gnupg package.

This will also install pinentry, a collection of simple PIN or passphrase entry dialogs which GnuPG uses for passphrase entry. Which pinentry dialog is used is determined by the symbolic link /usr/bin/pinentry, which by default points to /usr/bin/pinentry-gtk-2.

If you want to use a graphical frontend or program that integrates with GnuPG, see List of applications/Security#Encryption, signing, steganography.

Configuration

Directory location

$GNUPGHOME is used by GnuPG to point to the directory where its 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 installation.

To change the default location, either run gpg this way $ gpg --homedir path/to/file or set GNUPGHOME in one of your regular startup files.

Configuration files

The default configuration files are ~/.gnupg/gpg.conf and ~/.gnupg/dirmngr.conf.

By default, the gnupg directory has its permissions set to 700 and the files it contains have their permissions set to 600. Only the owner of the directory has permission to read, write, and access the files. This is for security purposes and should not be changed. In case this directory or any file inside it does not follow this security measure, you will get warnings about unsafe file and home directory permissions.

Append to these files any long options you want. Do not write the two dashes, but simply the name of the option and required arguments. You will find skeleton files in /usr/share/gnupg. These files are copied to ~/.gnupg the first time gpg is run if they do not exist there. Other examples are found in #See also.

Additionally, pacman uses a different set of configuration files for package signature verification. See Pacman/Package signing for details.

Default options for new users

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/user1/.gnupg and /home/user2/.gnupg and copy the files from the skeleton directory to it. Users with existing GnuPG home directory are simply skipped.

Usage

Note: Whenever a <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.

Create key pair

Generate a key pair by typing in a terminal:

$ gpg --full-gen-key
Tip: Use the --expert option for getting alternative ciphers like ECC.

The command will prompt for answers to several questions. For general use most people will want:

  • the RSA (sign only) and a RSA (encrypt only) key.
  • a keysize of the default value (2048). A larger keysize of 4096 "gives us almost nothing, while costing us quite a lot"[1].
  • an expiration date. A period of a year is good enough for the average user. This way even if access is lost to the keyring, it will allow others to know that it is no longer valid. Later, if necessary, the expiration date can be extended without having to re-issue a new key.
  • your name and email address. You can add multiple identities to the same key later (e.g., if you have multiple email addresses you want to associate with this key).
  • no optional comment. Since the semantics of the comment field are not well-defined, it has limited value for identification.
  • a secure passphrase.
Note: The name and email address you enter here will be seen by anybody who imports your key.

List keys

To list keys in your public key ring:

$ gpg --list-keys

To list keys in your secret key ring:

$ gpg --list-secret-keys

Export your public key

gpg's main usage is to ensure confidentiality of exchanged messages via public-key cryptography. With it each user distributes the public key of their keyring, which can be be used by others to encrypt messages to the user. The private key must always be kept private, otherwise confidentiality is broken. See w:Public-key cryptography for examples about the message exchange.

So, in order for others to send encrypted messages to you, they need your public key.

To generate an ASCII version of your public key (e.g. to distribute it by e-mail):

$ gpg --output public.key --armor --export <user-id> 

Alternatively, or in addition, you can #Use a keyserver to share your key.

Tip: Add --no-emit-version to avoid printing the version number, or add the corresponding setting to your configuration file.

Import a public key

In order to encrypt messages to others, as well as verify their signatures, you need their public key. To import a public key with file name public.key to your public key ring:

$ gpg --import public.key

Alternatively, #Use a keyserver to find a public key.

Use a keyserver

You can register your key with a public PGP key server, so that others can retrieve your key without having to contact you directly:

$ gpg --send-keys <key-id>

To find out details of a key on the keyserver, without importing it, do:

$ gpg --search-keys <key-id>

To import a key from a key server:

$ gpg --recv-keys <key-id>
Warning: Anyone can send keys to a keyserver, so you should not trust that the key you download actually belongs to the individual listed. You should verify the authenticity of the retrieved public key by comparing its fingerprint with one that the owner published on an independent source, such as their own blog or website, or contacting them by email, over the phone or in person. Using multiple authentication sources will increase the level of trust you can give to the downloaded key. See Wikipedia:Public key fingerprint for more information.
Tip:
  • Adding keyserver-options auto-key-retrieve to gpg.conf will automatically fetch keys from the key server as needed.
  • An alternative key server is pool.sks-keyservers.net and can be specified with keyserver in dirmngr.conf.; see also wikipedia:Key server (cryptographic)#Keyserver examples.
  • You can connect to the keyserver over Tor using --use-tor. hkp://jijrk5u4osbsr34t5.onion is the onion address for the sks-keyservers pool. See this GnuPG blog post for more information.
  • You can connect to a keyserver using a proxy by setting the http_proxy environment variable and setting honor-http-proxy in dirmngr.conf. Alternatively, set http-proxy host[:port] in dirmngr.conf, overriding the http_proxy environment variable.

Encrypt and decrypt

You need to #Import a public key of a user before encrypting (options --encrypt or -e) a file or message to that recipient (options --recipient or -r).

To encrypt a file with the name doc, use:

$ gpg --recipient <user-id> --encrypt doc

To decrypt (option --decrypt or -d) a file with the name doc.gpg encrypted with your public key, use:

$ gpg --output doc --decrypt doc.gpg

gpg will prompt you for your passphrase and then decrypt and write the data from doc.gpg to doc. If you omit the -o (--output) option, gpg will write the decrypted data to stdout.

Tip:
  • Add --armor to encrypt a file using ASCII armor (suitable for copying and pasting a message in text format)
  • Use -R <user-id> or --hidden-recipient <user-id> instead of -r to not put the recipient key IDs in the encrypted message. This helps to hide the receivers of the message and is a limited countermeasure against traffic analysis.
  • Add --no-emit-version to avoid printing the version number, or add the corresponding setting to your configuration file.
  • You can use gnupg to encrypt your sensitive documents by using your own user-id as recipient, but only individual files at a time, though you can always tarball various files and then encrypt the tarball. See also Disk encryption#Available methods if you want to encrypt directories or a whole file-system.

Key maintenance

Backup your private key

To backup your private key do the following:

$ gpg --export-secret-keys --armor <user-id> > privkey.asc

Note that gpg release 2.1 changed default behaviour so that the above command enforces a passphrase protection, even if you deliberately chose not to use one on key creation. This is because otherwise anyone who gains access to the above exported file would be able to encrypt and sign documents as if they were you without needing to know your passphrase.

Warning: The passphrase is usually the weakest link in protecting your secret key. Place the private key in a safe place on a different system/device, such as a locked container or encrypted drive. It is the only safety you have to regain control to your keyring in case of, for example, a drive failure, theft or worse.

To import the backup of your private key:

$ gpg --allow-secret-key-import --import privkey.asc

Edit 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.

Some useful commands in the edit key sub menu:

> 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

Type help in the edit key sub menu for more commands.

Tip: If you have multiple email accounts you can add each one of them as an identity, using adduid command. You can then set your favourite one as primary.

Exporting subkey

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
Warning: If you forget to add the !, all of your subkeys will be exported.

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
Note: You will get a warning that the master key was not available and the password was not changed, but that can safely be ignored as the subkey password was.

At this point, you can now use /tmp/subkey.altpass.gpg on your other devices.

Rotating subkeys

Warning: Never delete your expired or revoked subkeys unless you have a good reason. Doing so will cause you to lose the ability to decrypt files encrypted with the old subkey. Please only delete expired or revoked keys from other users to clean your keyring.

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.

Note: You do not need to create a new key simply because it is expired. You can extend the expiration date.

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

> save

Update it to a keyserver.

$ gpg --keyserver pgp.mit.edu --send-keys <user-id>
Note: Revoking expired subkeys is unnecessary and arguably bad form. If you are constantly revoking keys, it may cause others to lack confidence in you.

Signatures

Signatures certify and timestamp documents. If the document is modified, verification of the signature will fail. Unlike encryption which uses public keys to encrypt a document, signatures are created with the user's private key. The recipient of a signed document then verifies the signature using the sender's public key.

Sign a file

To sign a file use the --sign or -s flag:

 $ gpg --output doc.sig --sign doc

The above also encrypts the file and stores it in binary format.

Clearsign a file or message

To sign a file without compressing it into binary format use:

 $ gpg --clearsign doc

This wraps the document into an ASCII-armored signature, but does not modify the document.

Make a detached signature

To create a separate signature file to be distributed separately from the document or file itself, use the --detach-sig flag:

 $ gpg --output doc.sig --detach-sig doc

This method is often used in distributing software projects to allow users to verify that the program has not been modified by a third part.

Verify a signature

To verify a signature use the --verify flag:

 $ gpg --verify doc.sig

where doc.sig is the signature you wish to verify.

To verify and decrypt a file at the same time, use the --decrypt flag as you normally would in decrypting a file.

If you are verifying a detached signature, both the file and the signature must be present when verifying. For example, to verify Arch Linux's latest iso you would do:

 $ gpg --verify archlinux-<version>-dual.iso.sig

where archlinux-<version>-dual.iso must be located in the same directory.

gpg-agent

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.

Starting with GnuPG 2.1.0 the use of gpg-agent is required. gpg-agent is started on-demand by the GnuPG tools, so there is usually no reason to start it manually.

Configuration

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:

~/.gnupg/gpg-agent.conf
default-cache-ttl 3600
Tip: To cache your passphrase for the whole session, please run the following command:
$ /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 using gpg-connect-agent:

$ gpg-connect-agent reloadagent /bye

The command should print OK.

pinentry

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:

~/.gnupg/gpg-agent.conf

# PIN entry program
# pinentry-program /usr/bin/pinentry-curses
# pinentry-program /usr/bin/pinentry-qt
# pinentry-program /usr/bin/pinentry-kwallet

pinentry-program /usr/bin/pinentry-gtk-2
Tip: For using /usr/bin/pinentry-kwallet you have to install the kwalletcli 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:

~/.config/systemd/user/gpg-agent.service
[Unit]
Description=GnuPG private key agent
IgnoreOnIsolate=true

[Service]
Type=forking
ExecStart=/usr/bin/gpg-agent --daemon
Restart=on-abort

[Install]
WantedBy=default.target
Note: If you use non-default value for the #GNUPGHOME environment variable, you need to pass it to the service. See systemd/User#Environment variables for details.

Unattended passphrase

Starting with GnuPG 2.1.0 the use of gpg-agent and pinentry is required, which 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:

~/.gnupg/gpg-agent.conf
allow-loopback-pinentry

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:

~/.gnupg/gpg.conf
pinentry-mode loopback
Note: The upstream author indicates setting pinentry-mode loopback in gpg.conf may break other usage, using the commandline option should be preferred if at all possible. [2]

SSH agent

gpg-agent has OpenSSH agent emulation. If you already use the GnuPG suite, you might consider using its agent to also cache your SSH keys. Additionally, some users may prefer the PIN entry dialog GnuPG agent provides as part of its passphrase management.

To start using GnuPG agent for your SSH keys, enable SSH support in the ~/.gnupg/gpg-agent.conf file:

~/.gnupg/gpg-agent.conf
enable-ssh-support

Next, make sure that gpg-agent is always started. Use either the systemd user service or add the following to your .bashrc file:

~/.bashrc
# Start the gpg-agent if not already running
if ! pgrep -x -u "${USER}" gpg-agent >/dev/null 2>&1; then
  gpg-connect-agent /bye >/dev/null 2>&1
fi

Then set SSH_AUTH_SOCK so that SSH will use gpg-agent instead of ssh-agent:

~/.bashrc
# Set SSH to use gpg-agent
unset SSH_AGENT_PID
if [ "${gnupg_SSH_AUTH_SOCK_by:-0}" -ne $$ ]; then
  export SSH_AUTH_SOCK="${HOME}/.gnupg/S.gpg-agent.ssh"
fi

Also set the GPG TTY and refresh the TTY in case user has switched into an X session. Example:

Tango-view-fullscreen.pngThis article or section needs expansion.Tango-view-fullscreen.png

Reason: Not clear why this is necessary (even tha man page does not explain it). (Discuss in Talk:GnuPG#)
~/.bashrc
# Set GPG TTY
export GPG_TTY=$(tty)

# Refresh gpg-agent tty in case user switches into an X session
gpg-connect-agent updatestartuptty /bye >/dev/null

Once gpg-agent is running you can use ssh-add to approve keys, following the same steps as for ssh-agent. The list of approved keys is stored in the ~/.gnupg/sshcontrol file. Once your key is approved, you will get a pinentry dialog every time your passphrase is needed. You can control passphrase caching in the ~/.gnupg/gpg-agent.conf file. The following example would have gpg-agent cache your keys for 3 hours:

~/.gnupg/gpg-agent.conf
default-cache-ttl-ssh 10800

Smartcards

GnuPG uses scdaemon as an interface to your smartcard reader, please refer to the man page for details.

GnuPG only setups

Note: To allow scdaemon direct access to USB smarcard readers the optional dependency libusb-compat have to be installed

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 with PSCD-Lite

Note: pcsclite and ccid have to be installed, and the contained systemd service pcscd.service has to be running, or the socket pscd.socket has to be listening.

PSCD-Lite is a daemon which handles access to smartcard (SCard API). If GnuPG's scdaemon fails to connect the smartcard directly (e.g. by using its integrated CCID support), it will fallback and try to find a smartcard using the PSCD-Lite driver.

Always use PSCD-Light

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 --card-status

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 reader-port from ~/.gnupg/scdaemon.conf, specify the location to libpcsclite.so library and disable ccid so we make sure that we use pcscd:

~/.gnupg/scdaemon.conf
pcsc-driver /usr/lib/libpcsclite.so
card-timeout 5
disable-ccid

Please check man scdaemon if you do not use OpenSC.

Tips and tricks

Different algorithm

You may want to use stronger algorithms:

~/.gnupg/gpg.conf
...

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

In the latest version of GnuPG, the default algorithms used are SHA256 and AES, both of which are secure enough for most people. However, if you are using a version of GnuPG older than 2.1, or if you want an even higher level of security, then you should follow the above step.

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.

Then run:

$ 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 your_password_file.asc file.

Revoking a key

Warning:
  • Anybody having access to your revocation certificate can revoke your key, rendering it useless.
  • Key revocation should only be performed if your key is compromised or lost, or you forget your passphrase.

Revocation certificates are automatically generated for newly generated keys, although one can be generated manually by the user later. These are located at ~/.gnupg/openpgp-revocs.d/. The filename of the certificate is the fingerprint of the key it will revoke.

To revoke your key, simply import the revocation certificate:

$ gpg --import <fingerprint>.rev

Now update the keyserver:

$ gpg --keyserver subkeys.pgp.net --send <userid>

Change trust model

By default GnuPG uses the Web of Trust as the trust model. You can change this to Trust on First Use by adding --trust-model=tofu when adding a key or adding this option to your GnuPG configuration file. More details are in this email to the GnuPG list.

Hide all recipient id's

By default the recipient's key ID is in the encrypted message. This can be removed at encryption time for a recipient by using hidden-recipient <user-id>. To remove it for all recipients add throw-keyids to your configuration file. This helps to hide the receivers of the message and is a limited countermeasure against traffic analysis. (Using a little social engineering anyone who is able to decrypt the message can check whether one of the other recipients is the one he suspects.) On the receiving side, it may slow down the decryption process because all available secret keys must be tried (e.g. with --try-secret-key <user-id>).

Using caff for keysigning parties

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 he Web of Trust. Keysigning parties allow users to get together in physical location to validate keys. The Zimmermann-Sassaman key-signing protocol is a way of making these very effective. Here you will find a how-to article.

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 package caff-svnAUR or bundled together with other useful tools in the package signing-party-svnAUR[broken link: archived in aur-mirror]. 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

To send the signatures to their owners you need a working MTA. If you do not have already one, install msmtp.

Troubleshooting

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:

cat /proc/sys/kernel/random/entropy_avail

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.

su

When using 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 /dev/pts/.

Note: The owner of tty must match with the user for which pinentry is running. Being part of the group tty is 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 #pinentry.

KGpg configuration permissions

There have been issues with kdeutils-kgpg being able to access the ~/.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

Tango-inaccurate.pngThe factual accuracy of this article or section is disputed.Tango-inaccurate.png

Reason: See #GPG_AGENT_INFO (Discuss in Talk:GnuPG#)

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.

However, since version 0.9.6 the package pinentry provides the pinentry-gnome3 program. You may set the following option in your gpg-agent.conf file

 pinentry-program /usr/bin/pinentry-gnome3

in order to make use of that pinentry program.

Since version 0.9.2 all pinentry programs can be configured to optionally save a passphrase with libsecret. For example, when the user is asked for a passphrase via pinentry-gnome3, a checkbox is shown whether to save the passphrase using a password manager. Unfortunately, the package pinentry does not have this feature enabled (see FS#46059 for the reasons). You may use pinentry-libsecretAUR as a replacement for it, which has support for libsecret enabled.

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

When 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 pubring.gpg and 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.

Smartcard not detected

Your user might not have the permission to access the smartcard which results in a card error to be thrown, even though the card is correctly set up and inserted.

One possible solution is to add a new group scard including the users who need access to the smartcard.

Then use an udev rule, similar to the following:

/etc/udev/rules.d/71-gnupg-ccid.rules
ACTION=="add", SUBSYSTEM=="usb", ENV{ID_VENDOR_ID}=="1050", ENV{ID_MODEL_ID}=="0116|0111", MODE="660", GROUP="scard"

One needs to adapt VENDOR and MODEL according to the lsusb output, the above example is for a YubikeyNEO.

See also