2

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.

martineau
  • 119,623
  • 25
  • 170
  • 301
Alphadelta14
  • 2,854
  • 3
  • 16
  • 19

3 Answers3

3
no_colon = b'CQC\xa1\xb5\xfc\x8b\xb7\n:\xa9\xb1\x0ffs\xa8'.hex()
colon = ':'.join(no_colon[i:i+2] for i in range(0, len(no_colon), 2))

Bascially, I used .hex() to essentially "remove" the b'' in the string and convert it to hex.

Then, ':'.join(no_colon[i:i+2] for i in range(0, len(no_colon), 2)) adds a colon after every 2 letters. I assume that's what you want. However, this will only work if there are always 2 characters between each colon.

This all outputs:

43:51:43:a1:b5:fc:8b:b7:0a:3a:a9:b1:0f:66:73:a8
The Pilot Dude
  • 2,091
  • 2
  • 6
  • 24
3
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.

fuzzydrawrings
  • 283
  • 2
  • 6
0

Take a look at the builtin hex function https://docs.python.org/3/library/stdtypes.html?highlight=hex#bytes.hex

You can add a parameter for a seperator.

    hashbytes = b'CQC\xa1\xb5\xfc\x8b\xb7\n:\xa9\xb1\x0ffs\xa8'
    print(hashbytes.hex(":"))
    43:51:43:a1:b5:fc:8b:b7:0a:3a:a9:b1:0f:66:73:a8
Mike
  • 1,495
  • 15
  • 11