00:00

BCrypt Password Encoding in Spring Security

Last updated:

BCrypt is the password hashing algorithm Spring Security uses by default. It was designed in 1999 specifically for passwords: every hash includes its own random salt and a cost factor that controls how slow hashing is, so it can be made slower as computers get faster.

This tutorial takes a real BCrypt hash apart, measures what the cost factor means in milliseconds, explains the 72-byte limit that catches many teams, and finishes with a Spring Boot sign-up API that stores BCrypt hashes and checks them at login.

1. What Is BCrypt?

BCrypt is a one-way, salted, adaptive hash function based on the Blowfish cipher. "One-way" means the password cannot be calculated back from the hash. "Salted" means a random value is mixed into every hash. "Adaptive" means the amount of work is a parameter, the cost factor (Spring calls it strength), which doubles the work for each step up.

In Spring Security, BCrypt is implemented by BCryptPasswordEncoder, one of the PasswordEncoder implementations. DelegatingPasswordEncoder uses it for every new password and stores the result with a {bcrypt} prefix.

2. Why BCrypt Is Used for Passwords

A general-purpose hash such as SHA-256 is designed to be fast; a modern GPU computes billions of them per second, so a leaked table of SHA-256 password hashes falls quickly to guessing. BCrypt is designed to be slow, and its cost factor keeps it slow as hardware improves.

The built-in salt defeats precomputed "rainbow tables" and ensures that two users with the same password get different hashes, so cracking one does not reveal the other. Because the salt and cost are stored inside the hash string, you do not need extra database columns.

3. How a BCrypt Hash Is Structured

This small program hashes the same password twice and checks both hashes:

BcryptAnatomy.java
package com.javabytechie.bcrypt;

import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;

public class BcryptAnatomy {
    public static void main(String[] args) {
        BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();   // strength 10
        String first = encoder.encode("river-lantern-42");
        String second = encoder.encode("river-lantern-42");
        System.out.println(first);
        System.out.println(second);
        System.out.println("same hash?     " + first.equals(second));
        System.out.println("first matches? " + encoder.matches("river-lantern-42", first));
        System.out.println("second matches? " + encoder.matches("river-lantern-42", second));
    }
}
Terminal
$ java BcryptAnatomy
$2a$10$sGNDUPBzZFDHc/3mqsBKf.T2QyMgngPnt3bx1SysYL5EqR5O5QpjK
$2a$10$C2ubVjFHtDhzn3D9AvHi/eowKn8FbtaZi9tis45b9937OBOVUR7t.
same hash?     false
first matches? true
second matches? true

The hashes differ because each one has a new salt, yet both match the password. Every BCrypt hash has the same 60-character layout:

Parts of a BCrypt hash stringA BCrypt hash starts with the version 2a, then the cost factor 10, then a 22-character salt, then a 31-character hash, separated by dollar signs. $2a$ algorithm version 10$ cost: 2^10 rounds 22 characters random salt (128 bits) 31 characters the actual hash (184 bits) Example: $2a$10$ + salt + hash = 60 characters in total
Figure 1: version, cost, salt and hash all live in one string, so no extra columns are needed.

When matches runs, it reads the version, cost and salt from the stored hash, hashes the submitted password with them and compares the result. That is why a different cost or a different salt on another row is never a problem.

3.1 What the Cost Factor Means in Time

Each increase of the strength by one doubles the work. This program measures it:

BcryptCostCheck.java
package com.javabytechie.bcrypt;

import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;

public class BcryptCostCheck {
    public static void main(String[] args) {
        for (int strength = 10; strength <= 14; strength++) {
            BCryptPasswordEncoder encoder = new BCryptPasswordEncoder(strength);
            encoder.encode("warm-up");                          // let the JIT compile first
            long start = System.nanoTime();
            int runs = 5;
            for (int i = 0; i < runs; i++) {
                encoder.encode("river-lantern-42");
            }
            long avgMillis = (System.nanoTime() - start) / runs / 1_000_000;
            System.out.printf("strength %d: %4d ms per hash%n", strength, avgMillis);
        }
    }
}
Terminal
$ java BcryptCostCheck
strength 10:   57 ms per hash
strength 11:  116 ms per hash
strength 12:  230 ms per hash
strength 13:  458 ms per hash
strength 14:  913 ms per hash

These numbers were measured on an Apple M4 laptop; your server will differ, so run the check on your own hardware. A common target is a hash time of roughly a quarter to half a second on the production server. Remember that every login pays this cost, and attackers pay it for every guess.

3.2 The 72-Byte Limit

BCrypt uses only the first 72 bytes of a password. In Spring Security 7.1.2, BCryptPasswordEncoder.encode throws IllegalArgumentException: password cannot be more than 72 bytes for longer input rather than silently ignoring the rest. Bytes are not characters: in UTF-8, many non-Latin characters take three bytes, so a 25-character Hindi password is already longer than 72 bytes. Check the byte length when users choose a password, as the example below does.

4. BCryptPasswordEncoder Constructors

ConstructorUse
BCryptPasswordEncoder()Strength 10, version $2a
BCryptPasswordEncoder(int strength)Custom strength from 4 to 31
BCryptPasswordEncoder(BCryptVersion version, int strength)Choose $2a, $2b or $2y for compatibility with other systems
BCryptPasswordEncoder(int strength, SecureRandom random)Supply your own random source for salts

upgradeEncoding returns true when a stored hash has a lower strength than the encoder's, so raising the strength can be combined with the automatic upgrade described in the PasswordEncoder tutorial.

5. A Complete Example: Marathon Volunteer Sign-Up

Volunteers for a city marathon register through a mobile app, then sign in with HTTP Basic. Passwords are hashed with BCrypt at strength 12 and validated for length in bytes. The API is used only by the mobile app, which sends credentials itself, so CSRF protection is disabled for it. The example uses Java 21, Spring Boot 4.1.2 and Spring Security 7.1.2 and spring-boot-starter-validation.

package com.javabytechie.bcrypt;

import java.util.Map;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpMethod;
import org.springframework.security.config.Customizer;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.DelegatingPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.SecurityFilterChain;

@Configuration
public class SecurityConfig {

    @Bean
    SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
        http
            .authorizeHttpRequests(auth -> auth
                .requestMatchers(HttpMethod.POST, "/api/volunteers").permitAll()
                .requestMatchers("/error").permitAll()
                .anyRequest().authenticated())
            .httpBasic(Customizer.withDefaults())
            .sessionManagement(s -> s.sessionCreationPolicy(SessionCreationPolicy.STATELESS))
            .csrf(csrf -> csrf.disable());   // mobile client only, no browser cookies
        return http.build();
    }

    @Bean
    PasswordEncoder passwordEncoder() {
        // BCrypt at strength 12, stored with the {bcrypt} prefix
        return new DelegatingPasswordEncoder("bcrypt", Map.of("bcrypt", new BCryptPasswordEncoder(12)));
    }
}

6. Step-by-Step Code Explanation

  1. Strength 12. The PasswordEncoder bean wraps BCryptPasswordEncoder(12) in a DelegatingPasswordEncoder, so hashes are stored as {bcrypt}$2a$12$... and the system can still move to another algorithm later.
  2. Two length checks. Bean Validation limits the password to 12-64 characters. The service then checks the UTF-8 byte length against BCrypt's 72-byte limit and returns a clear 400 instead of an unexplained server error.
  3. Hash once, store the hash. register calls encode once and stores only the result. The log line records only the first 14 characters, the prefix, version and cost ({bcrypt}$2a$12), but never the hash or the password.
  4. Login uses the same encoder. VolunteerService is also the UserDetailsService, so DaoAuthenticationProvider verifies Basic credentials with the same BCrypt encoder.

7. Expected Output

Terminal
$ curl -X POST localhost:8080/api/volunteers -H 'Content-Type: application/json' -d '{"username":"tara","password":"river-lantern-42"}'
HTTP/1.1 201
{"username":"tara","status":"registered"}

$ curl -X POST localhost:8080/api/volunteers -H 'Content-Type: application/json' -d '{"username":"tara","password":"another-pass-99"}'
HTTP/1.1 409
{"timestamp":"2026-11-18T12:14:03.497Z","status":409,"error":"Conflict","path":"/api/volunteers"}

$ curl -X POST localhost:8080/api/volunteers -H 'Content-Type: application/json' -d '{"username":"omkar","password":"पासवर्डपासवर्डपासवर्डपासवर्ड"}'
HTTP/1.1 400
{"timestamp":"2026-11-18T12:14:03.511Z","status":400,"error":"Bad Request","path":"/api/volunteers"}

$ curl -u tara:river-lantern-42 localhost:8080/api/volunteers/me
HTTP/1.1 200
{"username":"tara","station":"Water point 7"}

$ curl -u tara:wrong-password localhost:8080/api/volunteers/me
HTTP/1.1 401
{"timestamp":"2026-11-18T12:14:04.230Z","status":401,"error":"Unauthorized","path":"/api/volunteers/me"}

Tara registers and receives 201; a second sign-up with her name gets 409. Omkar's Hindi password is 28 characters, which passes the character limit, but it is 84 bytes in UTF-8, so the byte check rejects it with 400. Tara can then sign in with her password, and a wrong password gets 401. The log confirms the stored format:

Terminal
Stored tara with {bcrypt}$2a$12

8. Advantages and Limitations

AdvantagesLimitations
Salt and cost are built into the hash stringOnly the first 72 bytes of a password are used
Cost factor can grow with hardwareNot memory-hard, so GPUs and ASICs attack it more efficiently than Argon2
Supported by almost every platform and languageHigh strength slows logins and can be abused for denial of service without rate limiting
Spring Security's default, with automatic upgrades through DelegatingPasswordEncoderHash strings are 60 characters; columns must allow the {bcrypt} prefix too (68 or more)

9. Common Mistakes and Best Practices

  • Choosing strength by habit. Measure on production hardware and pick the highest strength your login traffic can afford.
  • Ignoring the byte limit. Validate the UTF-8 byte length at sign-up and password change.
  • Comparing with equals. Two encodings of the same password never match as strings; always call matches.
  • A database column that is too short. A truncated hash can never match. Use at least VARCHAR(100) to leave room for prefixes.
  • No rate limiting on login. Slow hashing protects stolen data, not your login endpoint. Limit attempts per account and per IP address.

10. Summary

  • BCrypt is a slow, salted, adaptive hash and the default for new passwords in Spring Security.
  • A hash such as $2a$12$... contains the version, cost, 22-character salt and 31-character hash.
  • Each strength step doubles hashing time; measure and choose the highest your servers can afford.
  • BCrypt uses at most 72 bytes, and Spring Security 7 rejects longer passwords when encoding.
  • Configure BCrypt through DelegatingPasswordEncoder so you can change algorithms later.

11. References