Storing Passwords Safely in the Database

Jul 18, 2024

Storing Passwords Safely in the Database

Why Safe Password Storage is Necessary

  • Prevents attackers from getting passwords even if the database is compromised

What Not to Do

  • Do not store passwords in plain text
    • Anyone with internal access can see them
    • If compromised, attackers can easily get all passwords

Secure Password Storage Recommendations by OWASP

Use a Modern Hashing Algorithm

  • Hashing: A one-way function; impossible to decrypt back to the original value
  • If an attacker obtains hashed passwords, they cannot use them to access the application
  • Use "slow" functions that use more resources to compute
    • Makes brute force attacks unattractive
  • Do not use: Legacy functions like MD5 and SHA-1 (they are "fast" and less secure)

Salt the Passwords

  • Salt: A unique randomly generated string added to each password during the hashing process
  • Importance of salting:
    • Prevents pre-computation attacks like rainbow tables and database-based lookups
    • Ensures each hash is unique to each password
  • Process of Salting:
    1. Combine the user-provided password with a randomly generated salt
    2. Compute the hash of this combination using an appropriate hashing function
    3. Store the hash and the salt in the database
  • Salt is not a secret and can be safely stored as plain text in the database

Validating Passwords

  • Fetch the user's salt from the database
  • Append the salt to the password provided by the user and hash it
  • Compare the computed hash with the hash stored in the database
  • If they match, the password is valid

Learn More

  • Check out our books and weekly newsletter on system design
  • Subscribe for updates and more information