MD5加密工具类MD5
程序员文章站
2022-03-14 20:29:08
...
传入字符串可直接返回加密结果
package com.mosukj.util;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
public class MD5 {
private final static String[] hexDigits = {
"0","1","2","3","4","5","6","7","8","9","a","b","c","d","e","f"
};
private static String byteArrayToHexString(byte[] b)
{
StringBuffer resultSb = new StringBuffer();
for (int i=0;i<b.length;i++)
{
resultSb.append(byteToHexString(b[i]));
}
return resultSb.toString();
}
private static Object byteToHexString(byte b)
{
int n=b;
if (n<0)
n = 256 + n;
int d1 = n/16;
int d2 = n%16;
return hexDigits[d1] + hexDigits[d2];
}
/**
* 加密方法
* @param origin 原始字符
* @return 加密后字符内容
*/
public static String compile(String origin)
{
String resultString = null;
MessageDigest md;
try
{
resultString = new String(origin);
md = MessageDigest.getInstance("MD5");
resultString = byteArrayToHexString(md.digest(resultString.getBytes()));
}
catch (NoSuchAlgorithmException e)
{
e.printStackTrace();
}
return resultString;
}
}
下一篇: php单例模式的讲解(代码示例)