Read common name from .pem file

2019-04-08 05:22发布

问题:

is there a way to read the common name from a .pem file in my shell?

Thanks

回答1:

First off, the .pem extension only refers to the type of encoding used in the file.

The common name would be a feature of the Subject or Issuer of a certificate, and can be recognised by the lines

$ grep CERTIFICATE f.pem
-----BEGIN CERTIFICATE-----
-----END CERTIFICATE-----

and lots of base64 encoded text in between.

If the .pem file contains an x509 certificate, this should do the trick:

openssl x509 -in cacert.pem -noout -text

This will dump the whole certificate. The openssl x509 command has several options to suppress the fields you don't want to see. You find those explained in the man page, under TEXT OPTIONS

You can also choose to get shown just the 'Subject' of the certificate:

openssl x509 -in cacert.pem -noout -subject

Example:

Let's capture the certificate of stackoverflow.com straight from the server

$ : | openssl s_client -connect stackoverflow.com:443 > f.pem 2>& 1 &&
      openssl x509 -in f.pem -noout -subject 2>& 1

Outputs:

subject= /C=US/ST=NY/L=New York/O=Stack Exchange, Inc./CN=*.stackexchange.com