Java实现MD5的随机加盐加密,这样以来就很难解密了,必须使用原密码才能正常的登录系统了,以下为Java实现的MD5随机加盐加密,以及使用Apache的Hex类实现Hex(16进制字符串和)和字节数组的互转:
package com.dq.online.onlinezuul.util; import org.apache.commons.codec.binary.Hex; import java.security.MessageDigest;
import java.util.Random; /**
* @Author Allen.Lv
* @Description //TODO
* @Date 13:43 2019/4/1
* @Desc: Coding Happy!
**/
public class Md5Utils { /**
* 加盐MD5加密
* <p>
*
* @Title : getSaltMD5
* </p>
* <p>
* @Description : TODO
* </p>
*/
public static String getSaltMD5(String password) {
// 生成一个16位的随机数
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");
}
}
// 生成最终的加密盐
String Salt = sBuilder.toString();
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 String.valueOf(cs);
} /**
* 使用Apache的Hex类实现Hex(16进制字符串和)和字节数组的互转
* <p>
*
* @Title : md5Hex
* </p>
* <p>
* @Description : TODO
* </p>
*/
// @SuppressWarnings("unused")
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 "";
}
} /**
* 验证加盐后密码是否还相同
* @param password
* @param md5str
* @return
*/
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));
} }
参考文献:
https://blog.csdn.net/Hello_World_QWP/article/details/78913096