Password Management Functions in Python

  • Share this:

Code introduction


This code defines a password management system including functions for hashing a password, verifying a password, and changing a password.


Technology Stack : bcrypt

Code Type : Password management

Code Difficulty : Intermediate


                
                    
import bcrypt

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

def verify_password(password, hashed):
    # Verify a password against a stored hash
    return bcrypt.checkpw(password.encode('utf-8'), hashed)

def change_password(old_password, new_password, hashed):
    # Change a password by verifying the old one and hashing the new one
    if verify_password(old_password, hashed):
        new_salt = bcrypt.gensalt()
        new_hashed = bcrypt.hashpw(new_password.encode('utf-8'), new_salt)
        return new_hashed
    return None                
              
Tags: