opensslpemder

Converting DER public key to PEM and back


I have a public key in DER format. asn1parse using openssl gives me this:

0:d=0 h1=4 1= 265 cons: SEQUENCE
4:d=1 h1=4 1= 256 prim: INTEGER: -4B95.........831 (I removed most of it)
264:d=1 h1=2 1=    3 prim: INTEGER 

I convert it to PEM using the following:

openssl rsa -RSAPublicKey_in -in myderkey -inform DER -outform PEM -out mypubkey

asn1parse looks like this after conversion:

0:d=0 h1=4 1= X cons: SEQUENCE
4:d=1 h1=2 1= X cons: SEQUENCE
...
...
...

I convert it back to DER using:

openssl rsa -pubin -in mypubkey -inform PEM - outform DER -out backToDerKey

After converting it back - asn1parse didn't change (remained the same when the key was in PEM format)

Is there any way to convert PEM public key to DER and have same ASN1 as the original DER key?

Tried to create create public key programmatically and save it to file, but got same results as with openssl.


Solution

  • Use the -RSAPublicKey_out argument to openssl to preserve the original PKCS1 format RSA key.

    You need to do this at each stage where you want PKCS1 format to be emitted by the OpenSSL rsa command.

    So, if you want that format for the PEM file then do it like this:

    openssl rsa -RSAPublicKey_in -in myderkey -inform DER -out mypubkey -RSAPublicKey_out
    

    If you want it in the DER file then do it like this:

    openssl rsa -pubin -in mypubkey -outform DER -out backToDerKey -RSAPublicKey_out