Password Hashing and Verification Functions

  • Share this:

Code introduction


This code defines four functions for password hashing, verification, salt generation, and password verification. The `hash_password` function is used to generate a hash of a password, `check_password` is used to verify the user's input password, `generate_salt` generates a new salt, and `verify_password` verifies the password.


Technology Stack : bcrypt

Code Type : The type of code

Code Difficulty : Advanced


                
                    
import bcrypt

def hash_password(password):
    # Hash a password for storing. Default salt rounds is 12.
    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.
    return bcrypt.gensalt()

def verify_password(hashed_password, user_password):
    # Verify a password against a stored hash and return a boolean.
    return bcrypt.verify(user_password.encode('utf-8'), hashed_password)                
              
Tags: