How do you install the hashlib module in Python?

The hashlib module is included in the Python standard library, so there is no need to install it separately. You can import and use it directly in your Python scripts. Here is a simple example:

import hashlib

# 计算字符串的MD5哈希值

string = "Hello, World!"

md5_hash = hashlib.md5(string.encode()).hexdigest()

print("MD5 Hash:", md5_hash)

# 计算文件的SHA256哈希值

filename = "example.txt"

with open(filename, "rb") as file:

    file_hash = hashlib.sha256(file.read()).hexdigest()

print("SHA256 Hash:", file_hash)

In the example above, we first imported the hashlib module. Then, we used the md5() function to calculate the MD5 hash value of the string “Hello, World!” and converted it to hexadecimal format using the hexdigest() function for display. Next, we used the sha256() function to calculate the SHA256 hash value of the file “example.txt”. We opened the file using the open() function in binary mode, read the file contents using the read() function, and then converted the hash value to hexadecimal format using the hexdigest() function. Finally, we printed the calculated hash value. Make sure that a file named “example.txt” exists in the same directory to run the example code.

广告
Closing in 10 seconds
bannerAds