Hashing, not encrypting
Passwords should never be stored as they are, and they shouldn't be encrypted either. Encryption can be reversed by anyone with the key – and if a database is stolen, the key often goes with it. Passwords should be hashed: turned into a fixed-length fingerprint that can't be turned back. To check a login, you hash what the user typed and compare the results.
Why not MD5 or SHA-256?
Because they're fast – and for passwords, fast is bad. A graphics card can test billions of MD5 or SHA-256 guesses every second, so most leaked "hashed" passwords are cracked within days. Password hashing algorithms are designed to be slow on purpose and to include a random salt, so identical passwords get different hashes and pre-computed tables are useless.
bcrypt or Argon2?
- Argon2id
- The modern choice and the winner of the Password Hashing Competition. As well as being slow, it uses a large amount of memory for each guess, which makes cracking with graphics cards and custom hardware much more expensive. Use it for new projects if your platform supports it (PHP 7.3+ does).
- bcrypt
- Older but still a solid, widely supported choice. Its "cost" setting doubles the work each time it goes up by one. Its main quirk: it only uses the first 72 bytes of a password, so very long passphrases are cut short.
- Argon2i
- An earlier variant of Argon2, included for checking older hashes. Prefer Argon2id for anything new.
Reading a hash
Everything needed to check a password is stored inside the hash itself:
$2y$12$… – bcrypt, cost 12, followed by 22 characters of salt and 31 of hash.$argon2id$v=19$m=19456,t=2,p=1$… – Argon2id version 19, using 19,456 KiB of memory, 2 passes and 1 lane, followed by the salt and the hash.
Because the settings travel with each hash, you can raise them later – PHP's
password_needs_rehash() tells you when a stored hash uses old settings, so you can upgrade it the next
time that user logs in.
Using it in PHP
// When a user sets a password
$hash = password_hash($password, PASSWORD_ARGON2ID); // or PASSWORD_DEFAULT (bcrypt)
// store $hash in a VARCHAR(255) column
// When they log in
if (password_verify($password, $hash)) {
if (password_needs_rehash($hash, PASSWORD_ARGON2ID)) {
// settings have changed – save password_hash($password, PASSWORD_ARGON2ID) instead
}
// logged in
}
Other languages have the same algorithms: bcrypt and argon2-cffi for Python,
bcrypt and argon2 for Node.js, BCrypt.Net and Konscious.Security.Cryptography
for .NET. Hashes made here work with all of them.
Choosing the settings
Aim for each login check to take roughly a quarter to half a second on your server – slow enough to hurt an attacker, fast enough that users don't notice. The OWASP password storage guidance suggests Argon2id with at least 19 MiB of memory and 2 passes, or bcrypt with a cost of 10 or more. This page runs in your browser in plain JavaScript, which is slower than a server, so higher settings may take a few seconds here.