'How to get public key in .cer or .crt formats

I have created self-signed SSL certificate using OpenSSL as follow:

openssl req -x509 -newkey rsa:2048 -keyout key.pem -out cert.pem -days 365

This gave me certificate and private key in .pem file. I need to provide my public key to my clients in .cer or .crt format. Is there any way to get public key in .cer/.crt formats?

What I have already tried:

1. Generating public key in .pem format and trying to convert it to .cer or .crt [Didn't work]

To extract public key in .pem file [worked fine]:

`openssl x509 -pubkey -noout -in signer-cert.pem  > signer-public-key-test.pem`

To convert it from .pem for .cer format openssl x509 -inform PEM -in signer-public-key-test.pem -outform DER -out signer-public-key-test.cer I get this error:

unable to load certificate
140067363030680:error:0906D06C:PEM routines:PEM_read_bio:no start line:pem_lib.c:701:Expecting: TRUSTED CERTIFICATE

2. Converting my certificate to .cer (which I did fine) and trying to export public key using windows certificate export wizard as instructions given here

It didn't work either. I couldn't enable the option to export keys and the final output, when opened in notepad++ was garbage.

So my question is, is there any way to generate the certificate from scratch and have the public key in .cer or .crt file. OR generating the certificate in .pem format and later extracting public keys to .crt or .cer

Any help is deeply appreciated.



Solution 1:[1]

Since .cer and .crt usually mean "DER or PEM-DER X.509 certificate" I don't know what you mean by having the public key in that format.

If you mean you want a DER encoded SubjectPublicKeyInfo representing the public key, the second stage of your pipeline would be

openssl asn1parse -noout -out some.file

You can remove the intermediate with

openssl x509 -in signer-cert.pem -noout -pubkey | 
    openssl asn1parse -noout -out signer-public-key-test.der

(Newline added to remove scrollbar)

Or, skip the certificate middleman altogether:

openssl rsa -in key.pem -pubout -outform der -out signer-public-key-test.der

Seems pretty weird that you want that particular format, though.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 bartonjs