Password encoding converts a user’s password into an irreversible hash before it is stored, so the real password never exists in the database. BCrypt is the standard algorithm for this in Spring Security: it adds a random salt to every password and is deliberately slow, which makes guessing attacks expensive. During login the entered password is hashed again and compared with the stored hash using PasswordEncoder.matches(), and the original password is never recovered. It is used so that even if the database is leaked, attackers cannot read passwords or reuse them on other sites.
Features
BCryptPasswordEncoderas the singlePasswordEncoderbean used by the whole application- A random salt for every hash, so the same password gives a different hash each time
- Configurable cost factor (
app.security.bcrypt-strength) so hashing can be made slower as hardware gets faster - Password strength rules at registration (length, upper case, lower case, digit, special character) and the BCrypt 72-byte limit
- Password verification with
matches()for login and for password change - Automatic hash upgrade: an old weak hash is re-hashed with the current cost after a successful login
- Hashes are never returned in API responses (
@JsonProperty(access = WRITE_ONLY))
Password Encoding Types
| Type | Explanation | Verdict |
|---|---|---|
| Plain text | The password is stored exactly as typed. Anyone who reads the database reads every password. | Never use |
| Fast hashes (MD5, SHA-1, SHA-256) | One-way hashes, but extremely fast and often unsalted, so billions of guesses per second are possible. | Not suitable for passwords |
| BCrypt | Salted, adaptive hash with a cost factor. Spring Security’s default and the most widely used. Used in this topic. | Recommended |
| SCrypt | Salted hash that also needs a lot of memory, which makes hardware attacks harder. | Good alternative |
| Argon2 | Winner of the Password Hashing Competition, memory-hard and configurable. | Good alternative (needs the Bouncy Castle library) |
| PBKDF2 | Repeats a hash many times; accepted by many security standards. | Acceptable |
DelegatingPasswordEncoder |
Stores an id with the hash, such as {bcrypt}$2a$10$..., so several algorithms can live together and old hashes can be migrated. Created by PasswordEncoderFactories.createDelegatingPasswordEncoder(). |
Good for migrations |
NoOpPasswordEncoder |
Compares plain text. Deprecated and only for tests. | Never use |
Anatomy of a BCrypt hash
$2a$12$N9qo8uLOickgx2ZMRZoMye IjZAgcfl7p92ldGxad68LJZdL17lhWy
| | | |
| | | +-- 31 characters: the hash itself
| | +-- 22 characters: the random salt (stored inside the hash)
| +-- cost factor 12: 2^12 = 4096 rounds
+-- algorithm version
The hash is always 60 characters long. The salt and the cost are stored inside it, so matches() needs nothing except the raw password and the stored hash. Each +1 in the cost factor doubles the time needed to compute a hash.
Hands-on Experiment: Secure User Registration System with BCrypt Password Hashing
To build a user registration system that stores only BCrypt hashes in MySQL, verifies passwords with matches(), enforces strong passwords and automatically upgrades weak hashes.
Software/Tools Required
- JDK 17
- Spring Boot 3.x
- Maven
- MySQL 8.x
- IDE (IntelliJ IDEA / Eclipse / STS)
- Postman
Step-by-Step Application Development
Step 1: Generate the Project via Spring Initializr
Open https://start.spring.io and select:
| Setting | Value |
|---|---|
| Project | Maven |
| Language | Java |
| Spring Boot | 3.3.x |
| Group | com.example |
| Artifact | secure-user-registration-system |
| Packaging | Jar |
| Java | 17 |
| Dependencies | Spring Web, Spring Security, Spring Data JPA, MySQL Driver |
Click Generate, extract the zip and open it in your IDE.
Step 2: Project Structure
secure-user-registration-system
├── pom.xml
└── src/main
├── java/com/example/securereg
│ ├── SecureUserRegistrationApplication.java
│ ├── entity
│ │ └── AppUser.java
│ ├── repository
│ │ └── AppUserRepository.java
│ ├── service
│ │ ├── UserService.java
│ │ ├── DataInitializer.java
│ │ └── SecurityConfig.java
│ └── controller
│ ├── AuthController.java
│ └── UserController.java
└── resources
└── application.properties
Step 3: Creating the files according to project structure
package com.example.securereg.entity;
import com.fasterxml.jackson.annotation.JsonProperty;
import jakarta.persistence.Column;
import jakarta.persistence.Entity;
import jakarta.persistence.GeneratedValue;
import jakarta.persistence.GenerationType;
import jakarta.persistence.Id;
import jakarta.persistence.Table;
@Entity
@Table(name = "app_users")
public class AppUser {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Column(nullable = false)
private String fullName;
@Column(nullable = false, unique = true)
private String username;
@Column(nullable = false, unique = true)
private String email;
// Holds the BCrypt hash (always 60 characters), never the real password.
// WRITE_ONLY: accepted in requests, never returned in responses.
@JsonProperty(access = JsonProperty.Access.WRITE_ONLY)
@Column(nullable = false, length = 100)
private String password;
public AppUser() {
}
public Long getId() { return id; }
public void setId(Long id) { this.id = id; }
public String getFullName() { return fullName; }
public void setFullName(String fullName) { this.fullName = fullName; }
public String getUsername() { return username; }
public void setUsername(String username) { this.username = username; }
public String getEmail() { return email; }
public void setEmail(String email) { this.email = email; }
public String getPassword() { return password; }
public void setPassword(String password) { this.password = password; }
}
package com.example.securereg.repository;
import com.example.securereg.entity.AppUser;
import org.springframework.data.jpa.repository.JpaRepository;
import java.util.Optional;
public interface AppUserRepository extends JpaRepository<AppUser, Long> {
Optional<AppUser> findByUsername(String username);
boolean existsByUsername(String username);
boolean existsByEmail(String email);
}
package com.example.securereg.service;
import com.example.securereg.entity.AppUser;
import com.example.securereg.repository.AppUserRepository;
import org.springframework.boot.CommandLineRunner;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Component;
/**
* Creates two sample users on first start:
* - demo : hashed with the current cost factor (from application.properties)
* - legacy : hashed with the old, weak cost factor 4, to demonstrate automatic hash upgrade
*/
@Component
public class DataInitializer implements CommandLineRunner {
private final AppUserRepository userRepository;
private final PasswordEncoder passwordEncoder;
public DataInitializer(AppUserRepository userRepository, PasswordEncoder passwordEncoder) {
this.userRepository = userRepository;
this.passwordEncoder = passwordEncoder;
}
@Override
public void run(String... args) {
if (userRepository.count() > 0) {
return;
}
userRepository.save(user("Demo User", "demo", "demo@example.com",
passwordEncoder.encode("Demo@1234")));
userRepository.save(user("Legacy User", "legacy", "legacy@example.com",
new BCryptPasswordEncoder(4).encode("Legacy@123")));
}
private AppUser user(String fullName, String username, String email, String passwordHash) {
AppUser user = new AppUser();
user.setFullName(fullName);
user.setUsername(username);
user.setEmail(email);
user.setPassword(passwordHash);
return user;
}
}
package com.example.securereg.service;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
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.PasswordEncoder;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.security.web.SecurityFilterChain;
import java.io.IOException;
@Configuration
public class SecurityConfig {
// Used by HTTP Basic (wrong username / password) and by exception handling (no login sent),
// so every authentication failure returns the same JSON message.
private static final AuthenticationEntryPoint ENTRY_POINT = (request, response, ex) ->
writeJson(response, 401, "Unauthorized", "Invalid username or password");
/**
* THE most important bean of this topic. Spring Security uses this encoder
* for every password it checks. The cost factor comes from application.properties.
*/
@Bean
public PasswordEncoder passwordEncoder(@Value("${app.security.bcrypt-strength:10}") int strength) {
return new BCryptPasswordEncoder(strength);
}
@Bean
public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
http
.csrf(csrf -> csrf.disable())
.sessionManagement(session -> session.sessionCreationPolicy(SessionCreationPolicy.STATELESS))
.authorizeHttpRequests(auth -> auth
.requestMatchers("/error", "/api/public/**", "/api/auth/**").permitAll()
.anyRequest().authenticated())
.httpBasic(basic -> basic.authenticationEntryPoint(ENTRY_POINT))
.exceptionHandling(ex -> ex
.authenticationEntryPoint(ENTRY_POINT)
.accessDeniedHandler((request, response, accessDeniedException) ->
writeJson(response, 403, "Forbidden", "You do not have permission to access this resource")));
return http.build();
}
private static void writeJson(HttpServletResponse response, int status, String error, String message)
throws IOException {
response.setStatus(status);
response.setContentType("application/json");
response.getWriter().write("{\"status\":" + status
+ ",\"error\":\"" + error + "\",\"message\":\"" + message + "\"}");
}
}
package com.example.securereg.service;
import com.example.securereg.entity.AppUser;
import com.example.securereg.repository.AppUserRepository;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsPasswordService;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import java.nio.charset.StandardCharsets;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Optional;
import java.util.regex.Pattern;
/**
* All password work happens here:
* encode() -> turn a raw password into a BCrypt hash (registration, password change)
* matches() -> check a raw password against the stored hash (login, password change)
*/
@Service
public class UserService implements UserDetailsService, UserDetailsPasswordService {
// at least one lowercase, one uppercase, one digit, one special character, minimum 8 characters
private static final Pattern STRONG_PASSWORD =
Pattern.compile("^(?=.*[a-z])(?=.*[A-Z])(?=.*\\d)(?=.*[^A-Za-z0-9]).{8,}$");
// BCrypt only uses the first 72 bytes of a password
private static final int BCRYPT_MAX_BYTES = 72;
private final AppUserRepository userRepository;
private final PasswordEncoder passwordEncoder;
public UserService(AppUserRepository userRepository, PasswordEncoder passwordEncoder) {
this.userRepository = userRepository;
this.passwordEncoder = passwordEncoder;
}
// ---------------- REGISTRATION: store the hash, never the password ----------------
public AppUser register(AppUser user) {
if (isBlank(user.getFullName()) || isBlank(user.getUsername())
|| isBlank(user.getEmail()) || isBlank(user.getPassword())) {
throw new IllegalArgumentException("fullName, username, email and password are required");
}
if (userRepository.existsByUsername(user.getUsername())) {
throw new IllegalArgumentException("Username already exists");
}
if (userRepository.existsByEmail(user.getEmail())) {
throw new IllegalArgumentException("Email already registered");
}
validatePassword(user.getPassword());
user.setId(null);
user.setPassword(passwordEncoder.encode(user.getPassword())); // BCrypt hash with random salt
return userRepository.save(user);
}
// ---------------- VERIFICATION: matches() compares raw password with the stored hash ----------------
// Returns empty if the login failed, otherwise true when the old hash was upgraded to the current cost
public Optional<Boolean> verifyLogin(String username, String rawPassword) {
if (isBlank(username) || isBlank(rawPassword)) {
return Optional.empty();
}
return userRepository.findByUsername(username)
.filter(user -> passwordEncoder.matches(rawPassword, user.getPassword()))
.map(user -> {
boolean upgrade = passwordEncoder.upgradeEncoding(user.getPassword());
if (upgrade) {
user.setPassword(passwordEncoder.encode(rawPassword)); // re-hash with the stronger cost
userRepository.save(user);
}
return upgrade;
});
}
public void changePassword(String username, String currentPassword, String newPassword) {
AppUser user = getByUsername(username);
if (isBlank(currentPassword) || isBlank(newPassword)) {
throw new IllegalArgumentException("currentPassword and newPassword are required");
}
if (!passwordEncoder.matches(currentPassword, user.getPassword())) {
throw new IllegalArgumentException("Current password is incorrect");
}
if (passwordEncoder.matches(newPassword, user.getPassword())) {
throw new IllegalArgumentException("New password must be different from the current password");
}
validatePassword(newPassword);
user.setPassword(passwordEncoder.encode(newPassword));
userRepository.save(user);
}
// ---------------- HASH DEMO: same password, different hash every time (random salt) ----------------
public Map<String, Object> hashDemo(String rawPassword) {
if (isBlank(rawPassword)) {
throw new IllegalArgumentException("password is required");
}
checkLength(rawPassword);
String hash1 = passwordEncoder.encode(rawPassword);
String hash2 = passwordEncoder.encode(rawPassword);
Map<String, Object> result = new LinkedHashMap<>();
result.put("hash1", hash1);
result.put("hash2", hash2);
result.put("hashesAreEqual", hash1.equals(hash2));
result.put("hash1Matches", passwordEncoder.matches(rawPassword, hash1));
result.put("hash2Matches", passwordEncoder.matches(rawPassword, hash2));
result.put("wrongPasswordMatches", passwordEncoder.matches(rawPassword + "x", hash1));
result.put("algorithmVersion", hash1.substring(0, 3));
result.put("costFactor", Integer.parseInt(hash1.substring(4, 6)));
result.put("saltPart", hash1.substring(7, 29));
result.put("hashPart", hash1.substring(29));
return result;
}
// ---------------- PROFILE ----------------
public Map<String, Object> getProfile(String username) {
AppUser user = getByUsername(username);
String hash = user.getPassword();
Map<String, Object> result = new LinkedHashMap<>();
result.put("username", user.getUsername());
result.put("fullName", user.getFullName());
result.put("email", user.getEmail());
result.put("hashAlgorithm", hash.substring(0, 3));
result.put("hashCost", Integer.parseInt(hash.substring(4, 6)));
result.put("hashLength", hash.length());
return result;
}
public AppUser getByUsername(String username) {
return userRepository.findByUsername(username)
.orElseThrow(() -> new UsernameNotFoundException("User not found: " + username));
}
// ---------------- Spring Security integration ----------------
// Spring Security calls this on every HTTP Basic login, then runs matches() itself
@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
AppUser user = getByUsername(username);
return User.withUsername(user.getUsername())
.password(user.getPassword())
.roles("USER")
.build();
}
// Spring Security calls this after a successful login when the stored hash uses an older, weaker
// cost than the current setting. "newPassword" is already the new BCrypt hash.
@Override
public UserDetails updatePassword(UserDetails user, String newPassword) {
AppUser appUser = getByUsername(user.getUsername());
appUser.setPassword(newPassword);
userRepository.save(appUser);
return User.withUserDetails(user).password(newPassword).build();
}
// ---------------- helpers ----------------
private void validatePassword(String password) {
checkLength(password);
if (!STRONG_PASSWORD.matcher(password).matches()) {
throw new IllegalArgumentException(
"Password must be at least 8 characters and contain an uppercase letter, "
+ "a lowercase letter, a digit and a special character");
}
}
private void checkLength(String password) {
if (password.getBytes(StandardCharsets.UTF_8).length > BCRYPT_MAX_BYTES) {
throw new IllegalArgumentException("Password must not be longer than 72 bytes (BCrypt limit)");
}
}
private boolean isBlank(String value) {
return value == null || value.trim().isEmpty();
}
}
package com.example.securereg.controller;
import com.example.securereg.entity.AppUser;
import com.example.securereg.service.UserService;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Optional;
/**
* Public URLs (no login needed): registration, password verification demo, BCrypt hash demo.
*/
@RestController
@RequestMapping("/api")
public class AuthController {
private final UserService userService;
public AuthController(UserService userService) {
this.userService = userService;
}
// Registration: the password is hashed with BCrypt before it is saved
@PostMapping("/auth/register")
public ResponseEntity<?> register(@RequestBody AppUser user) {
try {
AppUser saved = userService.register(user);
return ResponseEntity.status(HttpStatus.CREATED).body(saved);
} catch (IllegalArgumentException ex) {
return ResponseEntity.badRequest().body(Map.of("error", ex.getMessage()));
}
}
// Verification demo: userService.verifyLogin() uses passwordEncoder.matches()
@PostMapping("/auth/login")
public ResponseEntity<?> login(@RequestBody Map<String, String> credentials) {
Optional<Boolean> result = userService.verifyLogin(credentials.get("username"), credentials.get("password"));
if (result.isEmpty()) {
return ResponseEntity.status(HttpStatus.UNAUTHORIZED)
.body(Map.of("error", "Invalid username or password"));
}
Map<String, Object> body = new LinkedHashMap<>();
body.put("message", "Password verified successfully");
body.put("username", credentials.get("username"));
body.put("hashUpgraded", result.get());
return ResponseEntity.ok(body);
}
// Hash demo: shows that one password gives a different BCrypt hash every time
// (public only for this lesson: BCrypt is slow on purpose, so do not expose this in production)
@PostMapping("/public/hash-demo")
public ResponseEntity<?> hashDemo(@RequestBody Map<String, String> body) {
try {
return ResponseEntity.ok(userService.hashDemo(body.get("password")));
} catch (IllegalArgumentException ex) {
return ResponseEntity.badRequest().body(Map.of("error", ex.getMessage()));
}
}
@GetMapping("/public/info")
public Map<String, String> info() {
return Map.of(
"system", "Secure User Registration System",
"message", "Public endpoint - no login required");
}
}
package com.example.securereg.controller;
import com.example.securereg.service.UserService;
import org.springframework.http.ResponseEntity;
import org.springframework.security.core.Authentication;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.Map;
/**
* Protected URLs: HTTP Basic login. Spring Security itself calls
* passwordEncoder.matches() to verify the password in the Authorization header.
*/
@RestController
@RequestMapping("/api/users")
public class UserController {
private final UserService userService;
public UserController(UserService userService) {
this.userService = userService;
}
@GetMapping("/me")
public Map<String, Object> me(Authentication authentication) {
return userService.getProfile(authentication.getName());
}
@PutMapping("/me/password")
public ResponseEntity<?> changePassword(@RequestBody Map<String, String> body, Authentication authentication) {
try {
userService.changePassword(authentication.getName(),
body.get("currentPassword"), body.get("newPassword"));
return ResponseEntity.ok(Map.of("message", "Password changed successfully"));
} catch (IllegalArgumentException ex) {
return ResponseEntity.badRequest().body(Map.of("error", ex.getMessage()));
}
}
}
package com.example.securereg;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class SecureUserRegistrationApplication {
public static void main(String[] args) {
SpringApplication.run(SecureUserRegistrationApplication.class, args);
}
}
spring.application.name=secure-user-registration-system
server.port=8080
# MySQL (database is created automatically if it does not exist)
spring.datasource.url=jdbc:mysql://localhost:3306/secure_registration_db?createDatabaseIfNotExist=true&useSSL=false&allowPublicKeyRetrieval=true&serverTimezone=UTC
spring.datasource.username=root
spring.datasource.password=password
# JPA / Hibernate
spring.jpa.hibernate.ddl-auto=update
spring.jpa.show-sql=false
# BCrypt cost factor (strength). Each +1 doubles the hashing time.
# 10 is the Spring default, 12 is a common choice for new applications. Allowed range: 4 to 31.
app.security.bcrypt-strength=12
Code language: PHP (php)
Step 4: Run SevureUserRegistrationApplication


