spring security can be used for encryption when configuring login.
Generally, plain text passwords are not stored in the database. Instead, the hash value of the password is stored, and it is a salted password hash value.
Spring security provides related encryption solutions.
BCryptPasswordEncoder#
Currently, Spring recommends using BCryptPasswordEncoder
for data encryption and verification.
BCryptPasswordEncoder has two effective methods: encode and matches.
encode method#
BCryptPasswordEncoder generates a new salt value each time it is encoded.
@Test
public void testEncoder() {
BCryptPasswordEncoder cryptPasswordEncoder = new BCryptPasswordEncoder();
logger.info(cryptPasswordEncoder.encode("dqn"));
logger.info(cryptPasswordEncoder.encode("dqn"));
logger.info(cryptPasswordEncoder.encode("dqn"));
logger.info(cryptPasswordEncoder.encode("dqn"));
logger.info(cryptPasswordEncoder.encode("dqn"));
}
It can be seen that the $ in the hash value should be the delimiter of the salt.
When storing, the salted hash value can be stored.
matches method#
The matches method is responsible for comparing whether the stored hash value belongs to a certain password.
It first extracts the salt from the stored hash value, applies it to the password, calculates the hash value, and then compares it.
Let's try using encode first:
logger.info("is true? {}",cryptPasswordEncoder.matches("dqn","$2a$1$95TYhnCLucrLeRDz9PVifuKm99u5mcMqRXe4bzirKOQZAjOhJ0Wr6"));
In Security Configuration#
Adding BCryptPasswordEncoder
in the Security configuration file is very simple:
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService(username -> {
// return something;
}).passwordEncoder(new BCryptPasswordEncoder());
}
Simply create a new one.