import java.security.MessageDigest;
import java.util.Random;
import org.apache.commons.codec.binary.Hex;
/**
*
* @author shilei
*
* @time 2019年6月13日 下午2:41:59
*
* @desc MD5加密
*/
public class MD5Utils {
public static final String MD5_SALT = getSalt();
/**
* @desc 加盐MD5加密
*/
public static String getSaltMD5(String password) {
password = md5Hex(password + MD5_SALT);
char[] cs = new char[48];
for (int i = 0; i < 48; i += 3) {
cs[i] = password.charAt(i / 3 * 2);
char c = MD5_SALT.charAt(i / 3);
cs[i + 1] = c;
cs[i + 2] = password.charAt(i / 3 * 2 + 1);
}
return String.valueOf(cs);
}
/**
* @desc 验证加盐后是否和原文一致
*/
public static boolean getSaltverifyMD5(String password, String md5str) {
char[] cs1 = new char[32];
char[] cs2 = new char[16];
for (int i = 0; i < 48; i += 3) {
cs1[i / 3 * 2] = md5str.charAt(i);
cs1[i / 3 * 2 + 1] = md5str.charAt(i + 2);
cs2[i / 3] = md5str.charAt(i + 1);
}
String Salt = new String(cs2);
return md5Hex(password + Salt).equals(String.valueOf(cs1));
}
/**
* @desc 使用Apache的Hex类实现Hex(16进制字符串和)和字节数组的互转
*/
private static String md5Hex(String str) {
try {
MessageDigest md = MessageDigest.getInstance("MD5");
byte[] digest = md.digest(str.getBytes());
return new String(new Hex().encode(digest));
} catch (Exception e) {
e.printStackTrace();
System.out.println(e.toString());
return "";
}
}
/**
* @desc 生成一个16位的盐
*/
private static String getSalt() {
Random random = new Random();
StringBuilder sBuilder = new StringBuilder(16);
sBuilder.append(random.nextInt(99999999)).append(random.nextInt(99999999));
int len = sBuilder.length();
if (len < 16) {
for (int i = 0; i < 16 - len; i++) {
sBuilder.append("0");
}
}
return sBuilder.toString();
}
}