Bcrypt Password Management with Python

  • Share this:

Code introduction


代码含义解释[英文]


Technology Stack : 代码所使用到的包和技术栈[英文]

Code Type : The type of code

Code Difficulty :


                
                    
import bcrypt
import os

def generate_salt():
    # Generate a random salt for bcrypt hashing
    return bcrypt.gensalt()

def hash_password(password):
    # Hash a password using bcrypt
    salt = generate_salt()
    hashed = bcrypt.hashpw(password.encode('utf-8'), salt)
    return hashed

def check_password(password, hashed):
    # Check if a password matches the hashed password using bcrypt
    return bcrypt.checkpw(password.encode('utf-8'), hashed)

def reset_password_file(filename, new_password):
    # Reset the password stored in a file using bcrypt
    if os.path.exists(filename):
        os.remove(filename)
    with open(filename, 'wb') as file:
        hashed = hash_password(new_password)
        file.write(hashed)

def verify_password_file(filename, password):
    # Verify the password stored in a file using bcrypt
    with open(filename, 'rb') as file:
        hashed = file.read()
        return check_password(password, hashed)