MD5加盐加密和Spring Security 使用BCrypt加密密码

原文链接: https://liuyanzhao.com/7569.html

原文链接:https://liuyanzhao.com/7569.html

1、MD5加盐加密

所谓加盐加密,就是在原先密码上加点“盐”然后加密。因为虽然MD5加密是不可逆的,但是别人可以根据你的MD5密码不断比较发现你的原密码,比如你的密码设置得很简单是123456,加密后是 e10adc3949ba59abbe56e057f20f883e,一旦数据库泄露,密码丢失,不法分子很容易试探出来原密码。如果加上盐,只要别人不知道盐是什么,破解难度会提高很多。

2、BCrypt加密

import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
 
public class BCryptUtil {
    /**
     * 对密码进行加密
     * @param password
     * @return
     */
    public static String encode(String password) {
        BCryptPasswordEncoder bcryptPasswordEncoder = new BCryptPasswordEncoder();
        String hashPass = bcryptPasswordEncoder.encode(password);
        return hashPass;
    }
    /**
     * 对原密码和已加密的密码进行匹配,判断是否相等
     * @param password
     * @param encodedPassword
     * @return
     */
    public static boolean match(String password,String encodedPassword) {
        BCryptPasswordEncoder bcryptPasswordEncoder = new BCryptPasswordEncoder();
        boolean result = bcryptPasswordEncoder.matches(password, encodedPassword);
        return result;
    }
    public static void main(String[] args) {
        String hashPass = encode("123456");
        System.out.println(hashPass);
        System.out.println(match("123456",hashPass));//true
        System.out.println(match("123456","$2a$10$7wOQPHU2MfHt3X4wCFx5H.EZu.rlHMtY5HTFsqXiPd6BA5vNHJNf2"));//true
        System.out.println(match("123456","$2a$10$nYQWXcY.eVUwI8kYGtMCVOD0hWE4AKjzFg0oo91qc/ECQg/DD/CpS"));//true
        System.out.println(match("123456","$2a$10$9etIPtquQ3f..ACQkDHAVuBfjBoDXXWHHCOBl/RaJADxuXdSQB6I2"));//true
    }
}

Spring Security 提供了BCryptPasswordEncoder类,实现Spring的PasswordEncoder接口使用BCrypt强哈希方法来加密密码。一种基于随机生成salt(盐)的根据强大的哈希加密算法。

使用 BCrypt 加密需要导入 Spring Security 的依赖。

每次运行都会得到不同的加密密码,但是这些加密后的密码都和 123456 相等。

建议使用 BCrypt 加密,更安全,但是密码字段长度至少要60位。所以在返回给前端输入框的时候注意长度问题,如果需要可以截取后比较。

 

猜你喜欢

转载自blog.csdn.net/itwxming/article/details/100935229