TL;DR
Don’t store passwords directly in your database! Use a strong hashing algorithm (like bcrypt or Argon2) with salts to protect them. This guide shows you how.
1. Why Not Just Store Passwords?
Storing passwords as plain text is incredibly dangerous. If your database gets hacked, all your users’ passwords are compromised. Hashing turns passwords into a one-way string of characters, making it much harder for attackers to get the original password even if they have access to the hash.
2. What is Hashing and Salting?
- Hashing: A mathematical process that converts data (like a password) into a fixed-size string of characters. It’s one-way – you can’t easily get back the original password from the hash.
- Salting: Adding a random, unique string to each password *before* hashing it. This makes ‘rainbow table’ attacks (precomputed tables of hashes) much less effective. Each password has a different salt, so even if two users have the same password, their hashes will be different.
3. Choosing a Hashing Algorithm
Some hashing algorithms are better than others. Here’s what to consider:
- bcrypt: A widely used and well-tested algorithm. It automatically includes salting.
- Argon2: More modern and generally considered more secure than bcrypt, especially against GPU cracking attacks. Requires more computational resources.
For most applications, bcrypt is a good starting point. Argon2 is preferable if you have the resources to implement it correctly.
4. Implementing Password Hashing (Example using Python and bcrypt)
- Install the bcrypt library:
- Hashing a password when creating an account:
- Verifying a password when logging in:
- Storing the hash in your database: Store the
hashed_passwordstring in your database. Do *not* store the original password!
pip install bcrypt
import bcrypt
def hash_password(password):
salt = bcrypt.gensalt()
hashed_password = bcrypt.hashpw(password.encode('utf-8'), salt)
return hashed_password.decode('utf-8')
# Example usage:
new_password = "MySecretPassword"
hashed_password = hash_password(new_password)
print(f"Hashed password: {hashed_password}")
def verify_password(password, hashed_password):
return bcrypt.checkpw(password.encode('utf-8'), hashed_password.encode('utf-8'))
# Example usage:
user_entered_password = "MySecretPassword"
is_valid = verify_password(user_entered_password, hashed_password)
print(f"Password is valid: {is_valid}")
5. Important Security Considerations
- Never store passwords in plain text. Seriously, never.
- Use a strong hashing algorithm with salting. bcrypt or Argon2 are good choices.
- Keep your libraries up to date. This ensures you have the latest security fixes.
- Rate limiting: Implement rate limiting on login attempts to prevent brute-force attacks.
- Password complexity requirements: Encourage users to choose strong, unique passwords (length, mixed case, symbols).

