Skip to content

Web security basics · Part 5 of 10

Storing passwords: salted hashing with bcrypt or Argon2

Never store passwords in plain text or with a fast hash. Use a slow, salted password hash such as bcrypt or Argon2 so stolen databases are hard to crack.

· 2 min read

securitypasswords

A database leak happens to careful teams too. What matters is what the attacker finds: plain passwords are a disaster, properly hashed ones are a long and expensive problem for the attacker.

What not to do

  • Plain text or reversible encryption: anyone with the data has every password.
  • A fast hash such as MD5 or SHA-256 on its own: modern hardware computes billions per second, so weak passwords fall within minutes.
  • A shared secret for all users: one leak breaks everything.

What a password hash is

A password hash is a one-way function designed to be slow and to need a lot of memory, so each guess costs the attacker real resources. Good choices are Argon2id, scrypt and bcrypt. Follow current guidance, such as the OWASP Password Storage Cheat Sheet, for parameters.

Salt

A salt is a random value stored next to each hash and mixed into the computation. It guarantees that two users with the same password have different hashes, and it makes precomputed tables, called rainbow tables, useless. Good libraries create and store the salt for you inside the hash string.

Work factor

The work factor (cost) sets how slow each hash is. Choose a value that takes a noticeable fraction of a second on your servers, and raise it over time as hardware improves.

Ruby
require "bcrypt"

hash = BCrypt::Password.create("correct horse battery staple", cost: 12)
puts hash.to_s.start_with?("$2a$12$")        # the cost and salt live inside the string
puts hash == "correct horse battery staple"  # true
puts hash == "wrong guess"                   # false

Around the hash

  1. Enforce a minimum length, and allow long passphrases. Length matters more than odd character rules.
  2. Rate-limit and monitor login attempts, and offer multi-factor authentication or passkeys.
  3. Compare with the library function, not with == on raw strings.
  4. Send password reset links that are random, single-use and short-lived. Never email a password.
  5. Never log passwords, including in error messages.

Takeaway

Use a maintained library with Argon2id or bcrypt, let it handle the salt, tune the cost and protect the login endpoint. Better still, offer passkeys so there is no password to leak.

A knowledge article, drafted with AI assistance and checked with automated tests. It is general background, not a description of my own experience or of any client's work.

Comments

Leave a comment

No account or email needed. Comments appear after review. A one-way hash of your IP address is kept for 30 days to fight spam, then erased.