Skip to content
Tutorials Center
My learning

Topics

Lesson 98 of 147 ยท Security

Password Hashing

Learn to store passwords safely in PHP with password_hash, password_verify and password_needs_rehash, bcrypt vs Argon2id, and why md5 and sha1 are never enough.

Sooner or later, databases leak: through an SQL injection, a stolen backup, a misconfigured server or an employee's laptop. When that happens, the question is what the attacker finds in the password column. If it's plain text, every account is compromised at once, and because people reuse passwords, so are their email and bank accounts. If it's a proper password hash, the attacker has to guess each password one by one, slowly enough that strong passwords stay safe.

PHP makes the right thing easy. Three functions, password_hash(), password_verify() and password_needs_rehash(), handle salts, algorithms and upgrades for you. This lesson explains what they do, why fast hashes like md5() and sha1() are dangerous for passwords, how to choose between bcrypt and Argon2id, how to upgrade old hashes transparently, and how to avoid leaking information through timing.

It's part of the Security chapter that starts with Web Security Basics. For general-purpose hashing (checksums, HMAC signatures) see the next lesson, Hashing, Encryption and Random Numbers.

Why not md5, sha1 or sha256?

A hash function turns any input into a fixed-size fingerprint, and you can't run it backwards. That sounds perfect for passwords: store hash($password), and at login compare hash($input) with it. Two problems make this unsafe.

Fast hashes are fast for attackers too. MD5, SHA-1 and SHA-256 were designed to hash gigabytes per second. An attacker with a leaked list simply hashes guesses, from dictionaries of real leaked passwords plus common variations, and looks for matches. A single modern graphics card computes billions of MD5 hashes per second.

Without a salt, equal passwords have equal hashes. Every user with the password sunshine1 has the same MD5 hash, so cracking it once cracks all of them, and precomputed tables of hashes for millions of common passwords make it instant.

PHP How fast hashes fail

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 fgets(STDIN)), it gets the next line from this box.

Ana and Chen share a hash, so one lookup cracks both. Only Ben's long passphrase survives, because it isn't in the dictionary. Even plain PHP, slowed down by the timing check in the loop, manages tens of thousands of MD5 hashes in 50 ms on one core of our server; dedicated cracking hardware is many thousands of times faster. Adding SHA-256 or hashing twice doesn't change the picture. You need a hash that is salted and deliberately slow.

password_hash and password_verify

password_hash() takes the password and an algorithm and returns a string that contains everything needed to check it later: the algorithm, its cost settings, a random salt generated for you, and the hash itself. password_verify() takes a login attempt and the stored string, recomputes the hash with the same settings and salt, and compares the result in constant time.

PHP Hashing and verifying a password

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 fgets(STDIN)), it gets the next line from this box.

The two hashes of the same password differ because each got its own random salt, yet password_verify() accepts both. A wrong password, even one differing only in case, is rejected. You never handle the salt yourself, and you never compare hashes with ===: always call password_verify().

PASSWORD_DEFAULT currently means bcrypt, shown as $2y$. Since PHP 8.4, its default cost is 12 (it was 10 before). The constant may point to a stronger algorithm in a future version, which is why the column storing hashes should be VARCHAR(255), not exactly 60 characters.

A typical registration and login look like this on a real server:

PHP
// Registration
$hash = password_hash($_POST['password'], PASSWORD_DEFAULT);
$pdo->prepare('INSERT INTO users (email, password_hash) VALUES (?, ?)')
    ->execute([$email, $hash]);

// Login
$stmt = $pdo->prepare('SELECT id, password_hash FROM users WHERE email = ?');
$stmt->execute([$email]);
$user = $stmt->fetch();

if ($user !== false && password_verify($_POST['password'], $user['password_hash'])) {
    session_regenerate_id(true);
    $_SESSION['user_id'] = $user['id'];
}

password_verify() takes the password exactly as typed. Don't trim() it, lowercase it or strip characters before hashing; a password may legitimately start with a space or contain any Unicode character.

Choosing the cost

"Deliberately slow" is tunable. For bcrypt, the cost is a power of two: each step up doubles the work. The goal is a hash that takes roughly a few hundred milliseconds on your server. That's unnoticeable for one login but makes guessing millions of passwords enormously expensive.

PHP Measuring bcrypt costs

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 fgets(STDIN)), it gets the next line from this box.

Each step roughly doubles the time. Run this on your production hardware and pick the highest cost that stays within your budget; the PHP 8.4 default of 12 is a good starting point. Remember that a busy login form or registration endpoint multiplies the cost by the number of requests, so slow hashing also needs rate limiting to keep attackers from using it to overload your server.

bcrypt or Argon2id?

PHP supports two password hashing families:

bcrypt (PASSWORD_BCRYPT, PASSWORD_DEFAULT) Argon2id (PASSWORD_ARGON2ID)
Age 1999, extremely well studied 2015, winner of the Password Hashing Competition
Tuning cost (CPU time) memory_cost (KiB), time_cost (passes), threads
Strength against GPUs Good Better: needs lots of memory per guess, which GPUs and custom chips lack
Input limit First 72 bytes only No practical limit
Availability Always Needs PHP built with Argon2 support (most Linux packages; check with defined('PASSWORD_ARGON2ID'))

Both are good choices, and either is vastly better than any fast hash. Argon2id is what current security guidance prefers when it's available. Its PHP defaults are 64 MiB of memory, 4 passes and 1 thread:

PHP Argon2id hashes

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 fgets(STDIN)), it gets the next line from this box.

The settings are stored in the hash itself (m=65536,t=4,p=1), so password_verify() works no matter which settings each user's hash was created with. Memory cost is per hash, per concurrent login: 64 MiB times 20 simultaneous logins is over a gigabyte, so size it for your server.

bcrypt only uses the first 72 bytes of the password and ignores the rest. Two long passwords that share their first 72 bytes verify as equal. That rarely matters for typed passwords, but it does if you ever hash a value made by joining other strings (such as $email . $password), and a multibyte UTF-8 password reaches 72 bytes with fewer than 72 characters. bcrypt also rejects passwords containing a NUL byte with a ValueError. Argon2id has neither limit. Never "fix" the limit by pre-hashing with a fast hash in hex or raw form without understanding the trade-offs; prefer Argon2id instead.

Upgrading hashes with password_needs_rehash

Algorithms and costs change over time. You can't recompute old hashes, since you don't know the passwords, but at login you briefly have the plain password. That's the moment to upgrade: after a successful password_verify(), ask password_needs_rehash() whether the stored hash uses your current algorithm and options, and if not, hash the password again and save it.

The same trick migrates a legacy database of MD5 hashes one user at a time:

PHP Upgrading old hashes at login

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 fgets(STDIN)), it gets the next line from this box.

Ana's MD5 hash and Ben's cost-10 bcrypt hash are replaced on their first successful login; Chen's already-current hash is left alone, and a failed login changes nothing. Users who never log in again keep their old hashes. For a legacy MD5 table, many teams also wrap the old hashes right away, storing password_hash(md5_hash) in a separate marked column, so no plain MD5 stays in the database while waiting for logins.

Timing and user enumeration

Login forms leak information in subtle ways. If an unknown email is rejected instantly but a known email with a wrong password takes 300 ms (because password_verify() ran), an attacker can measure response times and learn which emails have accounts. The same goes for different error messages ("No such user" vs "Wrong password").

The fix is to do the same work in both cases: when the user doesn't exist, verify against a dummy hash anyway, and show one generic message:

PHP Constant work for unknown users

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 fgets(STDIN)), it gets the next line from this box.

Without the dummy hash, the unknown email answers in a fraction of a millisecond, while the real account takes over 100 ms, a difference anyone can measure over the internet. With it, both take about the same time. The registration and "forgot password" forms can leak the same information ("this email is already registered"), so many sites answer those with a neutral message too and send the details by email.

Rules for storing passwords

  • Hash with password_hash() using PASSWORD_DEFAULT or PASSWORD_ARGON2ID; check with password_verify(); upgrade with password_needs_rehash() at login.
  • Never store plain text, never encrypt passwords (encryption can be reversed by whoever has the key), and never use md5(), sha1(), hash('sha256', ...) or crypt() with a home-made salt.
  • Don't impose maximum lengths below 64 characters or forbid special characters. Do require a minimum length (at least 8, better 12) and consider rejecting passwords known from leaks.
  • Never log passwords. PHP 8.2's #[\SensitiveParameter] attribute hides a parameter's value from stack traces: function login(string $email, #[\SensitiveParameter] string $password).
  • Rate-limit login attempts per account and per IP address, and offer two-factor authentication for important accounts.
  • Store the hash in a VARCHAR(255) column.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Why are md5() and sha256 hashes unsuitable for storing passwords?

    Password hashes must be salted and deliberately slow. password_hash() provides both.
  2. 2. You call password_hash('secret', PASSWORD_DEFAULT) twice. What do you get?

    Each call generates a new random salt, which is stored inside the hash string, so both verify.
  3. 3. When is the right moment to call password_needs_rehash()?

    Rehashing needs the plain password, which you only have during a successful login. That's when you upgrade the stored hash.
  4. 4. What does password_verify($long . 'abc', password_hash($long . 'xyz', PASSWORD_BCRYPT)) return when $long is 80 ASCII characters?

    bcrypt only uses the first 72 bytes, so the different endings are ignored. Argon2id doesn't have this limit.
  5. 5. Why should a login form run password_verify() against a dummy hash when the email doesn't exist?

    Answering unknown emails instantly while real accounts take hundreds of milliseconds lets attackers enumerate users by timing.

Summary

  • Store passwords with password_hash() and check them with password_verify(). The returned string contains the algorithm, options, a random salt and the hash.
  • Fast hashes (md5, sha1, sha256) are unsafe for passwords: attackers test billions of guesses per second, and unsalted hashes reveal shared passwords.
  • bcrypt (PASSWORD_DEFAULT, cost 12 since PHP 8.4) is solid but uses only the first 72 bytes; Argon2id is memory-hard and preferred where available. Tune the cost to a few hundred milliseconds.
  • password_needs_rehash() after a successful login upgrades old algorithms and costs, and lets you migrate legacy MD5 hashes.
  • Avoid user enumeration: same message and same amount of work (a dummy hash) for unknown users.
  • Use a VARCHAR(255) column, don't alter the password before hashing, never log it (#[\SensitiveParameter]), and rate-limit logins.

Next: Hashing, Encryption and Random Numbers