我们在使用MD5加密时通常会通过加盐的方式来提高安全性,下面的示例采用的是MD5+随机盐值的方式
import org.apache.commons.lang.RandomStringUtils;
import org.springframework.util.DigestUtils;
/**
* MD5加密工具类
*/
public class Md5Util {
private static final Integer SALT_LENGTH = 6;
//测试方法,比较性能
public static void main(String[] args) {
String content = "abc123xyz";
long start1 = System.currentTimeMillis();
md5Encrypt(content);
long end1 = System.currentTimeMillis();
long start2 = System.currentTimeMillis();
DigestUtils.md5DigestAsHex(content.getBytes()).toUpperCase();
long end2 = System.currentTimeMillis();
long l = end1 - start1;
long l1 = end2 - start2;
System.out.println("A耗时:" + l);
System.out.println("B耗时:" + l1);
}
/**
* MD5加密
* @param content 需要加密的明文
* @return 密文
*/
public static String md5Encrypt(String content) {
//随机生成盐值
String salt = RandomStringUtils.random(SALT_LENGTH, true, true).toUpperCase();
String before = salt.substring(0, 3);
String after = salt.substring(3, SALT_LENGTH);
String str = before + content + after;
//MD5加密
String md5Str = DigestUtils.md5DigestAsHex(str.getBytes()).toUpperCase();
int space = md5Str.length() / SALT_LENGTH;
StringBuffer md5StrBuffer = new StringBuffer(md5Str);
int index = 0;
char[] saleChars = salt.toCharArray();
for (int i = 0; i < salt.length(); i++) {
md5StrBuffer.insert(index, saleChars[i]);
index = index + space + i;
}
return md5StrBuffer.toString();
}
/**
* 密文验证
* @param content 明文
* @param md5Str 密文
* @return true密码正确, false密码错误
*/
public static boolean verifyPassword(String content, String md5Str) {
int space = (md5Str.length() - SALT_LENGTH) / SALT_LENGTH;
StringBuffer saltBuffer = new StringBuffer();
int index = 0;
for (int i = 0; i < SALT_LENGTH; i++) {
String saltChar = md5Str.substring(index, index + 1);
saltBuffer.append(saltChar);
index = index + space + i;
}
String salt = saltBuffer.toString();
String cipherText = md5Encrypt(content, salt);
if (cipherText.equals(md5Str)) {
return true;
}
return false;
}
}
通过测试对比会发现,该工具类的加密性能会比直接MD5加密性能低一些,请按需使用。
如果需要高性能直接使用DigestUtils.md5DigestAsHex(content.getBytes()).toUpperCas进行MD5加密即可。