File size: 1,401 Bytes
3d6f757 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 | # crypto_utils.py
"""
Cryptography utilities for password hashing and username encryption
"""
import bcrypt
import hashlib
def hash_password(password: str) -> str:
"""
Hash password with bcrypt
Args:
password: Plain text password
Returns:
Hashed password string
"""
salt = bcrypt.gensalt(rounds=10)
hashed = bcrypt.hashpw(password.encode('utf-8'), salt)
return hashed.decode('utf-8')
def verify_password(password: str, hashed: str) -> bool:
"""
Verify password against hash
Args:
password: Plain text password to verify
hashed: Stored password hash
Returns:
True if password matches, False otherwise
"""
try:
return bcrypt.checkpw(password.encode('utf-8'), hashed.encode('utf-8'))
except Exception as e:
print(f"Password verification error: {e}")
return False
def hash_username_for_storage(username: str) -> str:
"""
Create consistent SHA-256 hash of username for database storage
Args:
username: Plain text username
Returns:
SHA-256 hash hex string
"""
return hashlib.sha256(username.lower().encode('utf-8')).hexdigest()
def generate_encryption_key() -> str:
"""
Generate random encryption key for username encryption
Returns:
Random 32-byte hex string
"""
import secrets
return secrets.token_hex(32) |