17

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

2 Answers 2

28

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.

2
  • @CG3 - the question asks for the result to contain colons every two characters: 68:0B:C3:26:B5:75:2E:D0:FC:B5:59:88:9B:24:A7:69:98:48:2B:F4. Your suggestion doesn't, and results in : 680BC326B5752ED0FCB559889B24A76998482BF4. That's with OpenSSL 3.0.15. Commented Mar 1 at 7:04
  • You're absolutely right, my fault. Your sed syntax is spot on! Commented Mar 3 at 15:51
2

openssl x509 -noout -text -in [cert] is getting you more info about the cert, and if you want just the serial, you can grep for that there, ie.

... | grep -A1 "Serial Number"

This would give generate output like:

Serial Number:
            07:bf:0e:14:95:e7:1e:34:a2:b1:8b:df:ca:dd:ab:af:af:fb:50:fb

to remove the Serial Number: text add a tail -1

The full command would then be:

openssl x509 -noout -text -in [cert] | grep -A1 "Serial Number" | tail -1
1
  • No need to fight :-) You can provide your own answer even if the question already has an accepted one. However you should formulate the answer properly to ensure it won't get deleted - partial answers like this do. I'd suggest taking the Tour and checking the Asking- and Answering -sections in the Help to learn how these sites work. Commented Feb 18, 2023 at 19:08

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.