代码:
package md5;
import java.security.MessageDigest;
/**
* 求md5值分两步
* 1.拿到字符串的byte数组,注意abc 这种字母的byte 数组就是a一个元素b一个元素c一个元素,即[97,98,99], "我"作为一个汉字他的字节数组是3个byte,即[-26, -120, -111]
* 通过字节数组算出hash值的byte 数组(md.digest()), 这个hash 值的byte 数组的长度是16
* 2.hash 值的byte 数组,每个byte取高4位和低4位做下标拿字符,这样结果md5值是32位
*
* @author jaloli
*
*/
public class Md5 {
public final static String[] hashValueString = {"0","1","2","3","4","5","6","7","8","9","a","b","c","d","e","f"};
public static String byteToString(byte[] hashValueBytes){
String result = "";
for(int i=0;i<hashValueBytes.length;i++){
int hashValueInt = hashValueBytes[i];
hashValueInt = hashValueInt>0 ? hashValueInt : hashValueInt+256;
int high = hashValueInt / 16; //byte 的高4位
int low = hashValueInt % 16; //byte 的低4位
result += hashValueString[high] + hashValueString[low];
}
return result;
}
public static void byteToNum(byte[] hashValueBytes){
}
public static String GetMd5Code(String str) throws Exception {
String md5Value = "";
MessageDigest md = MessageDigest.getInstance("MD5");
byte[] hashValueBytes = md.digest(str.getBytes()); //返回值为存放hash 值的byte 数组
md5Value = byteToString(hashValueBytes);
return md5Value;
}
public static void main(String[] args) throws Exception {
System.out.println(Md5.GetMd5Code("我"));
}
}
结果:
"我" 的md5值是(32位) 16815254531798dc21ee979d1d9c6675
"abc" 的md5值是(32位) 900150983cd24fb0d6963f7d28e17f72