package com.lzj.www.md5.test;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import org.junit.Test;
/*
* MD5 算法(不带盐值)
*/
public class MD5 {
private static final String[] GOAL = { "0", "1", "2", "3", "4", "5",
"6", "7", "8", "9", "a", "b", "c", "d", "e", "f" };
public String getMD5(String object){
String result = null;
try {
MessageDigest digest = MessageDigest.getInstance("MD5");
//--> digest.digest(object.getBytes()) 目标!!只要转成16进制的字符串即可
result = byteArrayToString(digest.digest(object.getBytes()));
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
}
return result.toUpperCase();
}
private String byteArrayToString(byte[] object){
StringBuffer ss = new StringBuffer();
//实现把每个字节变成对应的16进制数
for(int i = 0; i < object.length; i++){
ss.append(byteToString(object[i]));
}
return ss.toString();
}
private String byteToString(byte object){
int temp = object < 0 ? object + 256 : object; //取正,再匹配下标即可
return GOAL[temp / 16] + GOAL[temp % 16];
}
@Test
public void test(){
System.out.println(getMD5("hello"));
}
}