Get common name (CN) from SSL certificate?

If you have openssl installed you can run:

openssl x509 -noout -subject -in server.pem

certtool -i < whatever.pem | egrep "^\s+Subject:"

Notice that's directing the file to standard input via <, not using it as argument. Sans egrep this will print the whole certificate out, but the CN is in the Subject: field near the top (beware there's also a CN value in the Issuer: field).

X.509 Certificate Information:
    Version: 3
    Serial Number (hex): 01
    Issuer: [...] CN=unixandlinux.ex  <- Not this one.
    Validity: ...
    Subject: CN=goldilocks

certtool is part of gnutls, if it is not installed just search for that. GnuTLS is a little nicer than OpenSSL, IMO.


I found the above answer, and found it to be very useful, but I also found that the certtool command syntax (on Ubuntu Linux, today) was noticeably different than described by goldilocks, as was the output. So, I thought it best to update that excellent answer with what might be "today's version."

The "i" option (now?) stands for "import," according to man certtool, so the proper command appears to be "d", "display." So, this command:

certtool d myfoo.crt

(The file-extension in my case just happens to be .crt not .pem ... this is not relevant.)

... produces output that, in relevant part, looks like this:

Common Name     : Foobar

Unquestionably, goldilocks was right: certtool output is much easier easier to work with than openssl in this case.