PasswordEncoder and BCrypt
45 min · Intermediate
Need help? Ask a tutor on WhatsApp (opens in a new tab)If a ShopLite database leaks, plain passwords expose every customer at once, and fast hashes are cracked within hours. Passwords need a slow, salted hash that nobody can turn back into the original.
The PasswordEncoder interface: encode and matches
PasswordEncoder is the Spring Security interface for storing passwords: encode(raw) makes the hash to store, and matches(raw, encoded) checks a typed password against a stored hash. There is no decode.
Your code calls encode once at sign-up, and Spring Security calls matches at every sign-in. Example 1 hashes one password twice.
<!-- pom.xml of the small lab project (inside shoplite-api the security starter already brings these) --><dependency> <groupId>org.springframework.security</groupId> <artifactId>spring-security-crypto</artifactId></dependency><dependency> <groupId>org.springframework</groupId> <artifactId>spring-core</artifactId></dependency>Example 1 · PasswordEncoderDemo.java: encode twice, check with matches
Runs in: a small Maven project with spring-security-crypto and spring-core (versions from Spring Boot 4.1.1)
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;import org.springframework.security.crypto.password.PasswordEncoder;
public class PasswordEncoderDemo {
public static void main(String[] args) { PasswordEncoder encoder = new BCryptPasswordEncoder(); String password = "orders ship in two days";
// Sign-up: hash once and store only the hash String first = encoder.encode(password); String second = encoder.encode(password); System.out.println("First hash: " + first); System.out.println("Second hash: " + second); System.out.println("Same text? " + first.equals(second));
// Sign-in: never decode; hash the typed password again and compare inside matches() System.out.println("matches(right password, first) = " + encoder.matches(password, first)); System.out.println("matches(right password, second) = " + encoder.matches(password, second)); System.out.println("matches(one letter off, first) = " + encoder.matches("orders ship in two dayS", first)); System.out.println("equals(right password, first) = " + password.equals(first)); }}First hash: $2a$10$QiZE/JKj3GOncLrKWOwKXeUDuA9W6I8hscni.IjhobeQ5Dx1zhgy6 Second hash: $2a$10$hqtIK5lWhpD7Nb7Drd5EOOlEYHV73.BU9OmrHX5f1lIQ3u8B3tPJ2 Same text? false matches(right password, first) = true matches(right password, second) = true matches(one letter off, first) = false equals(right password, first) = false
What this code does
- Each
encodecall gives a different string for the same password (your hashes will differ too). Both are correct:matchesaccepts the right password against either one. - Changing one letter (
canteeN) givesfalse. There is no partial match and no way to see how close a guess was. equalsbetween a password and its hash is always false. Code that compares strings instead of callingmatchescan never sign anyone in.
Why an interface and not a call to MessageDigest? Password hashing has many traps (salts, slow rounds, safe comparison, length limits), and each trap is a real breach somewhere. Spring's encoders are reviewed, tested code.
What can go wrong: comparing with equals. Two encodes of the same password give different text (Example 1), so hash.equals(encode(typed)) is always false. Only matches can redo the hash with the stored salt.
Predict the output
encode or matches?
Each hash was made by encoder.encode("secret-pass-1").
Round 1 of 3
What does same hold?
Reading a BCrypt hash
Salt is a random value made fresh for every encode and stored inside the hash itself, so equal passwords give different hashes and precomputed tables of hashes are useless.
A BCrypt hash is a 60-character string, and everything matches needs is inside it. Example 2 cuts one apart.
Example 2 · BcryptHashPartsDemo.java: the four parts of a stored hash
Runs in: a small Maven project with spring-security-crypto and spring-core (versions from Spring Boot 4.1.1)
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
public class BcryptHashPartsDemo {
public static void main(String[] args) { String hash = new BCryptPasswordEncoder().encode("orders ship in two days");
// $2a$10$ + 22 characters of salt + 31 characters of hash = 60 characters String[] parts = hash.split("\\$"); // "", "2a", "10", salt + hash String saltAndHash = parts[3];
System.out.println("Stored value: " + hash); System.out.println("Length: " + hash.length()); System.out.println("Version: " + parts[1]); System.out.println("Cost: " + parts[2] + " (2^" + parts[2] + " = " + (1 << Integer.parseInt(parts[2])) + " rounds of key setup)"); System.out.println("Salt: " + saltAndHash.substring(0, 22)); System.out.println("Hash: " + saltAndHash.substring(22)); }}Stored value: $2a$10$N6o9qQQ9A.O710/9sag.ROjXxf7YL0cSuk.kLWNb2bS.4tXC/Stg. Length: 60 Version: 2a Cost: 10 (2^10 = 1024 rounds of key setup) Salt: N6o9qQQ9A.O710/9sag.RO Hash: jXxf7YL0cSuk.kLWNb2bS.4tXC/Stg.
What this code does
split("\\$")cuts the string at each$. Part 1 is the version (2a), part 2 the cost, part 3 the salt and hash run together.- The first 22 characters of part 3 are the salt, the last 31 the hash, both in BCrypt's own Base64 alphabet (
./A-Za-z0-9). - Everything
matchesneeds is in these 60 characters, which is why onepassword_hashcolumn is enough.
The four parts are $2a$ (the version), 10$ (the cost), 22 characters of salt and 31 characters of the real hash. matches reads the version, cost and salt back out of the stored string, hashes the typed password with them and compares the last 31 characters, so no separate salt column is needed.
The salt is why a leaked table is not cracked all at once. An attacker cannot see who shares a password, and a precomputed rainbow table is useless: every guess must be redone for every single user.
Choosing the cost factor
Cost factor (also called strength or log rounds) sets how slow one BCrypt hash is: each step up doubles the work, because BCrypt runs 2^cost rounds of key setup. The default is 10, and Spring allows 4 to 31.
Slow is the point. Example 3 times one hash at costs 8 to 14 on a laptop.
Example 3 · CostFactorDemo.java: how long one hash takes
Runs in: a small Maven project with spring-security-crypto and spring-core (versions from Spring Boot 4.1.1)
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
public class CostFactorDemo {
public static void main(String[] args) { String password = "orders ship in two days"; new BCryptPasswordEncoder(10).encode(password); // warm-up: the first call also loads classes
System.out.println("cost ms per hash hashes per second (one core)"); for (int cost = 8; cost <= 14; cost++) { BCryptPasswordEncoder encoder = new BCryptPasswordEncoder(cost); int runs = 3; long start = System.nanoTime(); for (int i = 0; i < runs; i++) { encoder.encode(password); } double ms = (System.nanoTime() - start) / 1_000_000.0 / runs; System.out.printf("%4d %11.0f %17.1f%n", cost, ms, 1000 / ms); } }}cost ms per hash hashes per second (one core) 8 27 36.9 9 49 20.4 10 89 11.3 11 229 4.4 12 426 2.3 13 860 1.2 14 1952 0.5
What this code does
- Each step of cost roughly doubles the time: 89 ms at 10, about 430 ms at 12, almost 2 seconds at 14 on this laptop. Your numbers depend on your CPU.
- The warm-up call matters: the first
encodealso loads classes and would make cost 8 look slow. - ShopLite keeps the default 10 for development. On a server, measure there and choose the highest cost that stays near your sign-in budget.
A fast hash like SHA-256 lets one graphics card test billions of guesses per second. At cost 10 one CPU core manages about ten BCrypt hashes per second, so a guess list of a billion common passwords takes years per user instead of seconds.
Every sign-in and every sign-up pays the cost once. Measure on your server and pick the highest value that keeps one hash around 100 to 300 ms: at cost 14 a burst of sign-ins can keep every CPU busy, which an attacker can use to slow your site down.
DelegatingPasswordEncoder and the {bcrypt} prefix
DelegatingPasswordEncoder is a PasswordEncoder that writes an {id} such as {bcrypt} in front of each hash and hands every matches call to the encoder with that id, so the algorithm can change later.
The {bcrypt} prefix tells Spring which algorithm made each stored hash. Example 4 checks a BCrypt and an Argon2 hash with one encoder.
Example 4 · DelegatingEncoderDemo.java: the {id} prefix, old hashes and upgrades
Runs in: a small Maven project with spring-security-crypto and spring-core (versions from Spring Boot 4.1.1) plus org.bouncycastle:bcprov-jdk18on 1.86 for Argon2
import org.springframework.security.crypto.argon2.Argon2PasswordEncoder;import org.springframework.security.crypto.factory.PasswordEncoderFactories;import org.springframework.security.crypto.password.PasswordEncoder;
public class DelegatingEncoderDemo {
public static void main(String[] args) { PasswordEncoder encoder = PasswordEncoderFactories.createDelegatingPasswordEncoder(); String password = "orders ship in two days";
String hash = encoder.encode(password); System.out.println("New hash: " + hash); System.out.println("matches: " + encoder.matches(password, hash)); System.out.println("needs upgrade: " + encoder.upgradeEncoding(hash));
// An account from an older system, hashed with Argon2 and stored with its own {id} String argon2 = "{argon2@SpringSecurity_v5_8}" + Argon2PasswordEncoder.defaultsForSpringSecurity_v5_8().encode(password); System.out.println(); System.out.println("Old hash: " + argon2); System.out.println("matches: " + encoder.matches(password, argon2)); System.out.println("needs upgrade: " + encoder.upgradeEncoding(argon2));
// A hash with no {id} at all: the encoder does not know which algorithm made it String bare = hash.substring("{bcrypt}".length()); System.out.println(); try { encoder.matches(password, bare); } catch (IllegalArgumentException e) { System.out.println("No prefix: " + e.getMessage()); } }}New hash: {bcrypt}$2a$10$TWVEKcTNHi4yE3OUQJv2Lue9o2cSnWVhp2rJcft/Hywoam3DnuSBC
matches: true
needs upgrade: false
Old hash: {argon2@SpringSecurity_v5_8}$argon2id$v=19$m=16384,t=2,p=1$HAz+NCshYqnrlQ+Gd8g8+A$zAqOIQjp6340gvWr3j6YlL7NHrT7Z91UtQWGSq+ZBCU
matches: true
needs upgrade: true
No prefix: Given that there is no default password encoder configured, each password must have a password encoding prefix. Please either prefix this password with '{noop}' or set a default password encoder in `DelegatingPasswordEncoder`.What this code does
- New hashes start with
{bcrypt}. The same encoder also checks the Argon2 hash, because its{argon2@SpringSecurity_v5_8}prefix names the right encoder (Argon2 settings: 16 MB of memory, 2 passes). upgradeEncodingistruefor the Argon2 row because the current default is BCrypt; Spring Security can re-hash such rows at sign-in through aUserDetailsPasswordService.- A hash without a prefix is refused. In ShopLite that showed up as a 500 at sign-in when a seed script stored a BCrypt hash without
{bcrypt}: always store exactly whatencodereturns.
PasswordEncoderFactories.createDelegatingPasswordEncoder() encodes new passwords with BCrypt and still understands {argon2@SpringSecurity_v5_8}, {pbkdf2@SpringSecurity_v5_8}, {scrypt@SpringSecurity_v5_8}, {noop} and older formats. If ShopLite moves to Argon2 in two years, new hashes get {argon2...} while old {bcrypt} rows keep working, and upgradeEncoding(hash) tells you which rows to re-hash at the user's next sign-in.
Argon2 (Argon2PasswordEncoder) is the modern alternative: besides time it also costs memory per guess, which slows graphics cards more. It needs the BouncyCastle library (org.bouncycastle:bcprov-jdk18on). BCrypt at a sensible cost is still an accepted choice and is what ShopLite uses.
Find the bug
Find the password bug
Each snippet stores or checks passwords wrongly. Tap the wrong line.
Sign-in check.
Round 1 of 3SecurityConfig: @Bean PasswordEncoder passwordEncoder() { return PasswordEncoderFactories.createDelegatingPasswordEncoder(); }. Spring Security's sign-in and your UserService then use the same one.BCrypt's 72-byte input limit
72-byte limit is the most that BCrypt reads of a password, counted in UTF-8 bytes: an English letter is 1 byte, a Hindi or Tamil letter is 3 bytes.
The limit counts bytes, not characters. Example 5 encodes passwords of 72 and 73 bytes.
Example 5 · LongPasswordDemo.java: 72 bytes, not 72 characters
Runs in: a small Maven project with spring-security-crypto and spring-core (versions from Spring Boot 4.1.1)
import java.nio.charset.StandardCharsets;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
public class LongPasswordDemo {
static int bytes(String text) { return text.getBytes(StandardCharsets.UTF_8).length; }
public static void main(String[] args) { BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
String english = "my hostel room is 214 and my bike is a blue splendor"; String hindi = "मेरा पासवर्ड बहुत लंबा और सुरक्षित है"; System.out.println("English: " + english.length() + " characters, " + bytes(english) + " bytes"); System.out.println("Hindi: " + hindi.length() + " characters, " + bytes(hindi) + " bytes");
String exactly72 = "a".repeat(72); String hash = encoder.encode(exactly72); System.out.println("72 bytes encoded fine, length " + hash.length());
try { encoder.encode(exactly72 + "b"); } catch (IllegalArgumentException e) { System.out.println("73 bytes: " + e.getMessage()); }
// matches() still reads only the first 72 bytes of what is typed System.out.println("matches(72 a's + \"b\") = " + encoder.matches(exactly72 + "b", hash)); System.out.println("matches(71 a's) = " + encoder.matches("a".repeat(71), hash)); }}English: 52 characters, 52 bytes Hindi: 37 characters, 99 bytes 72 bytes encoded fine, length 60 73 bytes: password cannot be more than 72 bytes matches(72 a's + "b") = true matches(71 a's) = false
What this code does
- A 37-character Hindi passphrase is 99 bytes in UTF-8: well inside a 64-character rule, but too long for BCrypt. Count bytes with
getBytes(StandardCharsets.UTF_8).length. encoderefuses the 73rd byte with anIllegalArgumentException. Inside a controller that would surface as a 500 unless validation stops it first.matchesignores everything after 72 bytes: 72as plusbmatches the hash of 72as. That is why the limit belongs in the sign-up validation.
Since Spring Security 6.3, BCryptPasswordEncoder.encode refuses longer input with IllegalArgumentException: password cannot be more than 72 bytes; older versions silently ignored the rest. matches still compares only the first 72 bytes of what is typed, so the limit must be checked where passwords are created, at sign-up and password change, with a clear 400 and not a 500 from deep inside the encoder.
ShopLite's rule is 15 to 64 characters and at most 72 bytes in UTF-8, built in the Sign-up lesson. Some systems pre-hash long passwords with SHA-256 before BCrypt; that has its own traps, so if you need long passwords, prefer Argon2, which has no such limit.
Next step
Check your understanding
12 quick questions