Password Hash Generation with PBKDF2HMAC

  • Share this:

Code introduction


This function uses the PBKDF2HMAC algorithm to generate a hash of a password. It accepts a password and an optional salt value. If no salt is provided, it generates a random salt.


Technology Stack : cryptography

Code Type : Cryptography

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

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 salt, key                
              
Tags: