I'm trying to use hashlib to hash a byte array, but I can't get the hash to match what I am expecting (by confirming the answer with online SHA256 functions).
Here's how I'm doing the hash:
hashedData = hashlib.sha256(input[0:32]).hexdigest()
print('hash = ', hashedData)
Before I do the hash, I print out the hex digest for the input data:
print('input = ', input[0:32].hex())
When I compare with several online sha256 functions, the output doesn't match. For this example, the correct hash should be:
What am I doing wrong?
The data being hashed in your code appears to be a byte string, but the data you hash on whatever online tool you are using is your .hex()
result, which is ASCII hexadecimal values. They are not the same thing. See below for a comparison that reproduces both of your results:
from binascii import unhexlify
import hashlib
data1 = b'ff815ef617d058df5d16f96a73591e4d12ac358cc113a8c74d8f4ac5843dd921'
data2 = unhexlify(data1)
print(f'{data1=}\n{data2=}')
hashed1 = hashlib.sha256(data1).hexdigest()
hashed2 = hashlib.sha256(data2).hexdigest()
print(f'{hashed1=}\n{hashed2=}')
Output:
data1=b'ff815ef617d058df5d16f96a73591e4d12ac358cc113a8c74d8f4ac5843dd921'
data2=b'\xff\x81^\xf6\x17\xd0X\xdf]\x16\xf9jsY\x1eM\x12\xac5\x8c\xc1\x13\xa8\xc7M\x8fJ\xc5\x84=\xd9!'
hashed1='e417268832671b04efa73ba4093572975e084b8b33bfdcb4f9345093f80106ff'
hashed2='56e8d96c55150870ecc84c9a355de617993e21e29c9edcf3caa369b252fd2108'