BCrypt helps keep passwords safe by turning them into secret codes. This way, even if someone sees the code, they can't easily guess the original password.
0
0
Password encoding with BCrypt in Spring Boot
Introduction
When you want to store user passwords safely in a database.
When building a login system that checks passwords securely.
When you want to protect user accounts from hackers.
When you need to compare a typed password with a stored secret code.
When you want to follow security best practices in your app.
Syntax
Spring Boot
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
String encodedPassword = encoder.encode(rawPassword);
boolean matches = encoder.matches(rawPassword, encodedPassword);Use encode() to turn a plain password into a secure code.
Use matches() to check if a typed password matches the stored code.
Examples
This creates a secret code from the password "mySecret123".
Spring Boot
BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
String encoded = encoder.encode("mySecret123");This checks if the typed password matches the stored secret code.
Spring Boot
boolean isMatch = encoder.matches("mySecret123", encoded);You can set the strength (work factor) to 12 for more security but slower encoding.
Spring Boot
BCryptPasswordEncoder encoder = new BCryptPasswordEncoder(12);Sample Program
This program encodes a password and then checks if the original password matches the encoded one.
Spring Boot
package com.example.demo; import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; public class PasswordEncoderDemo { public static void main(String[] args) { BCryptPasswordEncoder encoder = new BCryptPasswordEncoder(); String rawPassword = "helloWorld"; String encodedPassword = encoder.encode(rawPassword); System.out.println("Raw password: " + rawPassword); System.out.println("Encoded password: " + encodedPassword); boolean matches = encoder.matches(rawPassword, encodedPassword); System.out.println("Password matches: " + matches); } }
OutputSuccess
Important Notes
Each time you encode the same password, the result looks different because BCrypt adds random salt.
Never store plain passwords, always store the encoded version.
Use a strength of 10 or higher for good security without slowing your app too much.
Summary
BCrypt turns passwords into secure codes to protect user data.
Use encode() to create the code and matches() to check passwords.
Always store encoded passwords, never plain text.