user9241855
user9241855

Reputation: 25

SHA256 giving unexpected result

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())

Here's an example output.

When I compare with several online sha256 functions, the output doesn't match. For this example, the correct hash should be: enter image description here

What am I doing wrong?

Upvotes: 1

Views: 983

Answers (2)

SbMil
SbMil

Reputation: 29

You need to give encoded input to sha256. Input must be passed as a bytestring. Use encode() method to convert it to bytestring format.


hashed = hashlib.sha256("test".encode()).hexdigest()
print(hashed)

In your case use bytes() method to encode your byte array:


hash_input=bytes(input)

Result: 9f86d081884c7d659a2feaa0c55ad015a3bf4f1b2b0b822cd15d6c15b0f00a08

Actual res from :9f86d081884c7d659a2feaa0c55ad015a3bf4f1b2b0b822cd15d6c15b0f00a08

Upvotes: -1

Mark Tolonen
Mark Tolonen

Reputation: 177396

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'

Upvotes: 2

Related Questions