Search code examples
pythonhexpycrypto

Two ways of printing a SHA-256 hash differ in 1 byte in Python


Consider the snippet:

from Cryptodome.Hash import SHA256
text = b'Jeanny'
print('Hash of', text)

hx = SHA256.new(text).hexdigest()
print(hx)

h = SHA256.new(text).digest()
[print('{0:x}'.format(h[i]), end = '' ) for i in range(0,len(h))]

It prints:

Hash of b'Jeanny'
f51c7dbd56cc25c565f7c7ef951b06121e87e34f2e3bb466e873a2518715fe50
f51c7dbd56cc25c565f7c7ef951b6121e87e34f2e3bb466e873a2518715fe50

Why is it that the second printed string of hex digits misses 0 in position 29?


Solution

  • Because it's trying to print "06", but you haven't told it to zero-fill the numbers.