Bcrypt Password Hashing and Verification Functions

  • Share this:

Code introduction


This set of functions provides methods to create password hashes, verify passwords, and generate salts using the bcrypt library.


Technology Stack : bcrypt

Code Type : Function set

Code Difficulty : Intermediate


                
                    
import bcrypt

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

def check_password(hashed_password, user_password):
    # Check a password against a stored hash.
    return bcrypt.checkpw(user_password.encode('utf-8'), hashed_password)

def generate_salt():
    # Generate a new salt for a password hash.
    return bcrypt.gensalt()

def verify_password(hashed_password, user_password):
    # Verify a password using a hashed version.
    return hashed_password == bcrypt.hashpw(user_password.encode('utf-8'), hashed_password)                
              
Tags: