Passwords must be stored safely to prevent unwanted access to user accounts. To protect passwords in your database, adhere to these best practices:
1. Hashing
Use a password hashing algorithm: Don't store raw passwords; instead, store hashed versions.
Choose a suitable algorithm:
- Recommended: Bcrypt, PBKDF2, or Argon2.
- Acceptable: If Argon2 is not practical, Scrypt is acceptable.
- Avoid: MD5, SHA-1, and SHA-256.
2. Hashing Configuration
Salt:
- For every password, use a different salt that is generated at random.
- Keep the hashed password and the salt together.
Iterations/Work Factor:
- To slow down the hashing process and increase its resistance to brute-force attacks, increase the number of iterations.
- Strike a balance between performance and security.
Key Size:
- Use a key size that is appropriate for the selected algorithm, such as 128 bits or greater.
3. Storage
- Store the hashed password and salt in a single, indexed column.
- Use a secure database with access controls, backups, and regular security updates.
4. Verification
When verifying a password:
- Retrieve the stored hashed password and salt.
- Hash the provided password using the same algorithm, salt, and configuration.
- Compare the resulting hash with the stored hash.
5. Additional Security Measures
Implement password policies:
- Password length and complexity requirements.
- Expiration and rotation policies.
Use additional security features:
- Two-Factor Authentication (2FA) or Multi-Factor Authentication (MFA).
- Rate limiting and IP blocking for brute-force protection.