DEV Community

Mario García
Mario García

Posted on • Updated on

Git: Backup and Restore GPG and SSH Keys

To sign your commits, you can use SSH (as explained in this article) or GPG keys.

Through this blog post, you will learn how to back up and restore your keys in case of changing device or reinstalling operating system.

Backup and Restore

SSH

To back up your keys:

  • Copy both id_x and id_x.pub from ~/.ssh/ to a USB drive

Where x is any of the supported SSH key types by GitLab, as shown in the following table:

Algorithm Public key Private key
ED25519 (preferred) id_ed25519.pub id_ed25519
ED25519_SK id_ed25519_sk.pub id_ed25519_sk
ECDSA_SK id_ecdsa_sk.pub id_ecdsa_sk
RSA (at least 2048-bit key size) id_rsa.pub id_rsa
DSA (deprecated) id_dsa.pub id_dsa
ECDSA id_ecdsa.pub id_ecdsa

To restore your keys, follow the instructions:

  • Copy both id_x and id_x.pub to ~/.ssh/
  • Change file permissions and ownership of both files


$ chown user:user ~/.ssh/id_rsa*
$ chmod 600 ~/.ssh/id_rsa
$ chmod 644 ~/.ssh/id_rsa.pub


Enter fullscreen mode Exit fullscreen mode

Where user is the username that you log in to your system with.

  • Start the ssh-agent


$ exec ssh-agent bash


Enter fullscreen mode Exit fullscreen mode
  • Add your SSH private key to the ssh-agent


$ ssh-add ~/.ssh/id_rsa


Enter fullscreen mode Exit fullscreen mode

GPG

  • Identify the private key by executing the following command.


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


Enter fullscreen mode Exit fullscreen mode

It will show something similar to this.



sec   4096R/3AA5C34371567BD2 2016-03-10 [expires: 2017-03-10]


Enter fullscreen mode Exit fullscreen mode

Characters after the slash are the ID of the private key.

  • Export the private key.


gpg --export-secret-keys $ID > my-private-key.asc


Enter fullscreen mode Exit fullscreen mode

$ID is the value of the ID of your private key, that was obtained previously.

  • Copy my-private-key.asc to a USB drive.

To restore:

  • Copy the my-private-key.asc file from the USB drive and paste it in the device where you want to import it

  • Import your GPG key



$ gpg --import my-private-key.asc


Enter fullscreen mode Exit fullscreen mode

Once the keys are imported, you can continue siging your commits.


Support me on Buy Me A Coffee

Top comments (0)