Password Hashing with bcrypt in Passlib

  • Share this:

Code introduction


This function uses the CryptContext class from the Passlib library to create a password hashing context and hashes the given password using the bcrypt algorithm. If a salt is provided, it will use that salt for the hashing. The function returns the hashed password.


Technology Stack : Passlib

Code Type : Function

Code Difficulty : Intermediate


                
                    
from passlib.context import CryptContext
from passlib.pwd import hash_password

def generate_secure_password(password, salt=None):
    # Initialize a new password hashing context
    ctx = CryptContext(schemes=["bcrypt"], deprecated="auto")
    
    # Hash the password with a new salt
    hashed_password = hash_password(password, salt=salt)
    
    return hashed_password

# JSON Explanation                
              
Tags: