How to generate MD5 hash in Python?
MD5 (Message Digest Algorithm 5) is a way to turn any input (like a text or file) into a fixed-length string of characters, usually a 32-character hexadecimal number. It’s often used to check the integrity of data—if the data changes even slightly, the MD5 hash will change.
To generate an MD5 hash in Python, you can use the hashlib
module:
- Create an MD5 hash object using
hashlib.md5()
. - Update the hash object with the string you want to hash, making sure to encode it into bytes.
- Get the resulting hash value using the
hexdigest()
method, which will give you the hash as a readable hexadecimal string.
import hashlib
def generate_md5_hash(text: str) -> str:
md5_hash = hashlib.md5()
md5_hash.update(text.encode('utf-8'))
return md5_hash.hexdigest()
# Example usage
text = "Hello, World!"
md5_hash_value = generate_md5_hash(text)
print("MD5 Hash:", md5_hash_value)