Databases in practice

Store password hashes, not passwords

Use a password-hashing function and compare submitted passwords without ever storing the original value.

8 minute lesson

~~~

Never store a password as plain text or reversible encrypted text.

Do not use a fast general-purpose hash such as plain SHA-256 either. Attackers can test enormous numbers of guesses quickly after stealing the database. Password hashing is deliberately slow and configurable.

Use a maintained password-hashing library. Argon2id is the preferred modern choice; scrypt is a suitable fallback, while bcrypt is mainly appropriate for legacy systems. Follow the library and current security guidance when selecting memory and time costs rather than inventing your own algorithm.

At registration, hash the password and store only the encoded result:

CREATE TABLE users (
  id BIGINT PRIMARY KEY,
  email TEXT NOT NULL UNIQUE,
  password_hash TEXT NOT NULL
);

A good library generates a unique random salt and includes the salt, algorithm, and cost parameters in the encoded hash. You usually do not need a separate salt column.

At sign-in, load password_hash and call the library’s verification function with the submitted password. Do not hash the submitted value yourself and compare two strings: the library understands the encoded parameters and performs the comparison safely.

Work factors change as hardware improves. Many libraries can tell you that an old hash needs upgrading. After a successful login, rehash the password with the current policy and replace the stored hash.

Hashing limits the damage of a database leak; it does not make authentication complete. Add rate limiting, secure password reset flows, session protection, and multi-factor authentication where appropriate. Password-reset tokens are secrets too: store a hash of the token, give it a short expiry, and make it single-use.

Never log passwords, even during debugging.

Your action: use your language’s maintained Argon2id library to hash one test password. Verify that the correct password succeeds, a wrong password fails, and two hashes of the same password differ because they use different salts.

Lesson completed

Take this course offline

Get every free book and course as PDF and EPUB files.

Get the download library →