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