public static String stringToMD5(String str) throws Exception
{
//定义处理后的返回值
StringBuffer result = new StringBuffer();
//定义长度为16的任意字符序列
char[] chars = {'0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F'};
//将字符串转为字节数组
byte[] srcBytes = str.getBytes();
//获得MD5加密算法
MessageDigest md5 = MessageDigest.getInstance("MD5");
//用MD5加密算法对源字节数组加密
byte[] md5Bytes = md5.digest(srcBytes);
//遍历字节数组,取出高四位和低四位对应的字符,最终会得到长度为32的字符串
for(byte b:md5Bytes)
{
//处理高四位,右移4位,再与00001111,得到的结果肯定在【0-15】范围内
result.append(chars[(b >> 4) & 0x0F]);
//处理低四位,直接与00001111
result.append(chars[b & 0x0F]);
}
return result.toString();
}
{
//定义处理后的返回值
StringBuffer result = new StringBuffer();
//定义长度为16的任意字符序列
char[] chars = {'0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F'};
//将字符串转为字节数组
byte[] srcBytes = str.getBytes();
//获得MD5加密算法
MessageDigest md5 = MessageDigest.getInstance("MD5");
//用MD5加密算法对源字节数组加密
byte[] md5Bytes = md5.digest(srcBytes);
//遍历字节数组,取出高四位和低四位对应的字符,最终会得到长度为32的字符串
for(byte b:md5Bytes)
{
//处理高四位,右移4位,再与00001111,得到的结果肯定在【0-15】范围内
result.append(chars[(b >> 4) & 0x0F]);
//处理低四位,直接与00001111
result.append(chars[b & 0x0F]);
}
return result.toString();
}