📅  最后修改于: 2023-12-03 14:47:25.925000             🧑  作者: Mango
SHA-256 is a cryptographic hash function used for generating hashed values of data. This function generates a unique hash value of 256-bits (32 bytes) from any data provided to it. In this article, we'll discuss how to use SHA-256 in Python.
To use SHA-256 in Python, we'll need to import the hashlib module. This module contains various hash functions including SHA-256.
import hashlib
To compute the SHA-256 hash of any data in Python, we create an instance of the hashlib.sha256() class and pass the data to be hashed to its update() method. Finally, we call the digest() method to get the hashed value.
data = b'Hello, World!'
hash_object = hashlib.sha256(data)
hashed_value = hash_object.digest()
print(hashed_value)
The output will be:
b'\xeb\x5e\x23\x72\x7c\x01\x6d\x4d\x85\x01\x19\x79\x1c\x2c\xd7\x1f\x16\x9a\x4f\x76\xe9\x59\x21\x38\xd7\x3f\x17\xe0\x5b\x08\x17'
SHA-256 is commonly used to ensure data integrity. For example, suppose we have a file and its hash value. If we apply SHA-256 to the file and the resulting hash value matches the original hash value, we can infer that the file has not been tampered with.
# Compute SHA-256 hash of data
original_data = b'Hello, World!'
hash_object = hashlib.sha256(original_data)
original_hashed_value = hash_object.digest()
# Tamper with data
tampered_data = b'Hello, Mars!'
# Compute SHA-256 hash of tampered data
hash_object = hashlib.sha256(tampered_data)
tampered_hashed_value = hash_object.digest()
# Compare hash values
if original_hashed_value == tampered_hashed_value:
print("Data is intact")
else:
print("Data has been tampered with")
The output in this case will be:
Data has been tampered with
In this article, we discussed how to compute SHA-256 hash values of data in Python. We also showed how SHA-256 can be used to ensure data integrity. SHA-256 is just one of many hash functions available in Python's hashlib module.