0

I need to use the cryptography library to get the MD5 from a file, here's whats I have:

from cryptography.hazmat.primitives import hashes
archivos = input()
with open(archivos, "rb") as f:
    bfile = f.read()
    print(bfile)
    readable_hash = hashes.Hash(hashes.MD5())
    readable_hash.update(bfile)
    readable_hash.finalize()
    print(readable_hash)

When I print bfile i get this, and that's what I need to hash to MD5:

b'RGBX\x01\x00\x00\x00X\x00b\x00o\x00x\x00G\x00a\x00m\x00e\x00s\x00\x00\x00'

and when I try to print readable_hash that supose it contains the MD5, I just get this:

<cryptography.hazmat.primitives.hashes.Hash object at 0x000001EE89A17F10>
  • `readable_hash` is the hash *object*, not the hash result. The hash result is returned by `readable_hash.finalize()`, but you don't save it so it gets thrown away. – President James K. Polk Oct 31 '22 at 01:48

1 Answers1

0

You can turn this into a human-readable string with binascii.b2a_hex:

Return the hexadecimal representation of the binary data. Every byte of data is converted into the corresponding 2-digit hex representation. The returned bytes object is therefore twice as long as the length of data.

import binascii

# ...
data = readable_hash.finalize()
md5_hash = binascii.b2a_hex(data).decode()

print(f"MD5 hash = {md5_hash}")
Stefan
  • 115
  • 2
  • 7