Proper Use of Hash Functions in Password Systems
Proper Use of Hash Functions in Password Systems
When using hash functions for passwords, never hash passwords directly with general-purpose functions. The speed that makes SHA-256 excellent for blockchain applications makes it terrible for password storage. Always use specialized password hashing functions like bcrypt, scrypt, or Argon2 that incorporate work factors to slow computation. These functions internally use cryptographic hash functions but add crucial protections.
# INCORRECT: Direct hashing with SHA-256
import hashlib
def insecure_password_hash(password):
# DON'T DO THIS - vulnerable to rapid brute force
return hashlib.sha256(password.encode()).hexdigest()
# CORRECT: Using a password-specific hashing function
import bcrypt
def secure_password_hash(password):
# bcrypt adds salt and work factor automatically
return bcrypt.hashpw(password.encode('utf-8'), bcrypt.gensalt())
# Verification remains simple
def verify_password(password, hashed):
return bcrypt.checkpw(password.encode('utf-8'), hashed)
Understanding hash functions helps recognize insecure implementations. Seeing MD5 or plain SHA functions used for passwords should trigger immediate security concerns. Even SHA-256 with static salts provides inadequate protection against modern attacks. Proper password hashing requires both appropriate algorithms and correct implementation, topics we'll explore in detail in subsequent chapters.