How to use the hashlib module in Python?
The hashlib module in Python is used for hash algorithms, allowing for the generation of digest information commonly used in scenarios such as password storage and digital signatures.
Operations with the hashlib module should be done according to the following steps:
- Import the hashlib module.
import hashlib
- Create a hash object:
hash_object = hashlib.new('算法名称')
The algorithm name can be the name of hashing algorithms like md5, sha1, sha256, etc.
- Update the digest information of the hash object.
hash_object.update(b'待计算的字符串')
In this case, ‘b’待计算的字符串’ is a byte string. If it is a regular string, you can use the encode() method to convert it into a byte string.
- Retrieve summary information:
digest = hash_object.digest()
The abstract information is binary data.
- Obtain the hexadecimal representation of the summary information.
hexdigest = hash_object.hexdigest()
The hexadecimal representation of the summary information is a string.
Here is the complete example code:
import hashlib
hash_object = hashlib.new('md5')
hash_object.update(b'Hello, World!')
digest = hash_object.digest()
hexdigest = hash_object.hexdigest()
print(digest)
print(hexdigest)
The code above uses the MD5 algorithm to calculate the digest of the string ‘Hello, World!’, and prints out the digest in binary and hexadecimal forms.
Note: In practical use, it is not recommended to use the MD5 algorithm for password storage as it has been proven to have security issues. It is recommended to use a more secure algorithm such as SHA256.