PYTHON

Securely Hash Passwords with Bcrypt in Python

Implement robust password security in Python applications by using the `bcrypt` library to hash and verify user passwords securely.

import bcrypt

def hash_password(password):
    """
    Hashes a plain-text password using bcrypt.
    Returns the hashed password as a byte string.
    """
    # Generate a salt and hash the password
    # bcrypt.gensalt() generates a salt with a default cost (12 rounds)
    hashed_password = bcrypt.hashpw(password.encode('utf-8'), bcrypt.gensalt())
    return hashed_password

def verify_password(plain_password, hashed_password):
    """
    Verifies a plain-text password against a hashed password.
    Returns True if they match, False otherwise.
    """
    # bcrypt.checkpw automatically extracts the salt from the hashed_password
    return bcrypt.checkpw(plain_password.encode('utf-8'), hashed_password)

# Example Usage:
user_password = "mySecretPassword123"

# Hash the password
hashed_pwd = hash_password(user_password)
# print(f"Hashed password: {hashed_pwd}")

# Verify a correct password
is_valid = verify_password(user_password, hashed_pwd)
# print(f"Verification (correct password): {is_valid}") # Expected: True

# Verify an incorrect password
is_invalid = verify_password("wrongPassword", hashed_pwd)
# print(f"Verification (wrong password): {is_invalid}") # Expected: False
How it works: This Python snippet demonstrates how to securely hash and verify user passwords using the `bcrypt` library. `bcrypt` is a strong, adaptive hashing algorithm designed to be resistant to brute-force attacks. The `hash_password` function generates a unique salt and hashes the provided plain-text password. The `verify_password` function then compares a plain-text password against a previously stored hash, correctly handling the salt that is embedded within the hash itself.

Need help integrating this into your project?

Our team of expert developers can help you build your custom application from scratch.

Hire DigitalCodeLabs