HomeContact

(Java)- Encrypting a string from Java to BCrypt

Published in Java
April 02, 2023
1 min read

What is BCrypt?

It is a password-hashing function published in 1999. It is an encryption function designed based on the Blowfish password and is one of the most powerful hash mechanisms in use to date. Since it is possible to slow down the operation speed by increasing the number of repetitions, it is possible to prepare for brute-forece attacks even if the operation capacity increases.

It can be used for encryption when storing password DB.

Add to dependency to write the spring-security-crypto.jar library.

<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-crypto</artifactId>
<version>5.1.5.RELEASE</version>
</dependency>

Sample Source Code

import org.springframework.security.crypto.bcrypt.BCrypt;
public class BCryptTest {
public static void main(String[] args) {
String password = "target text";
// Encrypt password to save to your DB
String encrypted = BCrypt.hashpw(password, BCrypt.gensalt());
System.out.println("encrypted : " + encrypted);
// Checkpw validation with encrypted string stored in the DB and password entered by the user at login
System.out.println(BCrypt.checkpw(password, encrypted)); // true
System.out.println(BCrypt.checkpw(password + "1", encrypted)); // false
}
}


Tags

#java#Encrypt

Share


Previous Article
Linux tail command

Topics

Java
Other
Server

Related Posts

Copying files to Java NIO (Files & Path)
April 11, 2023
1 min