Get common name (CN) from SSL certificate?

  • I have a SSL CRT file in PEM format. Is there a way that I can extract the common name (CN) from the certificate from the command line?

    Note, however, that in multi-domain certificates, CN does not contain all of them.

  • Jeff Smith

    Jeff Smith Correct answer

    7 years ago

    If you have openssl installed you can run:

    openssl x509 -noout -subject -in server.pem
    

    You can extract the CN out of the subject with: `openssl x509 -noout -subject -in server.pem | sed -n '/^subject/s/^.*CN=//p'`

    I modified what @MatthewBuckett said and used `sed -e 's/^subject.*CN=\([a-zA-Z0-9\.\-]*\).*$/\1/'` to get just the domain as I had additional details after the CN. Its not super strict matching for a valid CN but in most cases it works, you could be more slack and replace `[a-zA-Z0-9\.\-]` with `[^/]` but I am not certain that would always work.

    Add `\*` to what @flungo used to support wildcard domains: `sed -e 's/^subject.*CN=\([a-zA-Z0-9\.\-\*]*\).*$/\1/'` (`[^/]` works in my case, though)

    The `sed` commands suggested above won't work if the cert has Relative Distinguished Names (RDNs) specified after the Common Name (CN), for example OU (OrganizationalUnit) or C (Country). One way to cater for such cases would be an additional `sed`: `openssl x509 -noout -subject -in server.pem | sed 's/^.*CN=//' | sed sed 's/\/.*$//'`.

    **Easier way to separate** CN from other RDN/ATVs in Subject name: `openssl x509 -noout -subject -nameopt multiline | grep commonName` or for the value only `| sed -n 's/ *commonName *= //p'`

    Hmm, I had to use my `.crt`, not my `.pem` but otherwise it worked. Not sure if something's set up differently (MacOS, `OpenSSL 0.9.8zh 14 Jan 2016`)

License under CC-BY-SA with attribution


Content dated before 6/26/2020 9:53 AM