How to generate SHA256 hash in Python?
SHA-256 (Secure Hash Algorithm 256-bit) is a cryptographic hash function that takes an input (such as a message or file) and produces a fixed-length output of 256 bits, typically represented as a 64-character string. This output, known as the hash, is unique to the input data, meaning that even a minor change in the input will result in a completely different hash.
To generate an SHA-256 hash in Python, you can use the hashlib
library, which comes built into Python and supports several hashing algorithms.
- First, import the
hashlib
module. - Create a SHA-256 hash object using
hashlib.sha256()
. - Update the hash object with the input string (make sure to encode it to bytes).
- Call
.hexdigest()
to get the final hash value as a readable string.
import hashlib
def generate_sha256_hash(input_string: str) -> str:
sha256_hash = hashlib.sha256()
sha256_hash.update(input_string.encode('utf-8'))
return sha256_hash.hexdigest()
# Example usage
input_string = "Hello, world!"
sha256_hash_value = generate_sha256_hash(input_string)
print(f"SHA-256 Hash: {sha256_hash_value}")