Security integration framework used to SSM BCryptPasswordEncoder in Spring Security for password encryption (step must not be wrong)

Implement a security framework .Spring Security password encryption method Brief

1. First: Spring Security provides powerful encryption tool PasswordEncoder, the code PasswordEncoder interfaces are as follows:

package org.springframework.security.crypto.password;

public interface PasswordEncoder {
    String encode(CharSequence var1);//是是对密码加密的方法

    boolean matches(CharSequence var1, String var2);//是用来验证密码和加密后密码是否一致的如果一致则返回true
}

2. Secondly: Spring Security provides BCryptPasswordEncoder class that implements the Spring PasswordEncoder interfaces, use BCrypt strong hashing method to encrypt the password, by BCrypt strong encryption hashing every result is different: you can take a look at examples encrypted password, the password should be noted that both the encrypted plaintext passwords are: 123
Here Insert Picture Description3. the encrypted code can be seen each encrypted random string is generated:

public String encode(CharSequence rawPassword) {
        String salt;
        if (this.strength > 0) {
            if (this.random != null) {
                salt = BCrypt.gensalt(this.strength, this.random);
            } else {
                salt = BCrypt.gensalt(this.strength);
            }
        } else {
            salt = BCrypt.gensalt();
        }

        return BCrypt.hashpw(rawPassword.toString(), salt);
    }

Two encrypted specific implementation steps

1. Configuration tools necessary for encryption in the configuration file

<!--配置加密工具类-->
<bean id="passwordEncoder" class="org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder"/>

BCryptPasswordEncoder injection layer 2. In the implementation of service

@Autowired
 private BCryptPasswordEncoder passwordEncoder;//通过注解拿到加密对象

3. then add the required service encryption layer in the implementation in the method of operation such as saving operation

//保存一个用户,使用加密算法把加密后的密码保存入数据库
    @Override
    public void save(SysUser sysUser) {
        //二.使用安全框架加密方式
        //1.Security安全框架加密操作:加密密码并存入sysUser对象中
        String encode = passwordEncoder.encode(sysUser.getPassword());//拿到加密后的密码
        sysUser.setPassword(encode);//将加密后的密码设置到sysUser对象中
        userDao.save(sysUser);
    }

4. The above configuration end you need to run it, add a user (the user's password is encrypted), or the login password is not encrypted before use to fail; then remove the "{noop}"

//2.Security安全框架加密操作:去除+"{noop}"+————————————非常重要
            User user = new User(sysUser.getUsername(), sysUser.getPassword(), authorities);
            return user;

5. In the configuration file spring_security.xml arranged inside the first step reference id

<!-- Security安全框架加密操作:引入加密操作-->
<security:password-encoder ref="passwordEncoder"/>
Published 43 original articles · won praise 84 · views 8217

Guess you like

Origin blog.csdn.net/weixin_43330884/article/details/104632267