Your answer is one click away!

frogcdcn February 2016
### openssl - RSA public key from PEM to DER

I confronted a problem when translating RSA pub key using openssl, I want to get public key in DER format. Here is what I did:

generate RSA key pair openssl genrsa -out alice.key 1024

export only public key from my.key a) openssl rsa -in alice.pem -RSAPublicKey_out -out alice_pub.pem b) openssl rsa -in alice.pem -pubout -out alice_pub2.pem

The two approaches generate different footers in .pem: the first one outputs
`--Begin RSA public key ----`

, and the second outputs
`-- Begin Public key ----`

When using openssl asn1parse to analyze the two public key pem files,

`openssl asn1 parse -inform PEM -in alice_pub.pem`

, something unexpected happened. For alice_pub.pem, it works good; for alice_pub2.pem, openssl is unable to extract the "N" and "E" parameters indicating they have been "rsaEncryption".Openssl can only transform the second pem to DER, however, the pem content is obviously incorrect...

pls let me know how to solve this problem. Many thanks. This issue can be reproduced easily.

It's unclear what you mean when you say that OpenSSL can only transform the second PEM to DER - `openssl asn1parse`

can read both and output both as DER.

The output of `-RSAPublicKey_out`

is just the public key with no additional wrapping, and when put through `openssl asn1parse`

, you get the following:

```
0:d=0 hl=3 l= 137 cons: SEQUENCE
3:d=1 hl=3 l= 129 prim: INTEGER :...
135:d=1 hl=2 l= 3 prim: INTEGER :010001
```

However the output produced by `-pubout`

is a public key in X509 format, when put through `openssl asn1parse`

, you get the following output:

```
0:d=0 hl=3 l= 159 cons: SEQUENCE
3:d=1 hl=2 l= 13 cons: SEQUENCE
5:d=2 hl=2 l= 9 prim: OBJECT :rsaEncryption
16:d=2 hl=2 l= 0 prim: NULL
18:d=1 hl=3 l= 141 prim: BIT STRING
```

This format wraps the public key (displayed undecoded as `BIT STRING`

) with an indicator that it's an *RSA* public key (`rsaEncryption`

).

You can show the details of the encoded public key in the `-pubout`

output by using the `-strparse`

option for `openssl asn1parse`

. In the above output you can see the `BIT STRING`

is at offset 18, so using:

```
openssl asn1parse -inform PEM -in alice_pub2.pem -strparse 18
```

You will get something like the following:

```
0:d=0 hl=3 l= 137 cons: SEQUENCE
3:d=1 hl=3 l= 129 prim: INTEGER :...
135:d=1 hl=2 l= 3 prim: INTEGER :010001
```

In other words, exactly the same data as the raw RSA public key produced by the `-RSAPublicKey_out`

option for `openssl rsa`

.

Asked in February 2016

Viewed 2,046 times

Voted 9

Answered 1 times

Viewed 2,046 times

Voted 9

Answered 1 times