Encode, Decode, Validate using BCryptPasswordEncoder in Spring Boot Security

In spring boot, BCryptPasswordEncoder is one of the password encoders used in the spring boot security module for password encoding and password decoding or validate. BCryptPasswordEncoder is using the BCrypt algorithm. BCrypt is a one-way encryption algorithm. In this article, we’ll see what the BCryptPasswordEncoder is and how to encrypt using the BCryptPasswordEncoder, decrypt using the BCryptPasswordEncoder in spring boot security.

In spring boot security, BCryptPasswordEncoder works with various configurable parameters that determine the complexity of the algorithm. Such parameters are defined in the BCryptPasswordEncoder class constructor. The key parameters are strength, BCrypt version, Secure Random.



BCryptPasswordEncoder Constructors

There are different flavors of constructors available for the BCryptPasswordEncoder class using the 3 parameters described above. The code below shows the numerous constructors available in the BCryptPasswordEncoder class.

BCryptPasswordEncoder()
BCryptPasswordEncoder(int strength)
BCryptPasswordEncoder(BCryptVersion version)
BCryptPasswordEncoder(BCryptVersion version, SecureRandom random)
BCryptPasswordEncoder(int strength, SecureRandom random)
BCryptPasswordEncoder(BCryptVersion version, int strength)
BCryptPasswordEncoder(BCryptVersion version, int strength, SecureRandom random)

strength - any value in between 4 and 31
version  - values are BCryptVersion.$2A, BCryptVersion.$2Y, BCryptVersion.$2B
random   - Object of SecureRandom class


Password Encode using BCryptPasswordEncoder

In the real-time application, the password is encrypted using the BCryptPasswordEncoder and the encrypted password is stored in the database. If the customer states that they do not recall their password, an encrypted password must be created and stored in the database again.

BCryptPasswordEncoder is a password encoder that is available in spring boot security. If a raw password is given to the encode method, the password will be encoded using BCrypt algorithm and returned with a encrypted password.

pom.xml

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

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

.................

SpringBootSecurityPasswordEncoderApplication.java

package com.yawintutor;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;

@SpringBootApplication
public class SpringBootSecurityPasswordEncoderApplication {

	public static void main(String[] args) {
		SpringApplication.run(SpringBootSecurityPasswordEncoderApplication.class, args);

		BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
		String password = "yawinpassword";
		String encodedPassword = passwordEncoder.encode(password);
		System.out.println();
		System.out.println("Password is         : " + password);
		System.out.println("Encoded Password is : " + encodedPassword);
	}
}

Output

  .   ____          _            __ _ _
 /\\ / ___'_ __ _ _(_)_ __  __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
 \\/  ___)| |_)| | | | | || (_| |  ) ) ) )
  '  |____| .__|_| |_|_| |_\__, | / / / /
 =========|_|==============|___/=/_/_/_/
 :: Spring Boot ::        (v2.2.4.RELEASE)

2020-02-20 18:03:35.418  INFO 26060 --- [           main] ngBootSecurityPasswordEncoderApplication : Starting SpringBootSecurityPasswordEncoderApplication on banl1691b9157 with PID 26060 (/Users/test/STS/workspace/SpringBootSecurityPasswordEncoder/target/classes started by test in /Users/test/STS/workspace/SpringBootSecurityPasswordEncoder)
2020-02-20 18:03:35.421  INFO 26060 --- [           main] ngBootSecurityPasswordEncoderApplication : No active profile set, falling back to default profiles: default
2020-02-20 18:03:35.858  INFO 26060 --- [           main] ngBootSecurityPasswordEncoderApplication : Started SpringBootSecurityPasswordEncoderApplication in 0.664 seconds (JVM running for 3.197)

Password is         : yawinpassword
Encoded Password is : $2a$04$MzVXtd4o0y4DOlyHMMLMDeE4/eezrsT5Xad.2lmGr/NkCpwBgvn3e


Password Decode using BCryptPasswordEncoder

BCryptPasswordEncoder is a single-way password encoder. The one-way encoding algorithm is used to encrypt a password. There’s no way to decrypt the password. Alternatively, the one-way password encoder returns the same encrypted string if you call the encoding algorithm with the same password.

The authentication can be accomplished by re-encoding the password and checking the current encoded password in the database. The program below will demonstrate how to verify your password using the BCryptPasswordEncoder.

BCryptPasswordEncoder allows you to check your password using matches() api. We need to pass the actual raw password and the encrypted password. It returns true if the password matches the encrypted password, otherwise it returns false.

pom.xml

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

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

.................

SpringBootSecurityPasswordEncoderApplication.java

package com.yawintutor;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;

@SpringBootApplication
public class SpringBootSecurityPasswordEncoderApplication {

	public static void main(String[] args) {
		SpringApplication.run(SpringBootSecurityPasswordEncoderApplication.class, args);

		BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
		String password = "yawinpassword";
		String encodedPassword = passwordEncoder.encode(password);
		System.out.println();
		System.out.println("Password is         : " + password);
		System.out.println("Encoded Password is : " + encodedPassword);
		System.out.println();

		boolean isPasswordMatch = passwordEncoder.matches(password, encodedPassword);
		System.out.println("Password : " + password + "   isPasswordMatch    : " + isPasswordMatch);

		password = "yawin";
		isPasswordMatch = passwordEncoder.matches(password, encodedPassword);
		System.out.println("Password : " + password + "           isPasswordMatch    : " + isPasswordMatch);
	}

}

Output


  .   ____          _            __ _ _
 /\\ / ___'_ __ _ _(_)_ __  __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
 \\/  ___)| |_)| | | | | || (_| |  ) ) ) )
  '  |____| .__|_| |_|_| |_\__, | / / / /
 =========|_|==============|___/=/_/_/_/
 :: Spring Boot ::        (v2.2.4.RELEASE)

2020-02-20 19:28:20.910  INFO 32203 --- [           main] ngBootSecurityPasswordEncoderApplication : Starting SpringBootSecurityPasswordEncoderApplication on banl1691b9157 with PID 32203 (/Users/test/STS/workspace/SpringBootSecurityPasswordEncoder/target/classes started by test in /Users/test/STS/workspace/SpringBootSecurityPasswordEncoder)
2020-02-20 19:28:20.913  INFO 32203 --- [           main] ngBootSecurityPasswordEncoderApplication : No active profile set, falling back to default profiles: default
2020-02-20 19:28:21.456  INFO 32203 --- [           main] ngBootSecurityPasswordEncoderApplication : Started SpringBootSecurityPasswordEncoderApplication in 0.842 seconds (JVM running for 3.49)

Password is         : yawinpassword
Encoded Password is : $2a$10$DcSMNWX9S5DiP4i3OjjIbe4P0Gws4VQ609L0TQHqXlGYhhB/pylYa

Password : yawinpassword   isPasswordMatch    : true
Password : yawin           isPasswordMatch    : false



Related Articles

Leave a Reply

Your email address will not be published. Required fields are marked *