继续浏览精彩内容
慕课网APP
程序员的梦工厂
打开
继续
感谢您的支持,我会继续努力的
赞赏金额会直接到老师账户
将二维码发送给自己后长按识别
微信支付
支付宝支付

MD5 加盐(salt)

Alexpy
关注TA
已关注
手记 7
粉丝 0
获赞 8
public class PasswordUtil {
    /**
     * 生成含有随机盐的密码
     */
    public static String generate(String password) {
        Random r = new Random();
        StringBuilder sb = new StringBuilder(16);
        sb.append(r.nextInt(99999999)).append(r.nextInt(99999999));
        int len = sb.length();
        if (len < 16) {
            for (int i = 0; i < 16 - len; i++) {
                sb.append("0");
            }
        }
        String salt = sb.toString();
        System.out.println("salt1: " + salt);
        password = md5Hex(password + salt);
        char[] cs = new char[48];
        for (int i = 0; i < 48; i += 3) {
            cs[i] = password.charAt(i / 3 * 2);
            char c = salt.charAt(i / 3);
            cs[i + 1] = c;
            cs[i + 2] = password.charAt(i / 3 * 2 + 1);
        }
        return new String(cs);
    }

    /**
     * 校验密码是否正确
     */
    public static boolean verify(String password, String md5) {
        char[] cs1 = new char[32];
        char[] cs2 = new char[16];
        for (int i = 0; i < 48; i += 3) {
            cs1[i / 3 * 2] = md5.charAt(i);
            cs1[i / 3 * 2 + 1] = md5.charAt(i + 2);
            cs2[i / 3] = md5.charAt(i + 1);
        }
        String salt = new String(cs2);
        System.out.println("salt2: " + salt);
        return md5Hex(password + salt).equals(new String(cs1));
    }

    /**
     * 获取十六进制字符串形式的MD5摘要
     */
    public static String md5Hex(String src) {
        try {
            MessageDigest md5 = MessageDigest.getInstance("MD5");
            byte[] bs = md5.digest(src.getBytes());
            return new String(new Hex().encode(bs));
        } catch (Exception e) {
            return null;
        }
    }

    public static void main(String[] args) {
        String pwd = "e10adc3949ba59abbe56e057f20f883e";
        // 加密+加盐
        String password1 = generate(pwd);
        System.out.println("结果:" + password1 + "   长度:" + password1.length());
        // 解码
        System.out.println(verify(pwd, password1));

        // 加密+加盐
        String password2 = generate(pwd);
        System.out.println("结果:" + password2 + "   长度:" + password2.length());
        // 解码
        System.out.println(verify(pwd, password2));

        // 加密+加盐
        String password3 = generate(pwd);
        System.out.println("结果:" + password3 + "   长度:" + password3.length());
        // 解码
        System.out.println(verify(pwd, password3));

    }
}
打开App,阅读手记
1人推荐
发表评论
随时随地看视频慕课网APP