How to convert DER formatted public key file to PEM form

public-keyrsaunix

I need to use the PEM formatted public key for some purpose, but not finding the command which can convert DER formatted public key to PEM formatted public key.

The command I have used –
openssl rsa -in user_id_rsa.pub -inform DER -outform PEM -out pubkey.pem

Actually the command expect private key as a input.
But I got the below error –

unable to load Private Key 139901900170912:error:0D0680A8:asn1
encoding routines:ASN1_CHECK_TLEN:wrong tag:tasn_dec.c:1337:
139901900170912:error:0D08303A:asn1 encoding
routines:ASN1_TEMPLATE_NOEXP_D2I:nested asn1 error:tasn_dec.c:677:
139901900170912:error:0D0680A8:asn1 encoding
routines:ASN1_CHECK_TLEN:wrong tag:tasn_dec.c:1337:
139901900170912:error:0D07803A:asn1 encoding
routines:ASN1_ITEM_EX_D2I:nested asn1 error:tasn_dec.c:388:Type=RSA

My expected output should be in this format-

—–BEGIN RSA PUBLIC KEY—–
KEY CONTENT
—–END RSA PUBLIC KEY—–

Has anyone tried the same?

Best Answer

You should add -pubin for public key inputs.

openssl rsa -pubin -in user_id_rsa.pub -inform DER -outform PEM -out pubkey.pem

EDIT: To handle PEM RSA PUBLIC KEY format, specify -RSAPublicKey_in -RSAPublicKey_out instead.

openssl rsa -RSAPublicKey_in -in user_id_rsa.pub -inform DER -outform PEM -out pubkey.pem -RSAPublicKey_out

If you want to convert OpenSSH public key to PEM RSA PUBLIC KEY, just use ssh-keygen.

ssh-keygen -f user_id_rsa.pub -e -m PEM > pubkey.pem