调用效果:密码:123456,盐abcd(这是动态的,一个用户一个码,越长越好),得到:1G00500_000000abcd23456c000000abcd
最后给他加上md5 调用后得到: $2a$10$PZTMPfyTkkzZmIQXmhnv2uvOt9ecJxP4oEjkOJYKYaEMr.eewOGWa
就算密文被破解了得到的密码也是1G00500_000000abcd23456c000000abcd,完美防止了查看原密码123456
package com.java.core.web.utils;
public class Md5Utils {
//盐加密
public static String md5Password(String password,String salt){
//salt至少10位
if(salt.length()<10){
salt= Md5Utils.leftPad(salt,10,"0");
}
StringBuilder pwd=new StringBuilder(password+"c"+salt);
pwd=pwd.insert(1,"G");
pwd=pwd.insert(2,salt.substring(1));
pwd=pwd.insert(4,"5");
pwd=pwd.insert(5,salt.substring(2,4));
pwd=pwd.insert(7,"_");
pwd=pwd.insert(8,salt.substring(0,3));
//return pwd.toString(); md5
return new BCryptPasswordEncoder().encode(pwd.toString());
}
//字符串格式化长度不足补0
public static String leftPad(String str, int strLength,String chart) {
int strLen = str.length();
if (strLen < strLength) {
while (strLen < strLength) {
StringBuffer sb = new StringBuffer();
sb.append(chart).append(str);// 左补0
// sb.append(str).append("0");//右补0
str = sb.toString();
strLen = str.length();
}
}
return str;
}
}
这里顺便提一嘴,使用BCryptPasswordEncoder加密,每次生成的密文都不一样,比如密码123,第一次调用,得到密文xxxxxxxxxx,第二次调用得到密文aaaaaaaaaaaaaaa,这样做密码对比的时候就不能拿密文对比了,而是调用matches 去对比,代码如下
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
public class Test {
public static void main(String[] args) {
String password = "123456";
BCryptPasswordEncoder bcryptPasswordEncoder = new BCryptPasswordEncoder();
//加密:bcryptPasswordEncoder进行密码加密
String encodedPassword = bcryptPasswordEncoder.encode(password);
System.out.println("bcryptPasswordEncoder进行密码加密:"+encodedPassword);
//解密:
boolean flag = bcryptPasswordEncoder.matches(password, encodedPassword);
//如果flag为true,则解密成功 false,则解密失败
System.out.println("解密:"+flag);
}
}