PBKDF2HMAC Password Hash Generator with Optional Salt

  • Share this:

Code introduction


This function generates a password hash using the PBKDF2HMAC algorithm. It accepts a password and an optional salt value. If no salt is provided, the function generates a random 16-byte salt.


Technology Stack : cryptography library, hashes module, PBKDF2HMAC, os library, Scrypt

Code Type : Password hash generation function

Code Difficulty : Intermediate


                
                    
import os
from cryptography.hazmat.primitives import hashes
from cryptography.hazmat.backends import default_backend
from cryptography.hazmat.primitives.kdf.pbkdf2 import PBKDF2HMAC
from cryptography.hazmat.primitives.kdf.scrypt import Scrypt

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