Search code examples
pythonhashx509

How do I print a fingerprint (sha256 bytes) using colon notation?


I have an x509 certificate fingerprint which is basically just a SHA 256 byte string.

These are usually notated in the form 43:51:43:a1:b5:fc:8b:b7:0a:3a:a9:b1:0f:66:73:a8.

Is there a more appropriate way to generate these from a byte string like b'CQC\xa1\xb5\xfc\x8b\xb7\n:\xa9\xb1\x0ffs\xa8'?

binascii.hexlify(b'CQC\xa1\xb5\xfc\x8b\xb7\n:\xa9\xb1\x0ffs\xa8') gets me halfway there (b'435143a1b5fc8bb70a3aa9b10f6673a8'), but I don't have any of the colons.


Solution

  • hashbytes = b'CQC\xa1\xb5\xfc\x8b\xb7\n:\xa9\xb1\x0ffs\xa8'
    print(":".join([format(i,'02x') for i in hashbytes]))
    

    43:51:43:a1:b5:fc:8b:b7:0a:3a:a9:b1:0f:66:73:a8

    There's probably a shorter way, perhaps with the format() method on the hexdigest() string output.