How to use the hashlib module for hash algorithm calculation in Python 2.x
In Python programming, the hash algorithm is a commonly used algorithm used to generate a unique identification of data. Python provides the hashlib module to perform hash algorithm calculations. This article will introduce how to use the hashlib module to perform hash algorithm calculations and give some sample codes.
The hashlib module is part of the Python standard library and provides a variety of common hash algorithms, such as MD5, SHA1, SHA256, etc. When using the hashlib module, you first need to import the module:
import hashlib
Next, we can use the various hash algorithms provided by this module. Among them, the most commonly used are the MD5 and SHA1 algorithms.
The MD5 algorithm is a common hash algorithm that converts data of any length into a 128-bit hash value. The following is an example of using the MD5 algorithm to calculate a hash value:
import hashlib data = "Hello, World!" md5_hash = hashlib.md5(data).hexdigest() print("MD5 Hash:", md5_hash)
Run the above code, the output result is:
MD5 Hash: b10a8db164e0754105b7a99be72e3fe5
import hashlib data = "Hello, World!" sha1_hash = hashlib.sha1(data).hexdigest() print("SHA1 Hash:", sha1_hash)
SHA1 Hash: 0a4d55a8d778e5022fab701977c5d840bbc486d0
import hashlib filename = "example.txt" with open(filename, 'rb') as f: file_contents = f.read() md5_hash = hashlib.md5(file_contents).hexdigest() print("MD5 Hash of", filename, ":", md5_hash)
The above is the detailed content of How to use hashlib module for hash algorithm calculation in Python 2.x. For more information, please follow other related articles on the PHP Chinese website!