Skip to content

Instantly share code, notes, and snippets.

@fredreichbier
Last active March 10, 2024 09:47
Show Gist options
  • Star 5 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save fredreichbier/4399625 to your computer and use it in GitHub Desktop.
Save fredreichbier/4399625 to your computer and use it in GitHub Desktop.
How to extract your private ssh key from gpg-agent

How to extract a SSH private key from gpg-agent

Problem: Lost private key file ~/.ssh/id_rsa, but could connect to remote hosts via pubkey auth anyway: gpg-agent cached the private key. How to get the private key?

Solution: Use gpg-protect-tool to get the key (you need to know the passphrase of course):

gpgsm --call-protect-tool --p12-export ~/.gnupg/private-keys-v1.d/your-keyfile.key >key.p12

Now you have a PKCS12 file and you can extract the private key like this:

openssl pkcs12 -in key.p12 -out privkey.pem

And there is your extracted private key.

@hanyuwei70
Copy link

nvm. I have managed to recover my private key by decrypt original key and using cryptography Python library.
if you decrypted your key, there is a d section which is 32 bytes long. Use that in cryptography library to reconstruct your OpenSSH key.

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