Random Password Generator with Bcrypt Hashing

  • Share this:

Code introduction


This function generates a random password of a specified length and hashes it using the bcrypt algorithm, returning the hashed password.


Technology Stack : Passlib (CryptContext)

Code Type : Password Hashing

Code Difficulty : Intermediate


                
                    
from passlib.context import CryptContext
from random import choice

def generate_secure_password(length=12):
    # Initialize the CryptContext object with the default password hashing algorithm
    pwd_context = CryptContext(schemes=["bcrypt"], deprecated="auto")
    
    # Define the characters that can be used in the password
    chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789!@#$%^&*()_+"
    
    # Generate a random password of specified length
    random_password = ''.join(choice(chars) for i in range(length))
    
    # Hash the generated password using the bcrypt algorithm
    hashed_password = pwd_context.hash(random_password)
    
    return hashed_password