← Back to Python

All Topics

Advertisement

Learn/Python/Security

Password Hashing - bcrypt, Argon2, Passlib

Topic: Password Hashing

Advertisement

Introduction

Password hashing protects user credentials by converting plain text passwords into irreversible hashes. This tutorial covers bcrypt, Argon2, and Passlib for secure password storage.

bcrypt Implementation

import bcrypt

def hash_password(password: str) -> str:
    """Hash a password using bcrypt."""
    salt = bcrypt.gensalt(rounds=12)
    hashed = bcrypt.hashpw(password.encode('utf-8'), salt)
    return hashed.decode('utf-8')

def verify_password(password: str, hashed_password: str) -> bool:
    """Verify a password against a bcrypt hash."""
    return bcrypt.checkpw(
        password.encode('utf-8'),
        hashed_password.encode('utf-8')
    )

# Example usage
password = "securePassword123"
hashed = hash_password(password)
print(f"Hash: {hashed}")

is_valid = verify_password(password, hashed)
print(f"Valid: {is_valid}")

# False case
is_valid = verify_password("wrongpassword", hashed)
print(f"Valid: {is_valid}")

Argon2 Implementation

from argon2 import PasswordHasher
from argon2.exceptions import VerifyMismatchError

ph = PasswordHasher(
    time_cost=3,
    memory_cost=64 * 1024,
    parallelism=4,
    hash_len=32,
    type=argon2.Type.ID
)

def hash_password_argon2(password: str) -> str:
    """Hash a password using Argon2."""
    return ph.hash(password)

def verify_password_argon2(password: str, hashed: str) -> bool:
    """Verify password against Argon2 hash."""
    try:
        ph.verify(hashed, password)
        return True
    except VerifyMismatchError:
        return False

# Example usage
hashed = hash_password_argon2("mySecurePassword")
print(f"Argon2 hash: {hashed}")

valid = verify_password_argon2("mySecurePassword", hashed)
print(f"Valid: {valid}")

Passlib Implementation

from passlib.context import CryptContext

# Configure passlib with multiple schemes
pwd_context = CryptContext(
    schemes=["bcrypt", "argon2"],
    default="bcrypt",
    bcrypt__rounds=12,
    argon2__memory_cost=65536,
    argon2__time_cost=3,
    argon2__parallelism=4
)

def hash_password_passlib(password: str) -> str:
    """Hash password using Passlib."""
    return pwd_context.hash(password)

def verify_password_passlib(password: str, hashed: str) -> bool:
    """Verify password using Passlib."""
    return pwd_context.verify(password, hashed)

# Check if hash needs updating
def needs_rehash(hashed: str) -> bool:
    return pwd_context.needs_update(hashed)

# Example
hashed = hash_password_passlib("password123")
print(f"Hash: {hashed}")
print(f"Valid: {verify_password_passlib('password123', hashed)}")

Integration with User Models

# user.py
from sqlalchemy import Column, Integer, String
from app import db

class User(db.Model):
    __tablename__ = 'users'
    
    id = Column(Integer, primary_key=True)
    username = Column(String(100), unique=True, nullable=False)
    email = Column(String(100), unique=True, nullable=False)
    password_hash = Column(String(256), nullable=False)
    
    def set_password(self, password: str):
        self.password_hash = hash_password_passlib(password)
    
    def check_password(self, password: str) -> bool:
        return verify_password_passlib(password, self.password_hash)
    
    def needs_password_update(self) -> bool:
        return needs_rehash(self.password_hash)

# Creating user
user = User(username="john", email="john@example.com")
user.set_password("securePassword123")
db.session.add(user)
db.session.commit()

# Verifying login
user = User.query.filter_by(username="john").first()
if user and user.check_password("securePassword123"):
    print("Login successful")

Practice Problems

  1. Implement password strength validation
  2. Add password reset functionality with secure tokens
  3. Create rate limiting for login attempts
  4. Implement two-factor authentication with TOTP
  5. Add multi-layer password hashing with salt

Advertisement

Advertisement

Need More Practice?

Get personalized Python help from ChatWhole's AI-powered platform.

Get Expert Help →