MD5 hash in Python

MD5 hash in Python

MD5 (Message Digest Algorithm 5) is a widely used cryptographic hash function that produces a 128-bit (16-byte) hash value. It's commonly used to verify data integrity. However, MD5 is not collision-resistant; as such, it's not suitable for functions such as SSL certificates or cryptography that rely on a unique hash value.

In Python, you can compute the MD5 hash of a string or a file using the hashlib module.

1. MD5 Hash of a String:

import hashlib data = "Hello, World!" result = hashlib.md5(data.encode()) # Convert string to bytes and hash it md5_value = result.hexdigest() print(md5_value) 

2. MD5 Hash of a File:

If you want to compute the MD5 hash of a file's contents, you can do so by reading the file in binary mode:

def md5_of_file(file_path): with open(file_path, 'rb') as file: return hashlib.md5(file.read()).hexdigest() file_path = "path_to_your_file.txt" print(md5_of_file(file_path)) 

It's worth noting that while MD5 is fast, it's known to be vulnerable to hash collisions. For more secure applications, consider using a more collision-resistant hash function like SHA-256, also available in the hashlib module.


More Tags

metatrader5 delivery-pipeline abstract csh whatsapi uwsgi channel imageurl migration angular8

More Programming Guides

Other Guides

More Programming Examples