Article directory
foreword
The BCrypt algorithm is an algorithm based on a hash algorithm, so this algorithm is irreversible
1. What is the BCrypt algorithm?
The BCrypt algorithm is an algorithm based on a hash algorithm, so this algorithm is irreversible
The result of encoding by BCrypt algorithm, the length is fixed at 60 characters
Using the same original text for repeated encoding, the results obtained each time are different, because BCrypt uses a random salt during the encoding process, and the salt used is also saved as part of the encoding result
The diagram is as follows:
2. Use steps
1. Encrypt plaintext
Create a BCryptPasswordEncode class object and use the object.encode(plaintext) method to generate ciphertext
The code is as follows (example):
public void testEncode(){
BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
for (int i = 0; i < 5; i++) {
String rawPassword = "123456";
String encodedPassword = passwordEncoder.encode(rawPassword);
//在编码过程中,BCrypt使用了随机的盐
//所以每次得到的结果都不一致
log.debug("原文={},密文={}",rawPassword,encodedPassword);
//原文=123456,密文=$2a$10$xd.seKl0H3k/Ks72BoKJVO95yCvhhSy4u9nXzEOBOeJ7lxxke69Aq
//原文=123456,密文=$2a$10$2rfZBv4gjy4MeJ2h93VC3eARlVlBJRKje8UMMu9Ul4JV6FG.OPTxy
//原文=123456,密文=$2a$10$dGSHSIhvwnflGBIrdNsTwusPpvNbvjxzwz10mg3RTVrfR1sxhKmda
//原文=123456,密文=$2a$10$NUFTdtD1/rcA7d4qzpQ3PecDEIvzTp7HeuFl8gv7zcg1O/kw0vNqq
//原文=123456,密文=$2a$10$3CjSrCyMv/imDsJiJvwOVOxuNcaUOppExXg5kZLA1DJ0nZ/7aw48G
}
}
2. Verification
Use the object.matches(plaintext, ciphertext) to verify whether it matches. Since the salt is stored in the ciphertext as part of the encoding result when generating the ciphertext, so when verifying:
a. The salt value in the ciphertext will be taken out and added to the plaintext to generate the corresponding ciphertext
b. Compare the generated ciphertext with the ciphertext in the parameter to see if they are consistent
c. If consistent, the return value of the method is true; otherwise, the return value of the method is false
The code is as follows (example):
@Test
public void testMatches(){
BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
String rawPassword = "123456";
//从上面运行得到的密文随机取一个验证
String encodedPassword = "$2a$10$3CjSrCyMv/imDsJiJvwOVOxuNcaUOppExXg5kZLA1DJ0nZ/7aw48G";
//使用matches()方法,需传参原文,密文,返回值为布尔型,true则验证成功
boolean matches = passwordEncoder.matches(rawPassword,encodedPassword);
log.debug("原文={},密文={},匹配结果={}",rawPassword,encodedPassword,matches);
}
Summarize
Compared with the message digest algorithm, the BCrypt algorithm is simple to operate, and because BCrypt uses a random salt in the encoding process, its security is also higher