import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
/**
* MD5加密
*
*/
public class MD5Util {
// 盐,用于混淆MD5
private static final String SLAT = "&%MD588&&";
/**
* MD5加密字符串(大写)
*
* @param str 需要进行MD5加密的字符串
* @return
* @throws UnsupportedEncodingException
* @throws NoSuchAlgorithmException
*/
public static String md5EncryptUpper(String str) throws NoSuchAlgorithmException, UnsupportedEncodingException {
return md5Encrypt(str, SLAT, true);
}
/**
* MD5加密字符串(大写)
*
* @param str 需要进行MD5加密的字符串
* @param slat 加密用的盐
* @return
* @throws UnsupportedEncodingException
* @throws NoSuchAlgorithmException
*/
public static String md5EncryptUpper(String str, String slat)
throws NoSuchAlgorithmException, UnsupportedEncodingException {
return md5Encrypt(str, slat, true);
}
/**
* MD5加密字符串(小写)
*
* @param str 需要进行MD5加密的字符串
* @return
* @throws UnsupportedEncodingException
* @throws NoSuchAlgorithmException
*/
public static String md5EncryptLower(String str) throws NoSuchAlgorithmException, UnsupportedEncodingException {
return md5Encrypt(str, SLAT, false);
}
/**
* MD5加密字符串(小写)
*
* @param str 需要进行MD5加密的字符串
* @param slat 加密用的盐
* @return
* @throws UnsupportedEncodingException
* @throws NoSuchAlgorithmException
*/
public static String md5EncryptLower(String str, String slat)
throws NoSuchAlgorithmException, UnsupportedEncodingException {
return md5Encrypt(str, slat, false);
}
/**
* MD5加密
*
* @param str 要加密的字符串
* @param slat 加密用的盐
* @param toUpperCase 是否转换为大写
* @return
* @throws UnsupportedEncodingException
* @throws NoSuchAlgorithmException
*/
public static String md5Encrypt(String str, String slat, boolean toUpperCase)
throws NoSuchAlgorithmException, UnsupportedEncodingException {
str = str + slat;
byte[] hash = MessageDigest.getInstance("MD5").digest(str.getBytes("UTF-8"));
if (toUpperCase) {
return HexToByteUtil.parseByte2HexStrToUpperCase(hash);
} else {
return HexToByteUtil.parseByte2HexStrToLowerCase(hash);
}
}
public static void main(String[] args) throws Exception {
System.out.println(MD5Util.md5EncryptUpper("123456789"));
}
}
用到的工具类
HexToByteUtil.parseByte2HexStrToUpperCase()
作用是将二进制的数据转为16进制然后转换为大写
部分代码实现:
/**
* 将二进制转换成16进制
*
* @param buf
*
* @param toUpperCase 是否转换为大写
* @return
*/
public static String pares2To16(byte buf[], boolean toUpperCase) {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < buf.length; i++) {
String hex = Integer.toHexString(buf[i] & 0xFF);
if (hex.length() == 1) {
hex = '0' + hex;
}
if (toUpperCase) {//大写
sb.append(hex.toUpperCase());
}else {//小写
sb.append(hex.toLowerCase());
}
}
return sb.toString();
}