How to generate SHA1 hash in Python?
SHA-1 (Secure Hash Algorithm 1) is a cryptographic hash function that takes an input (such as a message or file) and produces a fixed-length string of characters, typically a 160-bit value. The output, known as the hash, is unique to the input data, meaning even a small change in the input will result in a completely different hash.
To generate an SHA-1 hash in Python, you can use the hashlib
library, which provides various hashing algorithms. SHA-1 is one of them, and it turns any input (like a string) into a fixed-length sequence of characters, known as a hash.
- First, you need to import the
hashlib
module. - Then, create a SHA-1 hash object using
hashlib.sha1()
. - You update the hash object with the input string, ensuring the string is encoded (since SHA-1 requires bytes, not text).
- Finally, you call
.hexdigest()
to get the hash as a readable string.
import hashlib
def generate_sha1_hash(input_string: str) -> str:
sha1_hash = hashlib.sha1()
sha1_hash.update(input_string.encode('utf-8'))
return sha1_hash.hexdigest()
# Example usage
input_string = "Hello, world!"
sha1_hash_value = generate_sha1_hash(input_string)
print(f"SHA-1 Hash: {sha1_hash_value}")