import java.security.MessageDigest;
import java.util.Random;
import com.sun.org.apache.xerces.internal.impl.dv.util.HexBin;
/**
* @fileName Md5PasswordUtil.java
* @Description 明文密码加密加盐操作
* 1:生成加密密码:首先使用randomSalt获取随机盐值,并保存;再将随机盐值和明文密码传入generate生成加密密文
* 2:密码校验:将明文密码和加密后的密文传入verify,校验成功返回true,反则返回false
* @author user
* @date 2017年9月6日
* @version 1.0
*/
public class Md5PasswordUtil {
/**
* 生成16位数的随机salt值
* @return
*/
public static String randomSalt(){
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();
return salt;
}
/**
* 生成含有随机盐的密码
* @param password 明文密码
* @param salt 盐值
* @return
*/
public static String generate(String password,String 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);
}
/**
* 校验密码是否正确
* @param password 明文密码
* @param md5 加密加盐后的密码
* @return
*/
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);
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());
new HexBin();
return new String(HexBin.encode(bs));
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
}
原文地址:https://www.cnblogs.com/zeussbook/p/9530059.html