Reputation: 993
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
Upvotes: 0
Views: 1288
Reputation: 34282
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
Upvotes: 1
Reputation: 26896
In Python 3, with your code you are comparing str
with int
and while this can be done, it would not try to interpret the content of the string, so '7' != 7
.
One way to circumvent this is to cast your int
to str
, e.g.:
if digest[0] == str(my_digest[0]):
Upvotes: 0
Reputation: 3790
The issue is with the type
. You are comparing a string to an int. See below for a possible fix.
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
print("digest[0]", type(digest[0]))
print("my_digest[0]", type(my_digest[0]))
if(int(digest[0]) == my_digest[0]):
print("correct")
else:
print("not correct")
print(digest)
Upvotes: 0