To securely store passwords in a database, follow these best practices:
-
Use a Strong Hashing Algorithm: Hash passwords with a secure algorithm like bcrypt, Argon2, or PBKDF2. Avoid using SHA-1 or MD5 as they are no longer considered secure.
-
Add a Salt: Generate a unique, random salt for each password. This helps prevent rainbow table attacks by making identical passwords produce different hashes.
-
Avoid Encryption: Passwords should be hashed, not encrypted. Hashing is one-way, meaning it can’t be reversed, while encryption is reversible, which could expose passwords if keys are leaked.
-
Set a High Cost Factor: Hashing algorithms like bcrypt and Argon2 allow you to set a "cost" or "work factor," which defines the hashing complexity. Use a high cost factor (e.g., bcrypt cost of 12 or above) to make brute-force attacks slower.
Here’s how you could implement secure password storage using bcrypt in Python:
import bcrypt
# Hashing a password
password = b"your_password_here"
salt = bcrypt.gensalt() # Generate salt
hashed_password = bcrypt.hashpw(password, salt) # Hash with salt
# Verifying a password
is_correct = bcrypt.checkpw(password, hashed_password)
print("Password is correct:", is_correct)