Secret GPG key

Back up a GPG secret key

I have reinstalled system recently and did not think I would need to backup my keys, so they will be available when needed. We all learn on our mistakes, so here is an easy way to export and import your GPG secret keys. The --armor option will export the key in ASCII format, otherwise the key will be exported in binary format.

First, check the name used to generate the key by running the command below. The line starting with uid will show the name:

gpg --list-secret-keys

Next, to export your private key, run the command below and replace Your Name with name used to create the key and path/to/ to wherever you want save the file.

gpg --export-secret-keys --armor Your Name > /path/to/secret-key-backup.asc

You can also export the GPG trust database. Simply run:

gpg --export-ownertrust > /path/to/trustdb-backup.txt

Import a GPG secret key

To import your GPG key, run the following command:

gpg —-import /path/to/secret-key-backup.asc

To import the GPG trust database, first remove the existing one:

rm ~/.gnupg/trustdb.gpg
and import your backup:
gpg --import-ownertrust < /path/to/trustdb-backup.txt

If you do not have database backed up, you can restore trust level with the command below. Replace Your Name and when promped, chose your ultimate or another trust level:

gpg --edit-key Your Name
gpg> trust
gpg> save