Skip to content
Tutorials Center
My learning

Topics

Lesson 17 of 39 ยท Authentication Basics

Password Hashing and Login

Store passwords safely: why hashing beats encryption, salts, slow hashes (scrypt, bcrypt, Argon2), constant-time comparison, login endpoints and password rules.

If your API has user accounts, you will store something derived from each user's password. How you do it decides what happens on the day your database leaks (and sooner or later, someone's database does leak). Done right, attackers get data that costs them years of computing per password. Done wrong, they get every password in one second, and because people reuse passwords, they get your users' email and bank accounts too.

The rules fit on one line: never store a password, store a salted, slow, one-way hash of it, and compare in constant time. This lesson explains each word.

Never store plaintext, and do not encrypt

  • Plaintext: anyone with the database (a leaked backup, a curious admin, an SQL injection) reads every password.
  • Encryption is reversible by design. If the key is stolen along with the data, every password is exposed. You never need to read a password back; you only need to check whether a login attempt matches.
  • Hashing is one-way: you can compute hash(password) but cannot recover the password from the hash. Login works by hashing the attempt and comparing.

Why plain SHA-256 is not enough

General-purpose hashes (MD5, SHA-1, SHA-256) are designed to be fast: billions per second on a graphics card. An attacker with a stolen table of sha256(password) values simply tries every common password, every dictionary word and every leaked password list, and cracks most accounts within hours. Two more problems:

  • Identical passwords produce identical hashes, so cracking one reveals every user who chose it (and attackers use pre-computed rainbow tables).
  • Speed is the enemy: you want hashing to be deliberately slow and memory hungry.

Salt and slow hashing

A salt is a random value, unique per user, that you mix into the hash. It is stored next to the hash (it is not secret). Salts make identical passwords hash differently and make pre-computed tables useless.

A password hashing function adds a tunable cost so each guess takes, say, 50-100 ms and plenty of memory:

Algorithm Notes
Argon2id Winner of the Password Hashing Competition; the OWASP first choice
scrypt Memory-hard, built into Node's crypto module
bcrypt Older, widely supported, limits passwords to 72 bytes
PBKDF2 Standardised (FIPS), CPU-hard only; needs a very high iteration count

Use your language's maintained library and the recommended parameters, and store the parameters with the hash so you can raise them later. Node.js has crypto.scrypt without extra packages, which is what the examples use.

flowchart LR
    P["Password"] --> H["scrypt(password, salt, cost)"]
    S["Random salt (16+ bytes)"] --> H
    H --> D["Stored: algorithm$params$salt$hash"]
    L["Login attempt"] --> V["Hash with same salt + params"] --> C{"Equal? constant-time"}
    D --> V

Registration stores the hash and salt; login recomputes and compares.

Hash and verify with scrypt

The functions below produce a self-describing string scrypt$N$r$p$salt$hash. verify re-reads the parameters from the string, so you can change the defaults for new users later and old hashes keep working. Comparison uses crypto.timingSafeEqual so the time taken does not leak how many leading bytes matched.

Node.js Hash and verify a password with scrypt

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

The last lines prove the point of the salt: the same password gives two different stored strings, yet both verify.

Constant-time comparison

With a normal ===, the comparison stops at the first different byte, so a measurable timing difference reveals how much of a secret an attacker guessed. crypto.timingSafeEqual always examines every byte. It requires buffers of equal length, which is why the hash is compared as fixed-length buffers. Use it for any secret comparison (hashes, API keys, tokens, signatures).

A registration and login API

Pulling it together, here is the account part of an API: POST /register and POST /login. Notes on the design:

  • Passwords have a minimum length (12 is a good modern minimum; length matters more than symbol rules) and a maximum (for example 128 characters) to stop someone sending a 10 MB "password" to burn your CPU.
  • Login errors are identical whether the email is unknown or the password is wrong, and even for unknown emails we still run a hash, so response time does not reveal which emails exist.
  • Responses never contain the hash.
  • A real system would also rate-limit login attempts and use MFA; see the security chapter.
Node.js Register and log in

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Both failed logins return the same 401 and the same message. An attacker cannot tell a real account from a missing one.

Password policy in 2026

Current guidance (NIST SP 800-63B, OWASP) is simpler than the old "one uppercase, one symbol" rules:

  • Minimum length (at least 8, preferably 12 or more); allow long passphrases and all Unicode and spaces.
  • Do not force periodic changes; require a change only after a suspected breach.
  • Check new passwords against lists of breached or very common passwords.
  • Encourage password managers (allow paste).
  • Offer MFA or passkeys.
  • Provide a safe reset flow via a single-use, short-lived token sent to the verified email, and never reveal whether an email exists.

Upgrading hashes

Hash costs go up as hardware gets faster. Because the stored string carries its parameters, you can rehash on login: after verifying a password successfully, if the stored cost is lower than your current setting, hash the plaintext again with the new parameters and update the record. Users migrate gradually without ever being asked to reset anything.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Why is hashing preferred over encryption for stored passwords?

    Login only needs a comparison. A one-way hash removes the key-theft risk of reversible encryption.
  2. 2. What is the purpose of a salt?

    A unique random salt per user forces attackers to attack each hash separately.
  3. 3. Why is plain SHA-256 a poor choice for passwords?

    Password hashes must be deliberately slow and memory hard (Argon2id, scrypt, bcrypt).
  4. 4. Why does login return the same message for an unknown email and a wrong password?

    Distinguishable responses enable account enumeration.
  5. 5. What does crypto.timingSafeEqual protect against?

    Normal comparison returns early at the first mismatch; constant-time comparison does not leak progress.

Summary

  • Never store plaintext or reversibly encrypted passwords; store a salted, slow, one-way hash (Argon2id, scrypt, bcrypt).
  • A random per-user salt and tunable cost parameters belong in the stored string, so you can upgrade later.
  • Compare secrets with crypto.timingSafeEqual, and return identical errors for unknown emails and wrong passwords.
  • Limit password length from above to prevent denial of service, require a sensible minimum and block breached passwords.
  • Add rate limiting, MFA and a safe reset flow around login.

Next: Basic Auth and API Keys