You can download this code by clicking the button below.
This code is now available for download.
This function generates a password hash using the PBKDF2HMAC algorithm, supports custom salts, and is used for password storage and verification.
Technology Stack : cryptography (for cryptographic operations)
Code Type : Function
Code Difficulty : Intermediate
import os
from cryptography.hazmat.backends import default_backend
from cryptography.hazmat.primitives import hashes
from cryptography.hazmat.primitives.kdf.pbkdf2 import PBKDF2HMAC
def generate_password_hash(password, salt=None):
if salt is None:
salt = os.urandom(16)
kdf = PBKDF2HMAC(
algorithm=hashes.SHA256(),
length=32,
salt=salt,
iterations=100000,
backend=default_backend()
)
key = kdf.derive(password.encode('utf-8'))
return key, salt