基于MD5 的双重加密
package com.goods.springbootmybatisgoods.util;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
public class MD5Util {
public static String md5(String source) {
try {
MessageDigest md = MessageDigest.getInstance("MD5");
byte[] inputBytes = source.getBytes();
byte[] md5Bytes = md.digest(inputBytes);
StringBuilder sb = new StringBuilder();
for (byte b : md5Bytes) {
sb.append(String.format("%02x", b));
}
String md5Hash = sb.toString();
System.out.println("MD5 Hash: " + md5Hash);
return md5Hash;
} catch (NoSuchAlgorithmException e) {
throw new RuntimeException(e);
}
}
public static String md5(String source, String salt) {
try {
byte[] saltByte = salt.getBytes();
MessageDigest md = MessageDigest.getInstance("MD5");
byte[] passwordWithSalt = concatenateByteArrays(source.getBytes(), saltByte);
byte[] md5Bytes = md.digest(passwordWithSalt);
StringBuilder sb = new StringBuilder();
for (byte b : md5Bytes) {
sb.append(String.format("%02x", b));
}
return sb.toString();
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
}
return source;
}
private static byte[] concatenateByteArrays(byte[] a, byte[] b) {
byte[] result = new byte[a.length + b.length];
System.arraycopy(a, 0, result, 0, a.length);
System.arraycopy(b, 0, result, a.length, b.length);
return result;
}
public static String encodePassword(String password, String salt) {
return md5(md5(password, salt));
}
}