/**
*
*/
package com.wuhongbo.common.util.encry;
import java.security.MessageDigest;
/**
* MD5加密
*
* @author wuhongbo
*/
public class MD5Util
{
private final static char hexDigits[] = { '0', '1', '2', '3', '4', '5',
'6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' };
/**
* MD5加密
*
* @param s
* 加密内容
* @param hex
* 字符长度必须为16位,允许为空或长度为0
* @return
* @throws Exception
*/
public static String encode(String s, char[] hex) throws Exception
{
if (hex == null || hex.length == 0)
{
hex = hexDigits;
}
else if (hex.length != 16)
{
throw new Exception("掩码长度必须是16位的字符串");
}
try
{
byte[] strTemp = s.getBytes();
MessageDigest mdTemp;
mdTemp = MessageDigest.getInstance("MD5");
byte[] md = mdTemp.digest(strTemp);
// 处理掩码
StringBuffer sb = new StringBuffer();
for (int i = 0; i < md.length; i++)
{
int num = md[i];
// String temp = Integer.toHexString(num & 0xFF);
// if (temp.length() == 1)
// {
// temp = "0" + temp;
// }
// sb.append(temp.toUpperCase());
int n = num;
if (n < 0)
{
n += 256;
}
int d1 = n / 16;
int d2 = n % 16;
String temp =hexDigits[d1] + "" + hexDigits[d2];
sb.append(temp);
}
// 掩码处理
return sb.toString().toUpperCase();
}
catch (Exception e)
{
throw new Exception("加密失败,请检查加密码算法。");
}
}
/**
* MD5加密
*
* @param s
* 加密内容
* @param hex
* 掩码,字符长度必须为16位,允许为空或长度为0
* @return
* @throws Exception
*/
public static String encode(String s, String hexStr) throws Exception
{
if (hexStr == null)
{
hexStr = "";
}
return encode(s, hexStr.toCharArray());
}
/**
* MD5加密
*
* @param s
* 加密内容
* @return
* @throws Exception
*/
public static String encode(String s) throws Exception
{
return encode(s, "");
}
// 测试主函数
public static void main(String args[])
{
try
{
System.out.println("MD5后:" + encode("admin"));
}
catch (Exception e)
{
e.printStackTrace();
}
}
}