← Go Back
Note that
To hash the content of a file (e.g., an image) you can use the following code:
Data to be hashed can be given in chunks using the
How to Hash a String With MD5
Using thehashlib
standard module:>>> from hashlib import md5
>>> md5(b"Hello, world!").hexdigest()
'6cd3556deb0da54bca060b4c39479839'
Note that
hashlib.md5()
takes a bytes
object, not a string. Therefore, to hash a string you must encode it first:>>> s = "Hello, world!"
>>> md5(s.encode("utf-8")).hexdigest()
'6cd3556deb0da54bca060b4c39479839'
To hash the content of a file (e.g., an image) you can use the following code:
with open("image.jpg", "rb") as f:
print(md5(f.read()).hexdigest())
Data to be hashed can be given in chunks using the
update()
method. This is especially helpful when data is too large to be loaded in memory at once:>>> h = md5()
>>> h.update(b"Hello, ")
>>> h.update(b"world!")
>>> h.hexdigest()
'6cd3556deb0da54bca060b4c39479839'
🐍 You might also find interesting: