Search code examples
pythonhashlib

How to cast HASHLIB digest to array in python?


I'm trying to compare the result of an SHA1 digest to an initialized array.

But when comparing the first byte, it returns that they are not equal, while when printing the first byte of the digest, it's the same as the first byte in my initialized array.

Should I cast it somehow?

import hashlib


my_digest = [0x7,0x3,0x8,0x2,0x2,0x5,0x6,0xa,0xb,0xb,0x3,0xe,0xe,0xa,0x3,0x2,0x5,0xf,0x9,0xa,0xd,0xe,0x1,0xc,0xc,0x0,0x4,0xe,0x4,0x9,0x3,0x3,0xe,0xe,0x8,0x1,0x7,0xc,0xd,0x3]
digest = hashlib.sha1(b"im a very good speaker").hexdigest()
# digest = 7382256abb3eea325f9ade1cc04e4933ee817cd3

if(digest[0] == my_digest[0]):
    print("correct")
else:
    print("not correct")
print(digest)

output :

not correct
7382256abb3eea325f9ade1cc04e4933ee817cd3

print(digest[0]) return 7


Solution

  • First of all, if you want to represent the digest as a list of hex integers, it will look like this:

    >>> my_digest = [0x73, 0x82, 0x25, 0x6a, 0xbb, 0x3e, 0xea, 0x32, 0x5f, 0x9a, 0xde, 0x1c, 0xc0, 0x4e, 0x49, 0x33, 0xee, 0x81, 0x7c, 0xd3]
    

    Second, you want digest() instead of hexdigest() to get the raw bytes hash:

    >>> digest = hashlib.sha1(b"im a very good speaker").digest()
    

    Finally, convert it to list before comparison:

    >>> list(digest) == my_digest
    True