# Password Encoding with BCrypt in Spring Security

> How should passwords be stored in a Spring Boot application, and why is BCrypt used instead of plain hashing?

Canonical: https://www.internhack.in/learn/interview/spring-boot-interview/spring-security-password-encoding
Last updated: 2026-11-28

Difficulty: Intermediate

## Question

How should passwords be stored in a Spring Boot application, and why is BCrypt used instead of plain hashing?

## Answer

The first rule of storing passwords is that you never store passwords. You store a one-way transformation of them, so even if your database leaks, attackers cannot simply read them. The interesting part of this question is how good that transformation needs to be, and why MD5 or SHA-256 alone are not enough.

A hash function turns any input into a fixed-size output and cannot be reversed directly. The problem is speed. General hash functions like SHA-256 are designed to be fast, which is great for checksums and terrible for passwords, because an attacker with a GPU can try billions of guesses per second against a leaked hash. Attackers also use rainbow tables, precomputed lists of hashes for common passwords. Two protections address these problems. Salting adds a random value to each password before hashing, so identical passwords produce different hashes, and precomputed tables become useless. Work factor makes each hash deliberately slow, so guessing costs real time.

BCrypt provides both. It generates a random salt automatically, embeds it in the output string, and takes a cost factor, called strength in Spring, default 10, meaning 2 to the power 10 rounds. Raising the cost by one doubles the time. A typical BCrypt result looks like $2a$10$ followed by 22 characters of salt and 31 of hash, so the algorithm version, cost, salt, and hash all live in one string and you need no separate salt column. Two hashes of the same password differ, so you cannot compare with equals; you call encoder.matches(raw, stored), which extracts the salt and cost from the stored value and recomputes.

In Spring Security you expose a PasswordEncoder bean, usually new BCryptPasswordEncoder(). You call encode when registering or changing a password, and DaoAuthenticationProvider uses matches during login. Spring also offers DelegatingPasswordEncoder, created by PasswordEncoderFactories.createDelegatingPasswordEncoder(), which prefixes hashes with an id like {bcrypt} so you can migrate to newer algorithms such as Argon2 or SCrypt over time without breaking old users. This is a good point to mention for long-lived systems, together with upgradeEncoding, which lets you re-hash a password on successful login when the cost or algorithm changes.

Some operational advice. BCrypt truncates input at 72 bytes, so very long passphrases beyond that are cut, and some teams pre-hash. Choose a cost that takes roughly a quarter second on your production hardware. Never log passwords, never return the hash from an API, and mark password fields with @JsonIgnore or keep them out of DTOs. Enforce minimum length and check against breached password lists. Add rate limiting and account lockout for login endpoints to slow online guessing, because hashing only protects data at rest.

Also distinguish encoding, encryption, and hashing in the interview. Encoding such as Base64 is reversible and offers no security. Encryption is reversible with a key and is right for data you must read back. Hashing is one-way and right for passwords. Saying the wrong word here is a red flag, even though Spring's own interface is unfortunately named PasswordEncoder.

## Code examples

### Registering and verifying passwords

```
@Configuration
class PasswordConfig {
    @Bean
    PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder(12);          // cost factor 12
        // or: PasswordEncoderFactories.createDelegatingPasswordEncoder() for migrations
    }
}

@Service
@RequiredArgsConstructor
class AuthService {
    private final UserRepository users;
    private final PasswordEncoder encoder;

    public void register(String email, String rawPassword) {
        User u = new User();
        u.setEmail(email);
        u.setPasswordHash(encoder.encode(rawPassword)); // salted, slow hash
        users.save(u);
    }

    public boolean verify(String email, String rawPassword) {
        return users.findByEmail(email)
                .map(u -> encoder.matches(rawPassword, u.getPasswordHash()))
                .orElse(false);
    }
}
```

Never compare with equals; matches re-derives the hash using the salt inside the stored string.

## Key points

- BCrypt salts automatically and embeds the salt in the output.
- Cost factor doubles work per increment.
- DelegatingPasswordEncoder helps migrate algorithms over time.
- Encoding, encryption and hashing are three different things.

## Common follow-up questions

- Why not use SHA-256 for passwords?
- What is a rainbow table?
- How do you upgrade hashes when you raise the cost?

## Interview tips

- Explain salt and work factor separately, that is the crux.
- Distinguish hashing from encryption and encoding.

## Concepts covered

PasswordEncoder, BCrypt, Hashing, Salting

Previous: [Spring Security Filter Chain and JWT Authentication Flow](https://www.internhack.in/learn/interview/spring-boot-interview/spring-security-filter-chain-jwt) · Next: [Spring Boot Actuator for Production Monitoring](https://www.internhack.in/learn/interview/spring-boot-interview/spring-boot-actuator) · [All of Spring Boot](https://www.internhack.in/learn/interview/spring-boot-interview)

## More Spring Boot questions

- [Spring AOP: Aspects, Advice and Proxies](https://www.internhack.in/learn/interview/spring-boot-interview/spring-aop-basics)
- [Microservices with Spring Cloud: Service Discovery and API Gateway](https://www.internhack.in/learn/interview/spring-boot-interview/spring-cloud-discovery-gateway)
- [Circuit Breaker and Resilience4j](https://www.internhack.in/learn/interview/spring-boot-interview/spring-circuit-breaker-resilience4j)
- [Testing: @SpringBootTest vs @WebMvcTest vs @DataJpaTest](https://www.internhack.in/learn/interview/spring-boot-interview/spring-testing-slices)
- [Testing Controllers with MockMvc and Mockito](https://www.internhack.in/learn/interview/spring-boot-interview/spring-mockito-mockmvc-testing)
- [Circular Dependencies in Spring and How to Fix Them](https://www.internhack.in/learn/interview/spring-boot-interview/spring-circular-dependencies)

## Related

- [Learn](https://www.internhack.in/learn)
- [Interview Prep](https://www.internhack.in/learn/interview)
- [Spring Boot](https://www.internhack.in/learn/interview/spring-boot-interview)
