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.
Find a keygrip of desired private key
gpg --list-secret-keys --with-keygrip
Import it into a new temporary gpgsm keyring
gpgsm --gen-key -o /tmp/keyring
#> 2 #select existing key
#> #keygrip_id
#> 3 #key purpose encryption, this is probably irrelevant
#> C=dummy, ST=dummy, L=dummy, O=dummy, OU=dummy, CN=dummy #Enter dummy X.509 subject name
#> nonexistent@dummy.com #email as well
The rest of the options are optional so just Enter through them, confirm the information, and enter the decryption password of key selected.
Now convert the key to pkcs12 format
gpgsm -o /tmp/key.p12 --export-secret-key-p12 '&keygrip_id'
Enter again the encryption password as before to decrypt it. Then enter new password which should be used for .p12 file. If your /tmp folder resides on RAM like mine, you can leave it blank as it will be safely removed after reboot.
Now convert it to ssh friendly format, which requires stripping first 4 output lines, so that it starts with ---BEGIN PRIVATE KEY---.
openssl pkcs12 -in /tmp/key.p12 -nodes -nocerts | tail -n +5 > /tmp/sshkey
There you have sshkey ready to use by ssh client. Hope this helps.