// Demonstrating double hashing (salt + hash) for secure password storage
# Double Hashing Implementation import hashlib import os def hash_password(password): # Step 1: Generate random salt (16 bytes) salt = os.urandom(16) # Step 2: First hash - SHA-256(password + salt) first_hash = hashlib.sha256( password.encode() + salt ).hexdigest() # Step 3: Second hash - PBKDF2 with 100,000 iterations final_hash = hashlib.pbkdf2_hmac( 'sha256', first_hash.encode(), salt, 100000 ) # Store: salt + final_hash in database return salt.hex() + ":" + final_hash.hex()
| username | salt | password_hash |
|---|---|---|
| admin | a7f3b9c2e1d4f6... | 9c4a8d09fbe... |
| john_doe | b8e2c7d1f5a3... | 7d2f3e8b1c9... |
| adish | c9d4e8f2a7b1... | 3a8b2c5d1e7... |
# Login Verification Process def verify_password(username, password): # 1. Retrieve salt and stored hash from database stored_data = db.get_user(username) salt = bytes.fromhex(stored_data['salt']) stored_hash = stored_data['password_hash'] # 2. Apply same double hashing with stored salt first_hash = hashlib.sha256( password.encode() + salt ).hexdigest() computed_hash = hashlib.pbkdf2_hmac( 'sha256', first_hash.encode(), salt, 100000 ).hex() # 3. Compare hashes (constant-time comparison) return hmac.compare_digest(computed_hash, stored_hash)