Table of Contents

Introduction

If you are into Linux or the Security field you most likely have heard the terms: PGP, GPG, GnuPG, OpenPGP. They sometimes are being used interchangeably to describe e.g. how to encrypt mails or how to verify signatures of installed programs and packages. It might be difficult for new users to understand the differences, and how the PGP encryption works, but it is simple if explained.

  • PGP: Pretty Good Privacy (PGP) is is an encryption program that provides cryptographic privacy and authentication for data communication. It was first developed by Phil Zimmermann in 1991.
  • OpenPGP: Is the non-proprietary encryption standard of PGP encryption software (RFC 4880) for encrypting and decrypting data.
  • GnuPG: The Gnu Privacy Guard (GnuPG) is a complete and free implementation of the OpenPGP standard.
  • GPG: Is usually referring to the GnuPG program or the keys created by it as GPG keys instead of PGP keys.
  • gpg: Is the GnuPG command line tool that can be found or installed on Linux systems, to encrypt/decrypt, sign and manage the keys.

GPG is used to prove your online identity, as it is linked to your real name and email address, and also to encrypt and decrypt mails or files for yourself or for other people. This is invaluable if you want to have private communications or save sensitive files and documents in a safe way.

GPG is being used for over 20 years to provide End-To-End encryption and it is still uncrackable even for modern supercomputers. But, There are a lot of arguments against its usage, primarily for easier means of secure communication, because it requires some technical skills to use it and for a novice user it could be easy to ruin its security (e.g. by sending his/her Private Key instead of the Public Key). We won’t discuss these arguments further, as this is a guide on how to use GPG, but you can find here more reasons to not use it.

In this post we will see, how we can generate a GPG key pair with the gpg utility, how to use it to encrypt and decrypt messages to communicate securely with other people, how to import other people’s Public Keys, how to verify signatures, how to renew or revoke a key and how to back up the keys.

Install GnuPG

First we need to install the GnuPG utility. Fore Debian/Ubuntu systems run:

$ sudo apt install gnupg

Generating GPG Keys

To generate a new GPG key pair, run:

$ gpg --full-gen-key

Options:

  • 1. Kind of key: RSA (default)
  • 2. RSA Size: 3072 (default) or 4096 (for better security)
  • 3. Key is valid for: 0 - until infinity (default)
    • A period of one 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. At a later stage, if necessary, the expiration date can be extended without having to re-issue a new key.
  • 4. Real Name: Your real name
  • 5. Email address: Your email address
  • 6. Comment: Optional Value - Add nothing
  • 7. Verify Info: (O) - Okay
  • 8. Enter Passphrase: Enter a secure passphrase for the GPG key
    • This passphrase is critical, because if your computer gets compromised it is the only security measure that protects your Private Key.

Share GPG Public Key

Create ASCII Armored version of GPG Public Key

In order to upload the Public Key to your website, or any other place you want to share your key, you need to create an ASCII armored version of your Public Key (instead of the default binary version) to be easily viewed and shared.

To create an ASCII armored version of your Public Key:

$ gpg --output publickey.asc --export --armor XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX

Where XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX is your key-ID.

You can also, specify the Public Key you want to export using the email:

$ gpg --output publickey.asc --export --armor your.email@example.com

Where your.email@example.com is the email that is associated with the Public Key.

The publickey.asc file should be created after this operation.

Upload GPG Public Key & Fingerprint

Now you just need to upload the publickey.asc file to your website for others to use your Public Key to talk securely to you.

Another important detail, is to also upload the fingerprint of your Public Key, in order for anyone who downloads the key, to be able to verify that the fingerprint of the downloaded key matches the one you have supplied.

Upload GPG Public Key to Keyserver

You can upload your Public Key to a Keyserver, like pgp.mit.edu and then it will likely be distributed to other Keyservers around the world.

Note, that you can not delete a key from the Keyservers. You can only upload a revocation certificate that it will tell people who download it that the key has been revoked.

Upload to a Keyserver:

$ gpg --send-keys --keyserver pgp.mit.edu key-ID

Check ASCII Armored GPG Public Key Fingerprint

To check the fingerprint of a Public Key, run:

$ gpg --with-fingerprint publickey.asc

We can also use the --show-keys option to check the fingerprint of a Public Key:

$ gpg --show-keys publickey.asc

In some versions of gpg some command won’t work. In order to view the fingerprint we will have to first import the key and then show it. We can use the --dry-run option in order to avoid importing every key we want to verify:

$ gpg --dry-run --import --import-options import-show publickey.asc

pub   rsa3072 2021-07-09 [SC]
      XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
uid           Your Name <your.email@example.com>
sub   rsa3072 2021-07-09 [E]

gpg: Total number processed: 1

Where XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX is the key-ID. (The fingerprint is the same but with spaces after 4 characters, like: XXXX XXXX XXXX XXXX XXXX XXXX XXXX XXXX XXXX XXXX)

Import GPG Public Keys

Import GPG Public Key from file

Import someones Public Key directly from a file:

$ gpg --import "name_of_pub_key_file"

Import someones Public Key directly from a link:

$ curl https://example.com/name_of_pub_key_file.asc | gpg --import

Import GPG Public Key from Keyserver

Import someones Public Key from a Keyserver, like:

$ gpg --keyserver pgp.mit.edu --recv-keys DAD95197

Search on Keyserver

Search a Public Key on a Keyserver, using parameters:

$ gpg --keyserver pgp.mit.edu --search-keys "search_parameters"

Verify & Trust & Sign GPG Keys

Verify GPG Keys

You can verify the Public Key of a person by checking the fingerprint of the given Public Key with the fingerprint they advertise (on their Website / GitHub / Keyserver etc).

Get the fingerprint of an imported Public Key:

$ gpg --fingerprint your_email@address.com

pub   rsa3072 2021-07-09 [SC]
      XXXX XXXX XXXX XXXX XXXX XXXX XXXX XXXX XXXX XXXX
uid           Your Name <your.email@example.com>
sub   rsa3072 2021-07-09 [E]

and check that fingerprint with the one the other person provides.

Trust GPG Keys

You can verify the Public Key of a person by checking the fingerprint, and even sign the key to verify you know the owner of the key. But if you want to have a personal information about the level of trust you have to a Public Key you can edit the key’s trust.

This information is private and it is not packaged with the key when it is exported. It is even stored separately from your keyrings in a separate database.

To set the trust of a key, you have to edit it:

gpg --edit-key key-id

Now on the new prompt, type the trust command (usually 4 = Full trust):

Please decide how far you trust this user to correctly verify other users' keys
(by looking at passports, checking fingerprints from different sources, etc.)

  1 = I don't know or won't say
  2 = I do NOT trust
  3 = I trust marginally
  4 = I trust fully
  5 = I trust ultimately
  m = back to the main menu

Choose the correct level of trust for the selected key and verify your choice:

Your decision? 4
Do you really want to set this key to ultimate trust? (y/N) y
gpg> quit

Sign GPG Keys

If you trust a persons Public Key, you can sign it, meaning that you trust this key and that you verify it belongs to the person that it is associated with.

To sign an imported key, run:

$ gpg --sign-key key-ID

Where key-ID is the key you want to sign (you can also enter the email address associated with the key).

Check the sign, with:

$ gpg --list-sig key-ID

pub   rsa3072 2021-07-09 [SC]
      XXXX XXXX XXXX XXXX XXXX XXXX XXXX XXXX XXXX XXXX
uid           [ultimate] Your Name <your.email@example.com>
sig 3         XXXXXXXXXXXXXXXX 2021-07-09  Your Name <your.email@example.com>
sig           YYYYYYYYYYYYYYYY 2021-07-19  Other Person <other.persons.email@example.com>
sub   rsa3072 2021-07-09 [E]
sig           XXXXXXXXXXXXXXXX 2021-07-09  Your Name <your.email@example.com>

After you signed it, you can send back the person the signed key, in order for him/her to display the trust relationship:

$ gpg --output signed.asc --export --armor key-ID

After you enter your passphrase, the signed Public Key will be displayed. Send the other person this, so they can they can demonstrate to other people that you trust them.

The other person can import the signed key, with:

$ gpg --import signed.asc

This will add the signing information into their GPG database.

Encrypt & Decrypt Files with GPG

With recipient’s Public Key (asymmetric cipher)

Encrypt Files

We can encrypt files and messages, with the --encrypt option, using the recipient’s Public Key. This is used if we want to send the file/message to another person or even to our selves.

We can also sign the file/message to verify that it is coming from us.

We can also add the -r flag, to add ourselves as a second recipient in order to encrypt the file/message with our Public Key and be able to decrypt after the encryption with our own Private Key.

Encrypt the file/message:

$ gpg --encrypt --sign --armor -r other.persons.email@example.com -r your.email@example.com name_of_file

To encrypt a file only for yourself, run:

$ gpg --encrypt --sign --armor -r your.email@example.com name_of_file

Decrypt Files

To decrypt a file/message that has been encrypted with our Public Key, we can use the --decrypt (or -d) option and specify the file we want to decrypt. For simplicity, we don’t even have to specify the --decrypt flag and simply pass the encrypted file/message to gpg.

Decrypt the file/message:

$ gpg -d name_of_file

Decrypt the file/message, and save it to a file:

$ gpg --output saved_file -d name_of_file

With a New Passphrase (symmetric cipher)

Encrypt Files

We can encrypt files and messages, with the --symmetric (or -c) option, that does not require the use of a key pair. We use this method if we want to simply encrypt a file/message with a passphrase.

Encrypt the file/message:

$ gpg -c --armor name_of_file

and enter a passphrase.

Now we will have an ASCII armored version of the encrypted file with the name:

  • name_of_file.asc

Decrypt Files

To decrypt a symmetric encrypted file/message, we use the --decrypt (or -d) option, and we just need to enter the passphrase we have given when encrypting the file.

Decrypt the file/message:

$ gpg -d name_of_file.asc

This will decrypt the file/message and print it to stdout.

If we want to save the decrypted file/message:

$ gpg --output name_of_file -d name_of_file.asc

Encrypt & Decrypt Emails with GPG

We can use our GPG keys to send and receive encrypted emails. There are a lot of ways for how it can be done:

  1. Manually copying the encrypted emails and decrypting them with the gpg utility.
  2. Using the PGP utilities that the email client provides, either a webmail client or an installed client:
  3. Using an extension or plugin for your Webmail client:

The first (1) method is the most simple one and we have already seen how we can encrypt and decrypt messages, but is also the most cumbersome and requires access to a terminal.

The second (2) method is not universal and only applies if your Web mail provider or the Email client you use has PGP encryption options. It can be the most safe option, especially for the offline Email client as there is no exposure of the Private Key to the internet, which is the case with Protonmail or other Web mail clients (although the key is of course stored encrypted with your password in their servers).

The third (3) method is the most user friendly and there are a lot of free extensions to choose from either for Web mail clients like Gmail and Yahoo, or for other Web mail clients.

Use OpenPGP with Thunderbird

The Thunderbird Email Client supports OpenPGP directly since version 78. We will see how we can use our GPG keys to send and receive encrypted emails in Thunderbird. We suppose you already have an email account connected to the Thunderbird client.

Import a Private Key to Thunderbird

  1. Open Thunderbird and under the Tools tab, select OpenPGP Key Manager.
  2. Under File, select your Import Secret Key(s) From File.
  3. Select the file where you have saved your Private Key.
  4. Unlock with your Passphrase.
  5. After receiving a OpenPGP keys successfully imported window, make sure to check the option Treat this key as a Personal Key.
  6. Go to the Account Settings tab, and under End-To-End Encryption select your previously imported Private Key.
  7. You can also select the option Add my digital signature by default if you want to verify that the messages are sent by you.

Send your Public Key with Thunderbird

We can now send to another person our Public Key, so he can send us encrypted emails using our Public Key that we can decrypt with our Private Key.

If you don’t have another GPG key pair or another person to test, you can follow Step 4.A from the FSF Foundation’s instructions.

To send our Public Key, we send a non-encrypted mail with the key attached. We can do this easily from Thunderbird:

  1. Under the Tools tab, select OpenPGP Key Manager.
  2. Right click on your key, and select Send Public Keys by Email.
  3. This will create a new draft message, as if you had just hit the Write button, but in the attachment you will find your Public Keyfile.
  4. Select the recipient, add a subject and send the email.

Now you will be able to read encrypted emails that other sent to you.

Import a Public Key to Thunderbird

Now that you have imported your Private Key, we need to import the other person’s Public Key in order to send him/her an encrypted email using his/her Public Key that he can decrypt with his/her Private Key.

There are many ways to import a Public Key:

  • From the attachment of an email.
  • From a Keyserver.
  • From a Keyfile.

To import a Public Key (file) to Thunderbird:

  1. Under the Tools tab, select OpenPGP Key Manager.
  2. Under File, select your Import Public Key(s) From File.
  3. Select the file where you have saved the Public Key.
  4. After receiveing a OpenPGP keys successfully imported window, make sure to check that you trust the key, after you check the fingerprint.

Now you will be able to send encrypted emails to others.

Send an Encrypted email with Thunderbird.

If we now have another person’s Public Key and he/she has our Public Key, we start communicating securely.

To write an encrypted mail:

  1. Select the Write option to write a mail.
  2. Select the recipient, add a subject and write something to the email.
  3. In the Security tab, select the Require Encryption option, and it will also automatically select to digitally sign the message and attach the Public Key.
  4. Send the message.

Now only you and the other person will be able to view the messages.

Verify PGP Signatures

We can use GPG/PGP to verify signatures, either for downloaded files and documents or for programs. For this example, we will verify the OpenOffice download with the provided PGP/ASC signature on their website.

  1. Download the Public Key of OpenOffice:
$ wget https://downloads.apache.org/openoffice/KEYS
  1. Check the Public Key’s fingerprint to ensure that it is the correct key:
$ gpg --fingerprint KEYS

pub   rsa4096 2012-02-13 [SC]
      D09FB15F1A24768DDF1FA29CCFEEF31651B5FDE8
uid                      Juergen Schmidt <jsc@apache.org>
# ...
  1. Import the Public Keys to your keyring:
$ gpg --import KEYS
  1. Download the software you want to verify, for our case we will download only the Language pack for our Debian system in order to minimize download times:
$ wget https://sourceforge.net/projects/openofficeorg.mirror/files/4.1.10/binaries/en-US/Apache_OpenOffice_4.1.10_Linux_x86-64_langpack-deb_en-US.tar.gz/download

$ tar -xvzf download

en-US/
en-US/DEBS/
en-US/DEBS/openoffice-en-us-base_4.1.10-2_amd64.deb
en-US/DEBS/openoffice-en-us-writer_4.1.10-2_amd64.deb
en-US/DEBS/openoffice-en-us-help_4.1.10-2_amd64.deb
en-US/DEBS/openoffice-en-us_4.1.10-2_amd64.deb
en-US/DEBS/openoffice-en-us-draw_4.1.10-2_amd64.deb
en-US/DEBS/openoffice-en-us-calc_4.1.10-2_amd64.deb
en-US/DEBS/openoffice-brand-en-us_4.1.10-2_amd64.deb
en-US/DEBS/openoffice-en-us-impress_4.1.10-2_amd64.deb
en-US/DEBS/openoffice-en-us-math_4.1.10-2_amd64.deb
en-US/DEBS/openoffice-en-us-res_4.1.10-2_amd64.deb
  1. Download the PGP signature file of the software you want to verify, for our case we will download the OpenOffice language pack signature:
$ wget https://downloads.apache.org/openoffice/4.1.10/binaries/en-US/Apache_OpenOffice_4.1.10_Linux_x86-64_langpack-deb_en-US.tar.gz.asc

See the signature:

$ cat Apache_OpenOffice_4.1.10_Linux_x86-64_langpack-deb_en-US.tar.gz.asc

-----BEGIN PGP SIGNATURE-----

iQIzBAABCgAdFiEEqT1i7MPI6hLbIg7JNOp25nkUhagFAmB+tdEACgkQNOp25nkU
hagy/hAAlRWtI8d4LumQ8DcuUL/r5Ytol8dpuwzWqwLGy9koXEKiEDMO7HoQbqDp
6eGM0UoFwV6snYtUlH2Bq4dUARJeb2oiTeOBgcmr/B2OJosJZYzkXPS4ISbso+Am
W/EmqQ1txOPjc0eBr7ciDqSTlh26W/V7oeBDJBviqaWlWkFvTnz0U4qWX6w2nCKJ
XW87D2q9DTDHY7YXEFSt6M3rj1gaFlXczxNU/btd7nh44yIIdht4T76zIOvUheWJ
17uwv7H5+yLMX1qL45xmpuJTKUeM+7RUIjOfSQOqUqUauacJMmydPBUxQMXpFmue
xQqo8F9XNMMsfIQB2RUc2qb+H76DSe75fd0kGCMh+5Y/hn/Ryb1jAl6IHwVVXX2c
eNsp0kApYnTy3nMSMoJmBvbrY+R3+nPr2l4/bFJb0JEG6i8VnQKiF07Zz6x6IEbb
yqWALiSFJJlRCBoxEJdHkODkgHtOLA6sWjnJMJ28BVy5kpgDjGVPJ7SIbUk758BS
YszfT33p6z65HorH39IxNLe561p+uJJL8xgA5LQWwKS3H4xUHXIukSTWHX3IM9tQ
cwtloNJpWZTE/cxhLwJjOa+Yz/t0AOe9tTjI2I81cUv0VC4Qf1HCc9EkRSTwzsyz
2PQytAcIyKu6q5vBcTK0Tc/tFSWRp3ovX3XcLGNZfTJsFH2CvGs=
=UlRG
-----END PGP SIGNATURE-----
  1. Use the Public Key to verify the PGP signature. If the signature is correct, then the software has not been modified.

In order to verify all the downloaded files, we have to either:

cd in the extracted directory and run:

$ cd en-US
$ gpg --verify ../Apache_OpenOffice_4.1.10_Linux_x86-64_langpack-deb_en-US.tar.gz.asc

gpg: assuming signed data in '../Apache_OpenOffice_4.1.10_Linux_x86-64_langpack-deb_en-US.tar.gz'
gpg: Signature made Τρι 20 Απρ 2021 02:06:57 μμ EEST
gpg:                using RSA key A93D62ECC3C8EA12DB220EC934EA76E6791485A8
gpg: Good signature from "Jim Jagielski (Release Signing Key) <jim@apache.org>" [unknown]
gpg:                 aka "Jim Jagielski <jim@jaguNET.com>" [unknown]
gpg:                 aka "Jim Jagielski <jim@jimjag.com>" [unknown]
gpg:                 aka "Jim Jagielski <jimjag@gmail.com>" [unknown]
gpg: WARNING: This key is not certified with a trusted signature!
gpg:          There is no indication that the signature belongs to the owner.
Primary key fingerprint: A93D 62EC C3C8 EA12 DB22  0EC9 34EA 76E6 7914 85A8

where the first argument of the --verify option is the signature file.

Or we can verify all downloaded files using the compressed download file:

$ gpg --verify Apache_OpenOffice_4.1.10_Linux_x86-64_langpack-deb_en-US.tar.gz.asc download

gpg: Signature made Τρι 20 Απρ 2021 02:06:57 μμ EEST
gpg:                using RSA key A93D62ECC3C8EA12DB220EC934EA76E6791485A8
gpg: Good signature from "Jim Jagielski (Release Signing Key) <jim@apache.org>" [unknown]
gpg:                 aka "Jim Jagielski <jim@jaguNET.com>" [unknown]
gpg:                 aka "Jim Jagielski <jim@jimjag.com>" [unknown]
gpg:                 aka "Jim Jagielski <jimjag@gmail.com>" [unknown]
gpg: WARNING: This key is not certified with a trusted signature!
gpg:          There is no indication that the signature belongs to the owner.
Primary key fingerprint: A93D 62EC C3C8 EA12 DB22  0EC9 34EA 76E6 7914 85A8

The first argument of the --verify option is the signature file and the remaining arguments are the files that contain the signed data.

If we see the Good signature from message then the software is legit.

Renew Expired GPG key pair

You can list the keys in order to see when they expires:

$ gpg --list-keys

pub   rsa3072 2021-07-09 [SC]
      XXXX XXXX XXXX XXXX XXXX XXXX XXXX XXXX XXXX XXXX
uid           Your Name <your.email@example.com>
sub   rsa3072 2021-07-09 [E] [expires: 2021-10-25]

It is advised to set an expiration date on your keys in order for them to become invalid after some time, if they become lost or forgotten.

If your GPG key pair gets expired, you can renew it with:

$ gpg --edit-key user-id

where user-id is the uid of the key you want to create a certificate for (usually the email address).

A prompt will be shown and you should enter the expire command:

> expire

Now you will be prompted to enter a new expiration date, as well as the passphrase for your secret key, which will be used to sign the new expiration date. You should enter the amount you want, usually 1y for one year:

gpg> expire

Changing expiration time for the primary key.
Please specify how long the key should be valid.
         0 = key does not expire
      <n>  = key expires in n days
      <n>w = key expires in n weeks
      <n>m = key expires in n months
      <n>y = key expires in n years
Key is valid for? (0) 1y
Is this correct? (y/N) y

Then you can update the expiration date for the subkeys you have (key 1, key 2, …):

> key 1
> expire

Changing expiration time for a subkey.
Please specify how long the key should be valid.
         0 = key does not expire
      <n>  = key expires in n days
      <n>w = key expires in n weeks
      <n>m = key expires in n months
      <n>y = key expires in n years
Key is valid for? (0) 1y
Is this correct? (y/N) y

Then you can quit and save the changes:

gpg> quit
gpg> Save changes? (y/N) y

Revoke GPG key pair

If your key ever becomes stolen, lost or compromised, you should use the Revocation Certificate in order to revoke the key and make it invalid.

First, find the key you want to revoke:

$ gpg --list-keys

pub   rsa3072 2021-07-09 [SC]
      XXXX XXXX XXXX XXXX XXXX XXXX XXXX XXXX XXXX XXXX
uid           Your Name <your.email@example.com>
sub   rsa3072 2021-07-09 [E]

Suppose the XXXX XXXX XXXX XXXX XXXX XXXX XXXX XXXX XXXX XXXX is the key-ID for the key you want to revoke.

We can revoke it with the following command:

$ gpg --output revoke.asc --gen-revoke key-ID

where revoke.asc is the Revocation Certificate, usually stored in ~/.gnupg/openpgp-revocs.d/.

After that, we need to import the Revocation Certificate in the keyring:

$ gpg --import revoke.asc

and now the key is successfully revoked.

Revoke GPG key pair on Keyserver

If we have upload our key in a Keyserver, we need to revoke it there also. Suppose the Keyserver is pgp.mit.edu.

We can first search our key in the Keyserver:

$ gpg --keyserver pgp.mit.edu --search-keys key-ID

We can revoke it, by uploading the revoked key we have in our keyring:

$ gpg --keyserver pgp.mit.edu --send-keys key-ID

Now, although the old key is not gonna be deleted from the Keyserver, the revoked key is also uploaded and sets the old key invalid.

Backup GPG

You can backup your GPG keys using mainly two methods:

  • Backing up the whole ~/.gnupg directory.
  • Backing up only the needed files:
    • The Public and Private Key (gpg --export-secret-keys)
    • The Revocation Certificate (~/.gnupg/openpgp-revocs.d/)
    • The Trust Database - Ownership (gpg --export-ownertrust)
    • The Public Keyring (gpg --export)

Backup GPG Directory

The first option is to backup the whole ~/.gnupg directory. The Private Keys are stored encrypted in this directory, so they are not easily visible by anyone.

Backup ~/.gnupg to a different directory or device:

$ cp ~/.gnupg /path/to/safe/directory

Then if you want to restore this directory, in a new computer for example, you will have to transfer it back at the ~/.gnupg location:

$ cp /path/to/safe/directory/.gnupg ~/

And to fix any ownership issues, change the ownership to your user on the new computer:

$ sudo chown -R $USER:$USER ~/.gnupg

Export GPG Private Key (ASCII Armored)

In order to save only the Private Key somewhere safe, either at an offline storage medium or even to print it, you can use --export-secret-keys option, and add the --armor option to, in order to create an ASCII version of the key that is not binary and readable:

$ gpg --export-secret-keys --armor --output privatekey.asc

It will ask for your passphrase to complete this operation. After that, the Private Key is saved in privatekey.asc.

You can now save it in another directory or device:

$ cp privatekey.asc /path/to/safe/directory

Note: Although the exported Private Key is encrypted with your passphrase, be very carefull with this file, as if it gets compromised and brute-forced, anyone can impersonate you and read all your encrypted files and emails.

Import GPG Private Key

To import the backed up Private Key:

$ gpg --import privatekey.asc

You must enter your passphrase to complete the import.

Delete Private Key (Shred)

If you want to delete the Private Key file you created, you can use the shred utility to delete the file permanently and make it harder to be recovered by overwriting it:

$ shred -zuv privatekey.asc

The shred options, do the following:

  • z: add a final overwrite with zeros to hide shredding
  • u: de-allocate and remove file after overwriting
  • v: show progress

Export GPG Revocation Certificate

The Revocation Certificate is automatically generated for each generated key. Their default location is under ~/.gnupg/openpgp-revocs.d/, where the filename of the certificate is the fingerprint of the key it will revoke.

You can also generate manually a Revocation Certificate for a key pair:

$ gpg --gen-revoke --armor --output revcert.asc user-id

where user-id is the uid of the key you want to create a certificate for (usually the email address).

You can now save it in another directory or device:

$ cp revcert.asc /path/to/safe/directory

or for the automatically generated ones:

$ cp ~/.gnupg/openpgp-revocs.d /path/to/safe/directory

The certificate is used to revoke a key if it ever gets lost or compromised. It is useful to backup it, because you can use it, if you no longer have access to your secret key, and therefore not be able to generate another certificate.

Note: It is important to keep the backup of the certificates in a safe place (an offline device), because if the revocation certificate is used, the action cannot be undone and your key is no longer valid. You must protect the certificate the same way you protect your secret key.

Export GPG Trust Database

The GPG Trust Database is used to keep the trust values for each of the Public Keys you have. If you want to keep the trust values, you have to backup the Trust Database. It is located at ~/.gnupg/trustdb.gpg, but as the manual says:

There is no need to backup this file; it is better to backup the ownertrust values (see option –export-ownertrust).

To export the Trust Database:

$ gpg --export-ownertrust > otrust.txt

You can now save it in another directory or device:

$ cp otrust.txt /path/to/safe/directory

Import GPG Trust Database

To import the Trust Database, we need to first delete the current one:

$ rm ~/.gnupg/trustdb.gpg

And then import it with:

$ gpg --import-ownertrust < otrust.txt

Export GPG Public Keyring

In order to save all the Public Keys we have imported to our system, we need to backup them. The Public Keys are saved at the ~/.gnupg/pubring.kbx and ~/.gnupg/pubring.gpg files. But we do need to backup the files directly, it is better to use the --export option.

To export the Public Keys:

$ gpg --export --armor > mypublickeys.asc

You can now save it in another directory or device:

$ cp mypublickeys.asc /path/to/safe/directory

Import GPG Public Keyring

To import the saved Public Keys, we can simply run:

$ gpg --import mypublickeys.asc

Backup GPG on Paper

Export GPG Private Key to Paperkey

Another emergency backup solution is to print the Private Key on physical paper and store it somewhere secure. Paper will last a long time and it will save you a lot of problems in case any digital backup is lost.

We can use the paperkey utility to print the keys, which we can install with:

$ sudo apt install paperkey

To create a backup of your GnuPG key, pipe the Private Key to paperkey:

$ gpg --export-secret-key key-id | paperkey --output paperkey.asc

With this method, we keep only the Private part of the key. In order to restore the GPG Private Key from the Paperkey backup we will also need the Public Key. This is easier to have available, if we have uploaded online, either to a Keyserver or a personal website.

The file we need to print is paperkey.asc.

Encode Paperkey to QR code

By default, paperkey will output the secret key as human readable text. While this format guarantees the ability to read and restore the printed information, it is not very convenient to type out all the hexadecimal characters.

However we can use the Paperkey format and encode it to other formats, such as a QR code.

We will use the qrencode utility to encode the Paperkey, which we can install with:

$ sudo apt install qrencode

Because of the extended file size of the Paperkey and the storage limitations of QR codes, we wan’t be able to encode the key into only one QR code image.

The solution to this is to split the Paperkey to multiple files and convert each file into a QR code PNG image. Then when we want to decode the images, each QR code will produce a string that we can concatenate.

We will use the split utility, to split the Paperkey, and then qrencode to convert each chunk from the file into a QR code image:

# Split paperkey to 2500 bytes chunks
$ split -C 2500 paperkey.asc paperkey_split-
# Convert each chunk to a QR code file
$ for i in paperkey_split-*; do qrencode -r ${i} -o "${i}_qr.png";done
# Overcomplicated oneliner to delete split chunks, because they are not needed anymore
$ find . -type f -not -name "paperkey_split-*.png" | grep "paperkey_split-" | cut -d/ -f 2 | xargs rm

Now the QR code images we want will have the format paperkey_split-*_qr.png.

We can use the montage utility to concatenate all the images into one for ease of printing, which we can install with:

$ sudo apt install montage

To concatenate all the images into one:

$ montage -mode Concatenate -tile 2x paperkey_split-*_qr.png paperkey_splits_qr.png

The QR code images we need to print are paperkey_split-*_qr.png or the complete paperkey_splits_qr.png.

Restore Paperkey from QR code

To restore the multiple QR code images back to the Paperkey format, we first need to scan all the QR codes, concatenate them into a single string and then parse the data back to paperkey.

We will use the zbar utilities to restore the Paperkey, which we can install with:

$ sudo apt install zbar-tools

First we need to scan the QR code printed images, either with the camera of our phone or with our scanner. It is better to do it with a scanner or a good quality camera to make sure we will recover the key.

After we have scanned the QR code images and given them the same paperkey_split-*_qr names we can use the zbarimg utility, to feed all images to it, delete the last new line and append the result to paperkey.asc:

# Convert each QR code image to Paperkey and append result
$ for i in paperkey_split-*; do zbarimg --raw -q $i | head -n -1; done > paperkey.asc

Now we have back the Paperkey that we can use to restore the GPG Private Key.

NOTE: We use the -q (or --quiet) option with zbarimg to print only the decoded symbol data, and other status text that will interfere with the raw data.

Import GPG Private Key from Paperkey

To restore the physical copy of our Private Key, we need the file with the paperkey data and the Public Key.

We can get the paperkey file, either:

  • By restoring by hand from the Paperkey printed copy
  • By restoring it from the QR code image

We can restore it and save it to a binary OpenPGP format file:

$ paperkey --pubring publickey.gpg --secrets paperkey.asc --output privatekey.gpg

and then import it:

$ gpg --import privatekey.asc

or, we can restore it and import it directly:

$ paperkey --pubring publickey.gpg --secrets paperkey.asc | gpg --import

Error: If you receive a “Error: unable to parse OpenPGP packets (is this armored data?)" while restoring your key, you need to dearmor your Public Key first and convert it to the binary OpenPGP format:

# Copy armored format
$ cp publickey.asc publickey
# Convert armored to binary OpenPGP format
$ gpg --dearmor publickey
# Now you have publickey.gpg to use with paperkey

GPG Files

The most important configuration files of GnuPG:

  • ~/.gnupg/pubring.gpg : The public keyring using a legacy format.
    • You should backup this file.
  • ~/.gnupg/pubring.kbx : The public keyring using a different format.
    • You should backup this file.
  • ~/.gnupg/trustdb.gpg: The trust database.
    • There is no need to backup this file; it is better to backup the ownertrust values
  • ~/.gnupg/random_seed: A file used to preserve the state of the internal random pool.
  • ~/.gnupg/openpgp-revocs.d: This is the directory where gpg stores pre-generated revocation certificates.
    • The file name corresponds to the OpenPGP fingerprint of the respective key.
    • It is suggested to backup those certificates and if the primary Private Key is not stored on the disk to move them to an external storage device.
    • Anyone who can access theses files is able to revoke the corresponding key.
    • You may want to print them out.
    • You should backup all files in this directory and take care to keep this backup closed away.

GPG Commands

List GPG Keys

List GPG keys:

$ gpg --list-keys

/home/$USER/.gnupg/pubring.kbx
-------------------------------
pub   rsa3072 2021-07-09 [SC]
      XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
uid           [ultimate] Your Name <your.email@example.com>
sub   rsa3072 2021-07-09 [E]

The XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX alphanumeric string is your key-ID.

Delete GPG Keys

Delete GPG key, both public and private.

First delete the Private Key:

$ gpg --delete-secret-keys key-ID

Then, you can delete the Public Key:

$ gpg --delete-keys key-ID

List GPG Fingerprints

List keys and fingerprints in your system:

$ gpg --fingerprint

/home/$USER/.gnupg/pubring.kbx
-------------------------------
pub   rsa3072 2021-07-09 [SC]
      XXXX XXXX XXXX XXXX XXXX XXXX XXXX XXXX XXXX XXXX
uid           [ultimate] Your Name <your.email@example.com>
sub   rsa3072 2021-07-09 [E]

The XXXX XXXX XXXX XXXX XXXX XXXX XXXX XXXX XXXX XXXX alphanumeric string is the fingerprint of the key.