Cipher Utility

Hashing Passwords Correctly in Your Database

Salts, slow hashes and the settings that matter.

Why passwords need special treatment

Most people reuse passwords. When a site leaks its password database, attackers try the same email and password combinations on banks, email providers and shops, so a mistake in one application hurts users everywhere else. You can't stop every breach, but you can store passwords so that a stolen database is close to useless. The method has been known for decades: hash each password with a slow, salted password hashing function.

Breaches caused by weak storage

  • LinkedIn: a 2012 breach, whose full extent of about 117 million accounts became public in 2016, exposed passwords hashed with unsalted SHA-1. Most of them were cracked.
  • Adobe, 2013: around 153 million records. The passwords were encrypted with 3DES in ECB mode rather than hashed, and stored next to plain text password hints, so many could be worked out.
  • Yahoo: a 2013 breach, disclosed in 2016, exposed account data for all of its users, including passwords hashed with MD5.
  • Facebook, 2019: the company found that hundreds of millions of passwords had been written in plain text to internal logs that employees could search.

Ways not to store passwords

Plain text

password: myPassword123

Anyone who can read the database, an attacker or an employee, sees every password.

Encoding

password: base64("myPassword123") = bXlQYXNzd29yZDEyMw==

Base64 is an encoding, not encryption. Anyone can reverse it. See Base64 is not encryption.

Encryption

password: AES_encrypt("myPassword123", key)

Encryption can be reversed by design. If the key leaks along with the database, which often happens because both live on the same servers, every password is exposed at once. Adobe is the example.

A fast hash

password: MD5("myPassword123") = 487753b954871b5b05f854060de151d8

MD5, SHA-1 and SHA-256 are built to be fast. A single graphics card can test billions of guesses per second against them, and without a salt, identical passwords produce identical hashes, so precomputed tables crack common passwords instantly. Why MD5 isn't secure goes into the details.

What a password hash needs

  • Slowness. Each hash should take tens to hundreds of milliseconds on your server, which is nothing for one login and a huge cost for an attacker making billions of guesses.
  • Memory hardness. If each hash also needs a lot of memory, graphics cards and custom chips lose most of their advantage, because they can't run as many guesses in parallel.
  • A unique salt. A random value per password means identical passwords get different hashes and precomputed tables don't work.
  • A cost setting. You can raise the cost as hardware gets faster without changing the algorithm.

Reading a bcrypt hash

Here is a real bcrypt hash of SecurePassword123 at cost 12:

$2y$12$UrCig44NrCb76dEeD167.eYj265UVe.HAQzS1MFmHmghSLXehrOkG
Version2ybcrypt; PHP writes 2y, most other libraries write 2b
Cost12212 rounds of the expensive key setup
SaltUrCig44NrCb76dEeD167.e22 characters, 128 random bits
HashYj265UVe.HAQzS1MFmHmghSLXehrOkG31 characters, 184 bits

Everything needed to check a password is in that one string, so store it whole in a single column. You can generate and check bcrypt hashes with the bcrypt tool.

Which algorithm to use

AlgorithmYearMemory hardVerdict
Argon2id2015YesFirst choice for new systems
scrypt2009YesGood
bcrypt1999A little (4 KB)Good, supported everywhere
PBKDF22000NoAcceptable where FIPS compliance requires it, with many iterations
SHA-256, SHA-1, MD5NoNever use alone for passwords

Argon2id

Argon2 won the Password Hashing Competition in 2015. It has three variants: Argon2d resists graphics card attacks best, Argon2i resists side-channel attacks, and Argon2id combines the two and is the one to use. You set the memory, the number of passes and the parallelism. OWASP's Password Storage Cheat Sheet suggests at least 19 MiB of memory, 2 passes and a parallelism of 1 as a minimum; more memory is better if your servers can afford it.

scrypt

scrypt was designed in 2009 to be memory-hard. Its parameters are N (cost), r (block size) and p (parallelism), and it uses about 128 × N × r bytes of memory, so N = 16384 and r = 8 needs 16 MiB.

bcrypt

bcrypt is based on the Blowfish cipher and has been in use since 1999. It is available in every major language. Use a cost of at least 10, and 12 if your servers can afford it. It only reads the first 72 bytes of a password and silently ignores the rest.

Implementation

PHP

// Hash when the user sets a password
$hash = password_hash($password, PASSWORD_ARGON2ID);   // or PASSWORD_BCRYPT

// Check at login
if (password_verify($password, $hash)) {
    // Upgrade the hash if the algorithm or cost has changed
    if (password_needs_rehash($hash, PASSWORD_ARGON2ID)) {
        $hash = password_hash($password, PASSWORD_ARGON2ID);
        // save $hash
    }
}

Python with argon2-cffi

from argon2 import PasswordHasher
from argon2.exceptions import VerifyMismatchError

ph = PasswordHasher(time_cost=2, memory_cost=65536, parallelism=2)  # 64 MiB

hash = ph.hash(password)

try:
    ph.verify(hash, password)
    if ph.check_needs_rehash(hash):
        hash = ph.hash(password)  # save the new hash
except VerifyMismatchError:
    pass  # wrong password

Node.js with bcrypt

const bcrypt = require('bcrypt');

const hash = await bcrypt.hash(password, 12);
const match = await bcrypt.compare(password, hash);

Edge cases

  • Long passwords and bcrypt. To accept more than 72 bytes, hash the password with SHA-256 first, Base64-encode the result (to avoid zero bytes) and pass that to bcrypt. Or use Argon2id, which has no such limit.
  • Unicode. The same character can be stored in more than one way. Normalize passwords (for example to NFKC) before hashing, so a user can still log in from a different device or keyboard.
  • Length limits. Allow long passwords, at least 64 characters, but set a sensible maximum so nobody can send a megabyte to your hash function.

Moving away from MD5 or SHA

You don't need to force every user to reset their password.

Rehash at login

  1. Keep the old hashes for now and add a column for the new ones.
  2. When a user logs in successfully, check the password against the old hash, then store an Argon2id or bcrypt hash and delete the old one.
  3. After a few months, force a reset for accounts that never logged in.

Until step 3, the old weak hashes remain in the database for inactive users.

Wrap the old hashes

Better: protect every account straight away by hashing the existing hashes.

stored = bcrypt(md5_hash)                     // once, for every user

at login:
check  = bcrypt_verify(md5(input), stored)    // then replace with bcrypt(input)

Every account is protected immediately, and each user moves to a plain bcrypt or Argon2id hash on their next login.

Common pitfalls

  • One salt for everybody. A global salt doesn't stop attackers from cracking all accounts in one pass. Each password needs its own random salt, which bcrypt and Argon2 generate for you.
  • Storing the salt in a separate table. It doesn't need to be secret; keep the full hash string in one field.
  • Hashing in the browser instead of on the server. The hash then becomes the password, and anyone who steals the database can log in with it. Hash on the server and use HTTPS to protect the password in transit.
  • Never raising the cost. A setting chosen years ago may be too cheap now. Check it every year or so and let the rehash-on-login code upgrade old hashes.
  • Writing passwords to logs. Check request logging, error reporting and debugging tools, as Facebook's case shows.

Performance and abuse

Aim for a hash time your servers can sustain at peak login traffic: roughly 50 to 100 ms for a typical web application, up to about half a second for high-value systems such as admin accounts.

Because every login attempt costs real CPU time and memory, attackers can try to overload a server through the login form. Rate limit login attempts per account and per IP address, add a CAPTCHA after repeated failures, and consider running password hashing on a separate worker queue so a flood of logins doesn't take down the rest of the application.

Standards and checks

NIST Special Publication 800-63B requires passwords to be stored with a salted, one-way key derivation function, and OWASP's Password Storage Cheat Sheet gives concrete settings for Argon2id, scrypt, bcrypt and PBKDF2. Regulations such as GDPR and PCI DSS ask for strong cryptography without naming one algorithm; following NIST and OWASP satisfies them in practice.

Before you ship, check that:

  • the same password hashed twice gives two different hashes
  • one hash takes the time you intended on production hardware
  • correct passwords pass and wrong ones fail, including passwords with non-English characters
  • very long passwords are handled the way you decided
  • old hashes are upgraded after a cost or algorithm change
  • rate limiting kicks in on repeated failed logins

For users, the other half of the problem is choosing passwords that are hard to guess; Password security best practices covers that side.

Try it on Cipher Utility

Further reading