Home > front end >  How to compare two byte arrays in Python
How to compare two byte arrays in Python

Time:04-16

I am trying to compare two byte arrays in Python.

This is my code

print("new_digest: ", new_digest)
print("digest: ", digest)
if digest == new_digest:
    return True
else:
    return False

and this is the output:

new_digest:  b"<\xc3\xb8\xa9'3\x81\xa2\xfb\xf7\xbfCm\xa8\xd6O\xd0\x03\xdd\xfadW\xfd,\xed\x03\\m\x87\xf8*"

digest:  b"<\xc3\xb8\xa9'3\x81\xa2\xfb\xf7\xbfCm\xa8\xd6O\xd0\x03\xdd\xfadW\xfd,\xed\x03\\m\x87\xf8*"

It is clear that they are equal but the function is returning false. Why is this?

The byte streams are generated using

from cryptography.hazmat.primitives import hashes
digest = hashes.Hash(hashes.SHA256())
digest.update(message)
digest = digest.finalize()

CodePudding user response:

Their Types could be different.Also I recommend you to use

return digest == new_digest

instead

if digest == new_digest:
    return True
else:
   return False

compare

type(digest) and type(new_digest)

if it won't work, convert to string and strip them.

.strip()

  • Related