Random Password Generator with Bcrypt Hashing

  • Share this:

Code introduction


This function generates a random password of a specified length using the bcrypt library and hashes it. It first generates a random salt using bcrypt's internal functions, then generates a random password, and hashes it with the salt. Finally, it returns the hashed password.


Technology Stack : bcrypt library, random password generation, password hashing

Code Type : The type of code

Code Difficulty : Intermediate


                
                    
import bcrypt
import random

def generate_random_password(length):
    """
    Generate a random password of a given length using bcrypt's random library
    """
    # Importing the necessary functions from bcrypt
    from bcrypt import _hash as hash_func
    from bcrypt import _genseed as generate_seed

    # Generating a random salt
    salt = generate_seed(16)

    # Generating a random password
    password = ''.join(random.choice('abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789') for i in range(length))

    # Hashing the password with the generated salt
    hashed_password = hash_func(password.encode('utf-8'), salt)

    return hashed_password