Blog | G5 Cyber Security

Password Storage: Best Practices

TL;DR

Never store passwords directly in your database! Use strong hashing algorithms (like bcrypt or Argon2) with salts to protect them. This guide explains why and how.

Why You Shouldn’t Store Passwords Directly

  1. Security Risks: If your database is compromised, attackers will have immediate access to all user passwords if they’re stored in plain text or even weakly encrypted.
  2. Legal & Reputational Damage: Data breaches involving passwords can lead to significant fines and loss of customer trust.
  3. It’s Easily Preventable: Modern techniques make storing passwords securely relatively straightforward.

How to Store Passwords Securely

The correct approach involves hashing, salting and potentially key stretching.

1. Hashing

Hashing is a one-way function: you can turn a password into an unreadable string of characters (the hash), but you can’t easily get the original password back from the hash. Good hashing algorithms are designed to be slow, making brute-force attacks harder.

2. Salting

A salt is a random string added to each password before hashing. This prevents attackers from using pre-computed tables of common passwords and their hashes (rainbow tables). Each user needs a unique salt.

3. Key Stretching

Key stretching involves repeatedly applying the hashing function to increase the computational effort required to crack the password, even with a salt. bcrypt and Argon2 include key stretching by default.

Practical Implementation Steps

  1. Choose an Algorithm: Start with bcrypt or Argon2. Argon2 is generally preferred for new applications.
  2. Generate Salts: Create a unique, random salt for each user when they register. Store the salt alongside the hash in your database (not the password itself!).
  3. Hash the Password: Combine the salt and password before hashing using your chosen algorithm.
  4. Store the Hash & Salt: Save both the generated hash and the original salt in your database.
  5. Password Verification: When a user logs in:
    • Retrieve the salt for that user from the database.
    • Hash the entered password using the retrieved salt.
    • Compare the resulting hash with the stored hash. If they match, the password is correct.

Example (Python with bcrypt)

This example uses the bcrypt library in Python.

import bcrypt

password = "mysecretpassword"
salt = bcrypt.gensalt()
hashed_password = bcrypt.hashpw(password.encode('utf-8'), salt)

print("Hashed Password:", hashed_password.decode('utf-8'))
print("Salt:", salt.decode('utf-8'))

# Verification example
entered_password = "mysecretpassword"
if bcrypt.checkpw(entered_password.encode('utf-8'), hashed_password):
    print("Password matches!")
else:
    print("Password does not match.")

Resources

Exit mobile version