魅力峰值

导航

SpringSecurity(1)密码加密

     自定义密码加密

1.加密工具类。本文使用md5加密方式

 

public class MD5Util {

    private static byte[] md5(String s) {
        MessageDigest algorithm;
        try {
            algorithm = MessageDigest.getInstance("MD5");
            algorithm.reset();
            algorithm.update(s.getBytes(StandardCharsets.UTF_8));
            byte[] messageDigest = algorithm.digest();
            return messageDigest;
        } catch (Exception e) {

        }
        return null;
    }
private static final String toHex(byte hash[]) { if (hash == null) { return null; } StringBuffer buf = new StringBuffer(hash.length * 2); int i; for (i = 0; i < hash.length; i++) { if ((hash[i] & 0xff) < 0x10) { buf.append("0"); } buf.append(Long.toString(hash[i] & 0xff, 16)); } return buf.toString(); } public static String hash(String s) { try { return new String(toHex(md5(s)).getBytes(StandardCharsets.UTF_8), StandardCharsets.UTF_8); } catch (Exception e) { return s; } }

}

 


2.实现接口  PasswordEncoder

   接口里边有两个方方法 encode(CharSequence charSequence)用来提供加密密码 和 方法 matches(CharSequence charSequence, String s)用来验证用户输入的密码和数据库查询出来的密码s是否匹配

 

 

@Component
public class MyPasswordEncoder implements PasswordEncoder {
    @Override
    public String encode(CharSequence charSequence) {
        return MD5Util.hash(charSequence.toString());
    }

    @Override
    public boolean matches(CharSequence charSequence, String s) {
        return encode(charSequence).equals(s);
    }

    @Override
    public boolean upgradeEncoding(String encodedPassword) {
        return false;
    }
}

3.配置加密方式(以下是部分代码)

@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(jsr250Enabled = true, prePostEnabled = true)
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {


    @Autowired
    private MyUserService myUserService;
    @Autowired
    private MyPasswordEncoder myPasswordEncoder;

    //配置用户认证方式,构建 AuthenticationManagerBuilder
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(myUserService).passwordEncoder(myPasswordEncoder);
    }

}

  

  

 

posted on 2019-01-08 15:01  魅力峰值  阅读(255)  评论(0)    收藏  举报