← Go Back

How to Hash a String With MD5

Using the hashlib standard module:

>>> from hashlib import md5
>>> md5(b"Hello, world!").hexdigest()

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()

To hash the content of a file (e.g., an image) you can use the following code:

with open("image.jpg", "rb") as f:

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()

cryptography md5 hashlib hashing

🐍 You might also find interesting: