This code example demonstrates the following advanced functionalities of the hashlib library:
os.urandom()
for password hashing.import hashlib
import os
def generate_salt():
# Generate a random salt
return os.urandom(16)
def hash_password(password, salt):
# Hash the password with salt using SHA-256
hashed_password = hashlib.sha256(password + salt).hexdigest()
return hashed_password
def verify_password(password, hashed_password, salt):
# Verify if the provided password matches the hashed password
return hashed_password == hash_password(password, salt)
def generate_digest(data):
# Generate a message digest using SHA-256
digest = hashlib.sha256(data.encode()).hexdigest()
return digest
# Example usage
password = b'my_password'
salt = generate_salt()
hashed_password = hash_password(password, salt)
print("Salt:", salt)
print("Hashed Password:", hashed_password)
# Verify the password
if verify_password(password, hashed_password, salt):
print("Password Verified!")
else:
print("Password Verification Failed!")
# Generate message digest
data = "Hello, World!"
digest = generate_digest(data)
print("Message Digest:", digest)
generate_salt()
function: This function generates a random salt of 16 bytes using os.urandom()
.hash_password()
function: It takes a password and salt as input, combines them, and then hashes the result using the SHA-256 algorithm. The resulting hash is returned as a hexadecimal string.verify_password()
function: This function verifies whether a provided password matches the hashed password by recalculating the hash using the same salt and comparing it with the stored hash.generate_digest()
function: It generates a message digest (hash) of input data using the SHA-256 algorithm. The input data is first converted to bytes before hashing.Salt: b’\x8d\xfeD\xe8\x80\x08\xfb8x\xd5\xa4\x88j\xe7\xbb’ Hashed Password: 62d6fc99b43266b9e9241b42d8d4c3365256fd6ff4a58f2ed8b06734ef3b7951 Password Verified! Message Digest: 681427575b22d95a0b9dbbf18b2dcdc7fd2ed95c2ab22e1e8c0b5a58b56e8d47
In this example:
b'\x8d\xfeD\xe8\x80\x08\xfb8x\xd5\xa4\x88j\xe7\xbb'
.b'my_password'
is hashed using the SHA-256 algorithm with the salt, resulting in the hashed password 62d6fc99b43266b9e9241b42d8d4c3365256fd6ff4a58f2ed8b06734ef3b7951
."Hello, World!"
is 681427575b22d95a0b9dbbf18b2dcdc7fd2ed95c2ab22e1e8c0b5a58b56e8d47
.