← Back to Questions
Spring Boot

What is BCryptPasswordEncoder?

Learn What is BCryptPasswordEncoder? with simple explanations, real-time examples, interview tips and practical use cases.

What is BCryptPasswordEncoder in Spring Security?

BCryptPasswordEncoder is a password hashing implementation provided by Spring Security that securely encodes user passwords before storing them in the database.

It uses the BCrypt hashing algorithm, which is one of the most secure and widely recommended algorithms for password protection in modern applications.

In simple words, BCryptPasswordEncoder converts plain-text passwords into secure hashed values so attackers cannot easily read or misuse them.


Why BCryptPasswordEncoder is Important

Storing passwords directly in the database is extremely dangerous.

Example of insecure storage:

username: naresh
password: admin123

If hackers access the database:

  • All passwords become visible
  • User accounts can be hacked
  • Personal data may be stolen
  • Major security breaches can occur

BCryptPasswordEncoder protects passwords using secure hashing.


What is BCrypt?

BCrypt is a strong password hashing algorithm designed specifically for secure password storage.

BCrypt provides:

  • One-way hashing
  • Automatic salt generation
  • Brute-force attack resistance
  • Strong password protection

What is One-Way Hashing?

One-way hashing means:

  • Password can be converted into hash
  • Original password cannot easily be recovered

Example:

admin123
→
$2a$10$8kD2Hf9L0kP3xY...

Why BCrypt is Better Than Simple Hashing

Older hashing algorithms like:

  • MD5
  • SHA-1

are no longer considered secure for passwords.

BCrypt is stronger because:

  • It uses salt automatically
  • It is computationally expensive
  • It slows down brute-force attacks

Spring Security BCryptPasswordEncoder Class

BCryptPasswordEncoder

implements:

PasswordEncoder

Spring Security Dependency

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-security</artifactId>
</dependency>

Create BCryptPasswordEncoder Bean

@Bean
public PasswordEncoder passwordEncoder() {

    return new BCryptPasswordEncoder();
}

Encoding Password Example

String encodedPassword =
        passwordEncoder.encode("admin123");

System.out.println(encodedPassword);

Example Output

$2a$10$Kf8Jx9L2pQ7VnD3eR5yT8uA0...

Important Observation

Every time BCrypt encodes the same password, the generated hash becomes different.

Example:

admin123
→ $2a$10$abc...

admin123
→ $2a$10$xyz...

Why Does BCrypt Generate Different Hashes?

BCrypt automatically generates:

Salt

Salt is random data added before hashing the password.


What is Salt?

Salt improves password security by making hashes unique.

Even if two users have the same password:

  • Their hashes become different

Benefits of Salt

  • Prevents rainbow table attacks
  • Prevents duplicate password detection
  • Improves password security

Password Verification Example

BCrypt uses:

matches()

method for authentication.

boolean result =
        passwordEncoder.matches(
                "admin123",
                encodedPassword
        );

System.out.println(result);

Output

true

How BCrypt Verification Works

  1. User enters password
  2. Spring Security extracts salt from stored hash
  3. Password is hashed again
  4. Hashes are compared
  5. Authentication succeeds or fails

BCrypt Hash Structure

Example:

$2a$10$Kf8Jx9L2pQ7VnD3eR5yT8uA0...

Meaning of Parts

Part Description
$2a$ BCrypt algorithm version
10 Strength/work factor
Remaining Part Salt + Hashed password

What is Strength or Work Factor?

BCrypt allows configuring hashing complexity.

Higher strength means:

  • More secure hashing
  • Slower processing
  • Harder brute-force attacks

Custom Strength Example

@Bean
public PasswordEncoder passwordEncoder() {

    return new BCryptPasswordEncoder(12);
}

Default Strength

Default BCrypt strength:

10

Recommended Strength

Strength Usage
10 Default production use
12 Higher security
14+ Very high security systems

User Registration Example

@Service
public class UserService {

    @Autowired
    private PasswordEncoder passwordEncoder;

    @Autowired
    private UserRepository userRepository;

    public void register(RegisterRequest request) {

        User user = new User();

        user.setUsername(request.getUsername());

        user.setPassword(
                passwordEncoder.encode(
                        request.getPassword()
                )
        );

        userRepository.save(user);
    }
}

Database Example

Username Password
naresh $2a$10$8Kf9P...

Authentication Flow with BCrypt

  1. User registers
  2. Password is encoded using BCrypt
  3. Encoded password stored in database
  4. User logs in later
  5. matches() validates password
  6. Authentication succeeds

BCrypt in JWT Authentication

JWT authentication still uses BCrypt for validating user credentials.

Login flow:

  1. User enters username and password
  2. BCrypt validates password
  3. JWT token is generated

Advantages of BCryptPasswordEncoder

  • Strong password hashing
  • Automatic salt generation
  • Protection against rainbow table attacks
  • Slows brute-force attacks
  • Widely recommended
  • Industry-standard security

Disadvantages of BCrypt

  • Slower than simple hashing algorithms
  • High strength increases CPU usage
  • Improper configuration may affect performance

BCrypt vs MD5

Feature BCrypt MD5
Security Very Strong Weak
Salt Support Automatic No
Brute Force Resistance High Low
Recommended Yes No

BCrypt vs SHA-256

Feature BCrypt SHA-256
Purpose Password hashing General hashing
Salt Support Automatic Manual
Brute Force Protection High Lower

Common Security Risks Without BCrypt

Risk Solution
Plain-text passwords Use BCrypt
Password leaks Hash passwords securely
Rainbow table attacks Use salt
Brute-force attacks Increase work factor

Best Practices for BCryptPasswordEncoder

  • Always use BCrypt in production
  • Never store plain-text passwords
  • Use strong password policies
  • Store passwords only after encoding
  • Use HTTPS for login APIs
  • Do not expose password fields in responses

Common Interview Questions on BCryptPasswordEncoder

What is BCryptPasswordEncoder?

BCryptPasswordEncoder is a Spring Security class used for secure password hashing.

Why is BCrypt recommended?

BCrypt automatically generates salt and provides strong protection against brute-force attacks.

What is the purpose of salt in BCrypt?

Salt makes hashes unique and prevents rainbow table attacks.

Why does BCrypt generate different hashes for the same password?

Because BCrypt generates random salt automatically.

What is the purpose of matches()?

matches() compares raw password with encoded password securely.


Conclusion

BCryptPasswordEncoder is one of the most important security components in Spring Security.

It provides secure password hashing, automatic salt generation, and strong protection against password attacks.

BCrypt is widely used in enterprise applications, banking systems, REST APIs, authentication systems, and microservices.

Understanding BCryptPasswordEncoder is essential for Spring Boot developers because secure password storage is mandatory in modern application security.

Why this Spring Boot question is important?

This interview question helps candidates understand real-time backend development concepts, practical problem solving, coding fundamentals, system design basics and production-ready application behavior.

Practice this question carefully for Java backend roles, Spring Boot developer interviews, microservices interviews, company interviews and full-stack developer preparation.

About the Author

Naresh Kumar is a Senior Java Backend Engineer with experience building enterprise applications using Java, Spring Boot, Microservices, Docker, Kubernetes and Cloud technologies.