package com.nanjing.water.common.security;
|
|
import java.security.MessageDigest;
|
import java.security.NoSuchAlgorithmException;
|
|
public class MD5Util {
|
private MD5Util() {
|
throw new IllegalStateException("Utility class");
|
}
|
|
/**
|
* 生成32位md5码
|
* @param content 待加密明文字符串
|
* @return 加密串
|
*/
|
public static String encrypt(String content) {
|
//region 加盐方式
|
try {
|
// 得到一个信息摘要器
|
MessageDigest digest = MessageDigest.getInstance("md5");
|
byte[] result = digest.digest(content.getBytes());
|
StringBuilder sb = new StringBuilder();
|
// 把每一个byte 做一个与运算 0xff;
|
for (byte b : result) {
|
// 与运算
|
int number = b & 0xff;// 加盐
|
String str = Integer.toHexString(number);
|
if (str.length() == 1) {
|
sb.append("0");
|
}
|
sb.append(str);
|
}
|
// 标准的md5加密后的结果
|
return sb.toString();
|
} catch (NoSuchAlgorithmException e) {
|
e.printStackTrace();
|
return "";
|
}
|
//endregion
|
|
//region 普通方式
|
|
/*char hexDigits[] = {
|
'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'
|
};
|
try {
|
byte[] btInput = content.getBytes();
|
// 获得MD5摘要算法的 MessageDigest 对象
|
MessageDigest mdInst = MessageDigest.getInstance("MD5");
|
// 使用指定的字节更新摘要
|
mdInst.update(btInput);
|
// 获得密文
|
byte[] md = mdInst.digest();
|
// 把密文转换成十六进制的字符串形式
|
int j = md.length;
|
char str[] = new char[j * 2];
|
int k = 0;
|
for (int i = 0; i < j; i++) {
|
byte byte0 = md[i];
|
str[k++] = hexDigits[byte0 >>> 4 & 0xf];
|
str[k++] = hexDigits[byte0 & 0xf];
|
}
|
return new String(str);
|
} catch (Exception e) {
|
return "";
|
}*/
|
|
//endregion
|
}
|
}
|