Spring Boot Tutorial 0/110 lessons ~6 min read Lesson 44

    Password Encryption

    Never store Orders passwords in plaintext.

    Course progress0%
    Focus
    12 guided sections
    Practice signal
    Examples included
    Career prep
    Interview Q&A included

    Introduction

    Never store Orders passwords in plaintext. Never use plain SHA-256 as a password hash. Use a slow, salted, adaptive algorithm via Spring Security's PasswordEncoder — typically BCrypt (BCryptPasswordEncoder), with Argon2 as a modern alternative when you standardize on it.

    On signup, encode the raw password once and persist only the hash. On login, matches(raw, hash) — do not re-encode and compare strings manually.

    Strength (cost factor) trades CPU for brute-force resistance. Tune for roughly a few hundred milliseconds per hash on your hardware class, and revisit as CPUs improve.

    Examples here use placeholders only — never commit real user passwords or production encoder secrets.

    Purpose of this lesson

    Hash and verify Orders credentials with BCryptPasswordEncoder as the PasswordEncoder bean.

    Understanding the topic

    Adaptive hashing beats fast digests for passwords.

    • PasswordEncoder: Spring's abstraction for encode/matches.
    • BCrypt: salted, costly, widely supported default choice.
    • encode: signup / password-change path only.
    • matches: login path; constant-time aware comparison inside the encoder.
    • Delegation: DelegatingPasswordEncoder supports migrating algorithms via id prefixes.

    Step-by-step explanation

    1. Declare @Bean PasswordEncoder passwordEncoder() { return new BCryptPasswordEncoder(12); }.
    2. On registration, store passwordEncoder.encode(raw) only.
    3. On authentication, rely on DaoAuthenticationProvider or call matches explicitly.
    4. Add rate limiting on login to complement slow hashes.

    Informative example

    BCrypt bean and usage.

    java
    @Configuration
    public class PasswordConfig {
    @Bean
    PasswordEncoder passwordEncoder() {
    return new BCryptPasswordEncoder(12);
    }
    }
    // registration
    String hash = passwordEncoder.encode(rawPassword);
    user.setPasswordHash(hash);
    // manual check (usually AuthenticationManager does this)
    if (!passwordEncoder.matches(submittedRaw, user.getPasswordHash())) {
    throw new BadCredentialsException("invalid");
    }

    Real-world use

    A legacy TechLearningPRO demo database once stored SHA-256 hex passwords. After a backup leak, credentials were trivial to crack. Migrating to BCrypt with DelegatingPasswordEncoder allowed verifying old ids while re-hashing to BCrypt on successful login — closing the window without a mass reset overnight.

    Security implications

    Password storage failures are catastrophic.

    • Never put sample passwords that look real in docs — use ChangeMe!-style test doubles only in local seeds.
    • Hashes still deserve access control; treat the user table as sensitive.
    • Force reset flows over email with single-use tokens, not recoverable encryption of passwords.

    Best practices

    • One shared PasswordEncoder bean for the app.
    • Re-hash on login when upgrading cost factor or algorithm.
    • Combine with lockout/rate limits and breach-password checks where appropriate.

    Common mistakes

    • Logging raw passwords or full hashes in debug statements.
    • Using a fast general-purpose hash for passwords.
    • Truncating passwords before hashing (silently weakening entropy).

    Advanced interview questions

    Interview Prep

    Practice concise answers, then expand each card for the explanation.

    3 questions
    1BeginnerQuestionWhy is BCrypt preferred over SHA-256 for passwords?+

    Answer

    BCrypt is deliberately slow and salted, which frustrates brute-force; SHA-256 is fast and unsuitable alone for password storage.
    2BeginnerQuestionWhat does PasswordEncoder.matches do?+

    Answer

    It verifies a raw password against a stored encoded hash using the algorithm embedded in that hash.
    3IntermediateQuestionHow do you migrate hashing algorithms?+

    Answer

    Use DelegatingPasswordEncoder with id prefixes and re-encode to the new algorithm on successful authentication.

    Hands-on exercise

    Lab. Register a user with BCrypt cost 12. Verify matches succeeds for the correct password and fails for a wrong one. Inspect the stored hash prefix ($2a$ / $2b$) and note the cost segment.

    Summary

    Password encryption protects Orders accounts at rest. Next: how security filters implement these checks in the request pipeline.

    Ready to mark this lesson complete?Track your journey across the entire course.