You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
recruit/java/com/example/utility/SaltMD5Util.java

55 lines
1.9 KiB

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

package com.example.utility;
import java.security.MessageDigest;
import java.util.Random;
import org.apache.commons.codec.binary.Hex;
public class SaltMD5Util {
public static String generateSaltPassword(String password) { // 生成盐和加盐后的MD5码并将盐混入到MD5码中,对MD5密码进行加强
Random random = new Random();
StringBuilder stringBuilder = new StringBuilder(16);
stringBuilder.append(random.nextInt(99999999)).append(random.nextInt(99999999));
int len = stringBuilder.length();
if (len < 16) {
for (int i = 0; i < 16 - len; i++) {
stringBuilder.append("0");
}
}
String salt = stringBuilder.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 new String(cs);
}
public static boolean verifySaltPassword(String password, String md5) { // 验证明文和加盐后的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));
}
private 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;
}
}
}
// 参考文章https://blog.csdn.net/weixin_46713508/article/details/129152215