In your application, you need to securely store user passwords. What approach would you take to implement password encoding in Spring Security? Discuss the choice of encoding algorithm and how to verify passwords during authentication.

Secure password storage in Spring Security relies on the PasswordEncoder abstraction, with BCrypt as the recommended algorithm because it's a slow, salted, one-way hash specifically designed to resist brute-force and rainbow-table attacks.

Key Points: • BCryptPasswordEncoder automatically generates and embeds a random salt per password, so identical passwords produce different hashes. • Its configurable work factor (strength) lets you tune hashing cost as hardware gets faster, keeping brute-forcing expensive. • Never store raw or reversibly-encrypted passwords—hashing must be one-way. • encode() is used when registering or changing a password; matches() is used during login to compare the raw input against the stored hash. • Spring Security's DaoAuthenticationProvider uses the configured PasswordEncoder automatically during the standard authentication flow.

Example: On registration, the raw password is hashed with BCryptPasswordEncoder before saving to the database; at login, the raw password entered is never compared directly—matches() re-hashes it with the stored salt and compares digests.

Code Example:

PasswordEncoder passwordEncoder = new BCryptPasswordEncoder();

// Registration
String encodedPassword = passwordEncoder.encode(rawPassword);
userRepository.save(new User(username, encodedPassword));

// Login verification
boolean isMatch = passwordEncoder.matches(rawPassword, storedEncodedPassword);

Interview Tip: A concise interview answer is:

"I'd use Spring Security's PasswordEncoder interface with BCryptPasswordEncoder, which salts and hashes passwords automatically with a tunable work factor. Passwords are hashed with encode() at registration and never stored raw, and matches() re-hashes the login attempt to compare against the stored hash during authentication."