Ssh – How to convert a ssh-keygen public key into a format that openssl PEM_read_bio_RSA_PUBKEY() function will consume

opensshopenssl

I'm having an issue generating a public key that the openssl PEM_read_bio_RSA_PUBKEY() function can consume. I keep getting errors.

Obviously I cannot simply use the ASCII string in the ssh-keygen <>.pub key file as it is in SSH file format or I perhaps SubjectPublicKeyInfo structure.

Here's the key gen code: ssh-keygen -t rsa -b 1024 -C "Test Key"

I found a converter in php on the web which will convert the contents of the public key into a base64 PEM ASCII string format. However the function still doesn't like it.

The Openssl documentation states:

  1. “RSA_PUBKEY() function which process a public key using an EVP_PKEY structure”
  2. “RSA_PUBKEY functions also process an RSA public key using an RSA structure”

How do I get my OpenSSH public key into either format that the OpenSSL function will consume it?

Best Answer

OK!

So I walked into this thinking "Easy, I got this." Turns out there's a whole lot more to it than even I thought.

So the first issue is that (according to the man pages for OpenSSL (man 3 pem)), OpenSSL is expecting the RSA key to be in PKCS#1 format. Clearly this isn't what ssh-keygen is working with. You have two options (from searching around).

If you have OpenSSH v. 5.6 or later (I did not on my laptop), you can run this:

ssh-keygen -f key.pub -e -m pem

The longer method of doing this is to break apart your SSH key into it's various components (the blog entry I found some of this in accuses OpenSSH of being "proprietary", I prefer to call it "unique") and then use an ASN1 library to swap things around.

Fortunately for you, someone wrote the code to do this:

https://gist.github.com/1024558

Related Question