GPG: Restoring a private key's UID from a pubkey's UID

The problem

When creating a new keypair since my old key was getting old (and insecure), I decided to backup my private key to an undisclosed location for security.

Unfortunately I did then add a UID to my private key and forgot to re-backup the key, which resulted in my public key have several UIDs, but my private key showing only one when restored from backup. I did try the restore procedure, but maybe a little too zealously and ended up nuking my .gnupg directory.

Yeah, get some sleep before you mess with gpg :)

The solution

It is actually pretty simple to solve the problem of "importing" your pubkey's UIDs to your privkey.

First, backup!

Let's not mess things any further and start with a good ol' backup of your ~/.gnupg directory:

cp -rp ~/.gnupg ~/BACKUP.gnupg

The plan

The idea is that the public portion of the UID is created simply as a function of your private key and the UID string. That means recreating a UID with the same string and the same key will be mathematically equivalent, and since the signatures you collected are function of the public key and the UID, they will be valid if we recreate a UID with the exact same string.

So the plan is to delete the missing UID in the pubkey, and then recreate the exact same UID, which will insert it in both the pubkey and the private key.

Deleting the missing UID(s) from the pubkey

Let's delete the missing UID from the pubkey.

It starts by editing the key:

gpg --edit-key <key ID>

At the GPG prompt, select the UID that is missing in the private key. Make sure you note down the full UID, exactly as it appears:

uid <unid number>

This will echo your pubkey UIDs back to you, and you should notice a little "*" next to the key you selected. Now, let's nuke it:

deluid

Recreating the same UID

Now that the UID is gone, let's re-add the exact same UID to the keypair:

adduid

Make sure you fill in the exact same UID information as you had before!

Don't forget to save

At the GPG prompt, make sure you save your work by issuing the following aptly named command:

save

Make sure it worked

You should now have your missing UIDs back in your private keyring! Let's check with:

gpg --list-private-keys

Make sure it all outputs what you expect (all the UIDs are there).

That's all! Hope it helps!