OpenSSL – How to Extract Serial from SSL Certificate

openssl

I'd like to know what is the best way to extract serial number from a SSL certificate formatted in PEM format.

After that I'd like to format the certificate in following format hexhex:hexhex:...:hexhex
so for example if my serial number of the SSL certificate in hexadecimal is

0123456709AB

the output should be

01:23:45:67:09:AB

For preference I'd like to acomplish this using openssl with the x509 option using one single line UNIX command

Best Answer

Try:

openssl x509 -noout -serial -in cert.pem | cut -d'=' -f2 | sed 's/../&:/g;s/:$//'

openssl x509 -noout -serial -in cert.pem will output the serial number of the certificate, but in the format serial=0123456709AB.

It is therefore piped to cut -d'=' -f2 which splits the output on the equal sign and outputs the second part - 0123456709AB.

That is sent to sed. The first part of the sed command s/../&:/g splits the string every two characters (..) and inserts a colon (:). This results in 01:23:45:67:89:AB: (note the colon on the end).

The second part of the sed command (s/:$//) searches for a colon at the end of the output and replaces it with an empty string, resulting in the desired output.


Or for a openssl and sed only answer:

openssl x509 -noout -serial -in test2.crt |  sed 's/.*=//g;s/../&:/g;s/:$//'

The addition of s/.*=//g at the start of the sed command replaces the cut in the first version.