1

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
  • 112,593
  • 23
  • 157
  • 280
Alphadelta14
  • 2,674
  • 3
  • 15
  • 17

2 Answers2

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
  • 1,798
  • 2
  • 4
  • 22
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
  • 273
  • 1
  • 6