Password Encryption with BCryptPasswordEncoder in Spring Security

Learn how to implement password encryption with BCryptPasswordEncoder in Spring Security. This post covers why BCrypt is secure and how to use it for hashing passwords with real-world examples.

Password Encryption with BCryptPasswordEncoder in Spring Security

๐Ÿ” Why Use Password Encryption?

Storing plain-text passwords is a critical security risk. If your database is compromised, all user credentials are instantly exposed. That’s where password encryption comes in โ€” and BCryptPasswordEncoder is one of the most secure options available in Spring Security.

๐Ÿ” What is BCryptPasswordEncoder?

BCryptPasswordEncoder is a Spring Security class that implements the BCrypt hashing algorithm. It:

  • Adds a random salt to each password
  • Is adaptive, meaning you can increase its workload as hardware improves
  • Prevents rainbow table and brute force attacks

Using Password Encryption with BCryptPasswordEncoder helps ensure your user credentials remain secure, even if attackers access your database.

๐Ÿ“ฆ Maven Dependencies

Add the following dependencies in your pom.xml:



    org.springframework.boot
    spring-boot-starter-security


๐Ÿ“‚ Project Structure


com.kscodes.security.encryption
โ”œโ”€โ”€ config/
โ”‚   โ””โ”€โ”€ SecurityConfig.java
โ”œโ”€โ”€ controller/
โ”‚   โ””โ”€โ”€ UserController.java
โ”œโ”€โ”€ model/
โ”‚   โ””โ”€โ”€ UserDto.java
โ”œโ”€โ”€ service/
โ”‚   โ””โ”€โ”€ UserService.java
โ””โ”€โ”€ PasswordEncryptionApplication.java

๐Ÿงช Create a DTO for User Registration

UserDto.java


package com.kscodes.security.encryption.model;

public class UserDto {
    private String username;
    private String password;

    // Getters and setters
}

๐Ÿ”ง Create a Password Encoder Bean

SecurityConfig.java


package com.kscodes.security.encryption.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;

@Configuration
public class SecurityConfig {

    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder(); // Default strength = 10
    }
}

๐Ÿ’ก Password Encryption with BCryptPasswordEncoder (in action)

UserService.java


package com.kscodes.security.encryption.service;

import com.kscodes.security.encryption.model.UserDto;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

@Service
public class UserService {

    private final PasswordEncoder passwordEncoder;

    public UserService(PasswordEncoder passwordEncoder) {
        this.passwordEncoder = passwordEncoder;
    }

    public String register(UserDto userDto) {
        String encryptedPassword = passwordEncoder.encode(userDto.getPassword());

        // Simulate saving encrypted password to DB
        System.out.println("Encrypted password for user " + userDto.getUsername() + ": " + encryptedPassword);

        return encryptedPassword;
    }

    public boolean verifyPassword(String rawPassword, String hashedPassword) {
        return passwordEncoder.matches(rawPassword, hashedPassword);
    }
}

๐ŸŒ Expose Controller Endpoint

UserController.java


package com.kscodes.security.encryption.controller;

import com.kscodes.security.encryption.model.UserDto;
import com.kscodes.security.encryption.service.UserService;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/api/users")
public class UserController {

    private final UserService userService;

    public UserController(UserService userService) {
        this.userService = userService;
    }

    @PostMapping("/register")
    public String register(@RequestBody UserDto userDto) {
        return userService.register(userDto);
    }

    @GetMapping("/verify")
    public String verify(@RequestParam String raw, @RequestParam String encrypted) {
        boolean match = userService.verifyPassword(raw, encrypted);
        return match ? "Passwords match!" : "Invalid password!";
    }
}

๐Ÿงช Test the Flow

1. Register a user


curl -X POST http://localhost:8080/api/users/register \
  -H "Content-Type: application/json" \
  -d '{"username":"ketan", "password":"mysecret"}'

๐ŸŸข You will get a hashed password like:


$2a$10$w1XvfpD9XK1nsmJPmQCe1uvsPwOxfRPfA1jhCFcCD3uyI6V1c5F.O

Verify a password


curl "http://localhost:8080/api/users/verify?raw=mysecret&encrypted="

โœ… Output: Passwords match!

โš ๏ธ Best Practices for Password Encryption with BCryptPasswordEncoder

  • Never store raw passwords, not even temporarily.
  • Always store the encrypted hash returned by encode().
  • Use matches() to verify login attempts.
  • Optionally increase strength (e.g., new BCryptPasswordEncoder(12)) for more security (at the cost of CPU usage).
  • Regenerate passwords if your security policies change.

๐Ÿง  Summary

Using Password Encryption with BCryptPasswordEncoder in Spring Security helps protect your application from one of the most critical vulnerabilities โ€” password leaks. It’s a standard tool used by professionals to hash, store, and verify user passwords securely.

๐Ÿ“š References