Skip to content

Instantly share code, notes, and snippets.

@AndreaPasqualini
Last active April 23, 2020 19:49
Show Gist options
  • Save AndreaPasqualini/68b4207a22919c2119a56a34c36a9748 to your computer and use it in GitHub Desktop.
Save AndreaPasqualini/68b4207a22919c2119a56a34c36a9748 to your computer and use it in GitHub Desktop.
Steps to export and import a private GPG key.

Copy a Private GPG Key across Machines

This document shows the steps to export and then import again a private GPG key. I find this useful when I need to reinstall my OS. If the GPG key has not been compromised (e.g., theft), then this is a safe way of moving keys around.

First, obtain the ID of the private key.

gpg --list-secret-keys --keyid-format LONG

This generates output that looks like the following

/home/andrea/.gnupg/pubring.kbx
-------------------------------
sec   rsa4096/<key-id> yyyy-mm-dd [SC]
      <long-alphanumeric-string>
uid   Andera Pasqualini (Key at <user@host>) <email>
ssb   rsa4096/<alphanumeric-string> yyyy-mm-dd [E]

The output will be longer if you have multiple keys. Note that the line starting with sec will contain the alphanumeric string <key-id>. Copy the key ID.

Then, export the private key to a file.

gpg --export-secret-keys <key-id> > ./private_gpg.key

This creates (or overwrites, if it exists already) a file named private_gpg.key in your current working directory.

Finally, import the key again.

gpg --import ./private_gpg.key

👉 Mind how you copy the GPG key across machines. Copying the file private_gpg.key over USB devices is not a great idea, because the file will remain readable even if you delete the file or format the device. The only way to safely make files on an external drive unreadable is by physically destroying the drive. If possible, copy (or better, pipe) the key over a ssh connection.

References

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment