public class MD5Utils {
private static final String hexDigIts[] = {"0","1","2","3","4","5","6","7","8","9","a","b","c","d","e","f"};
/**
* MD5加密
* @param origin 字符
* @param charsetname 编码
* @return
*/
public static String MD5Encode(String origin, String charsetname){
String resultString = null;
try{
resultString = new String(origin);
//创建具有MD5算法的信息摘要
MessageDigest md = MessageDigest.getInstance("MD5");
if(null == charsetname || "".equals(charsetname)){
//使用指定的字节数组对摘要进行最后更新,然后完成摘要计算
//将得到的字节数组变成字符串返回
resultString = byteArrayToHexString(md.digest(resultString.getBytes()));
}else{
resultString = byteArrayToHexString(md.digest(resultString.getBytes(charsetname)));
}
}catch (Exception e){
}
return resultString;
}
/**
* 将字节数组转换成十六进制,并以字符串的形式返回
* 128位是指二进制位。二进制太长,所以一般都改写成16进制,
* 每一位16进制数可以代替4位二进制数,所以128位二进制数写成16进制就变成了128/4=32位。
*/
public 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();
}
/**
* 将一个字节转换成十六进制,并以字符串的形式返回
*/
public static String byteToHexString(byte b){
int n = b;
if(n < 0){
n += 256;
}
int d1 = n / 16;
int d2 = n % 16;
return hexDigIts[d1] + hexDigIts[d2];
}
}
String md5Str = MD5Utils.MD5Encode("123456","utf8");
原生方法:https://blog.csdn.net/junmoxi/article/details/80841555