Password Salt is random data added to a password before hashing, ensuring that identical passwords produce different hashes and preventing precomputed attacks like rainbow tables.
# Without salt - identical passwords produce identical hashes
hash("password123") → abc123
hash("password123") → abc123 # Same hash!
# Attackers can use precomputed tables to crack
# With salt - different hashes even for same password
hash("password123" + "randomsalt1") → xyz789
hash("password123" + "randomsalt2") → def456 # Different!
# Python
import os
import hashlib
def hash_password(password):
salt = os.urandom(16) # Generate random salt
hash = hashlib.pbkdf2_hmac('sha256', password.encode(), salt, 100000)
return salt + hash # Store salt with hash
def verify_password(password, stored):
salt = stored[:16] # Extract salt
stored_hash = stored[16:]
new_hash = hashlib.pbkdf2_hmac('sha256', password.encode(), salt, 100000)
return new_hash == stored_hash