How To: Converting RSA keys from Crypto.RSAGenerateKeyPair

Let me preface this by saying that I’m not an expert in RSA, SSL, or OpenSSL, and don’t even know all the right terms. I’m merely reporting what worked for me.

We have a Xojo console app that has to share a private key with a JavaScript app, so we needed the key in the right format. I started with this post but that only got me part way. Still, a big help.

The problem: RSAGenerateKeyPair will create hex-encoded keys in the form of ABCDEF0123… but other platforms , like JavaScript, expect a key in the form of…

-----BEGIN PRIVATE KEY-----
123940aBa …
-----END PRIVATE KEY-----

It turns out that the conversion is dead simple. Just take the keys generated by RSAGenerateKeyPair, decode the hex, encode as Base64, and slap the header/footer on it.

For example:

dim privateKey as string
dim publicKey as string
call Crypto.RSAGenerateKeyPair( privateKey, publicKey )

dim convertedPrivateKey as string = _
    "-----BEGIN PRIVATE KEY-----" + EndOfLine  + _
    EncodeBase64( DecodeHex( privateKey ) ) + EndOfLine + _
    "-----END PRIVATE KEY-----"

If you need the DER encoded version, it’s almost the same thing, but you have to change the headers, like so:

  dim privateKey as string
  dim publicKey as string
  call Crypto.RSAGenerateKeyPair( 2048, privateKey, publicKey )
  
  dim derEncodedPrivateKey as string = Crypto.DEREncodePrivateKey( privateKey )
  
  dim convertedPrivateKey as string = _
  "-----BEGIN RSA PRIVATE KEY-----" + EndOfLine  + _
  EncodeBase64( derEncodedPrivateKey ) + EndOfLine + _
  "-----END RSA PRIVATE KEY-----"

Using a tool like openssl will show both as valid and output the DER encoded version.

openssl rsa -in ./path/to/key -check

I haven’t needed to convert the public key yet, but I’m guessing it will be something very similar.

I hope the experts here will jump in to clarify and correct.

I did a blog post last year about this:

http://blog.xojo.com/2015/06/01/privatepublic-key-interoperability/

Wouldn’t it be great if there was a reference to this blog from the appropriate developer.xojo.com pages & Local LR - both classic & new framework.