6

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?

BE77Y
  • 2,667
  • 3
  • 18
  • 23
CodeQuestor
  • 235
  • 1
  • 2
  • 6

1 Answers1

8

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
yaegashi
  • 841
  • 5
  • 11
  • Thanks for your inputs..But i got the following error - unable to load Public Key 139731637118624:error:0D0680A8:asn1 encoding routines:ASN1_CHECK_TLEN:wrong tag:tasn_dec.c:1337: 139731637118624:error:0D07803A:asn1 encoding routines:ASN1_ITEM_EX_D2I:nested asn1 error:tasn_dec.c:388:Type=X509_PUBKEY – CodeQuestor May 26 '15 at 16:42
  • Is `user_id_rsa.pub` really an RSA public key in DER format? How did you generate that file? OpenSSH public key format is not DER. – yaegashi May 26 '15 at 20:06
  • Please check updates in my answer. – yaegashi May 26 '15 at 20:32
  • @CodeQuestor, Accept this answer if this solved your question. – Appaji Chintimi Nov 23 '21 at 15:29