Crypto.DEREncodePublicKey findings

Hi all,

I had a little play with the new Crypto functions to export DER. With my test the Private Key exported was easy to use outside but I had some trouble with the public key. Some experimentation revealed that this is a DER encoded RSA Public Key, not the default public key openssl rsa spits out. To make complete the confusion, the openssl version on OSX 10.8 seems to be unable to deal with this format. To ease the key exchange with 3rd parties, I wrote a little function to convert the DER to PEM which is more easy to understand. If anybody interested, here is the code:

[code]Protected Function PEMEncodePublicKey(publicKey As String) As String
//the integrated Crypto.DEREncodePublicKey function outputs an MemoryBlock filled with the binaray form of an DER
//encoded RSAPublicKey (not the usual PublicKey OpenSSL exports with -pubout!)
//this method reformat that to PEM which is human readable and makes the unusual format obvious
//this does the same as:
//openssl rsa -inform der -outform pem -RSAPublicKey_out < Crypto.DEREncodePrivateKey
//or more specifically:
//openssl rsa -inform der -RSAPublicKey_in -outform pem -RSAPublicKey_out < Crypto.DEREncodePublicKey

dim result as string
dim DER as MemoryBlock

if Crypto.RSAVerifyKey(publicKey) then
DER = Crypto.DEREncodePublicKey(publicKey)

result = "-----BEGIN RSA PUBLIC KEY-----" + EndOfLine
result = result + ReplaceLineEndings(EncodeBase64(DER, 64), EndOfLine) + EndOfLine
result = result + "-----END RSA PUBLIC KEY-----" + EndOfLine

end if

return result
End Function

hope this saves someone a little trouble.


Thanks, this is actually extremely relevant to me right now.

thank you for promoting Im-/Export and the RSA stuff in the first place!

For these that are finding this in the archives:
The Public Key format Crypto.DEREncodePublicKey outputs is a RSA Public Key in DER format. This means PKCS#1 encoding. The ‘usual’ Public Key format is X.509 encoded. In PEM: -----BEGIN RSA PUBLIC KEY----- means PKCS#1, -----BEGIN PUBLIC KEY----- X.509
The Private Key Crypto.DEREncodePrivateKey outputs seems to be a plain PKCS #8/ASN.1 Private Key in DER format, not encrypted, so no pass-phase. As usual, it is possible to extract the Public Key from the Private Key.
further opernssl convertions are discussed here:
further readings:

Thanks Tobias, very helpful for me today. Do private keys require the same kind of conversion?

It does. The prefix and suffix strings are different though.