时光匆匆,白驹过隙,又是一年完结日。你好!2022
package com.utils;
import org.apache.commons.codec.binary.Hex;
import java.io.UnsupportedEncodingException;
import java.math.BigInteger;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Random;
import static org.apache.commons.codec.digest.DigestUtils.md5Hex;
/**
* @Author Chenxinlele
* @Date 2021/12/31 14:24
* @Version 1.0
*/
public class MD5Util {
/**
* MD5加密成32位的
*
* @param str
* @return
*/
public static String getMD5Str(String str) {
byte[] digest = null;
try {
MessageDigest md5 = MessageDigest.getInstance("md5");
digest = md5.digest(str.getBytes("utf-8"));
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
//16是表示转换为16进制数
String md5Str = new BigInteger(1, digest).toString(16);
for (int i = 0; i < 32 - md5Str.length(); i++) {
md5Str = "0" + md5Str;
}
return md5Str;
}
/**
* 加盐MD5
*
* @param password
* @return
*/
public static String generate(String password) {
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();
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摘要
*/
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;
}
}
}
上面是一个工具类,在你需要调用的地方调用即可,如下
public static void main(String[] args) {
// 原文
String password = "123456";
// 获取加盐后的MD5值
String ciphertext = MD5Util.generate(password);
System.out.println("加盐后MD5:" + ciphertext);
/**
* 循环查询里面是否含有123456加盐后的值(这里面第二个true)
*/
String[] tempSalt = {"42df5aa69e6c86b429a3859akg563b615171c96f0754e03f",
"42df5aa69e6c86b429a3859ab4884b615171c96f0754e03f",
"516512354a0fb42f2ad1a77f455d60f1ba85a9e21091e605"};
for (String temp : tempSalt) {
System.out.println("是否存在密码:" + MD5Util.verify(plaintext, temp));
}
}
上述只是一个测试类的调用,写业务逻辑的时候相差不大,只是一个里面的加密解密的调用!