Message Digest Algorithm MD5(中文名为消息摘要算法第五版)为计算机安全领域广泛使用的一种散列函数,用以提供消息的完整性保护。2004年8月17日中国山东大学的王小云教授实现了MD5的破译。因此md5常常用在文件和网络请求的完整性校验方面。
Java语言提供了md5的实现,方法如下:
private static byte[] getMD5(byte[] data) {
byte[] hash = null;
try {
MessageDigest digest = MessageDigest.getInstance("MD5");
digest.update(data);
hash = digest.digest();
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
}
return hash;
}
传入的参数data是一个byte数组。对于String类型,可以使用String.getBytes()方法获得。
生成的hash也是一个byte[]的数组,因为md5是使用128bit的散列值表示的,因此hash总共有16个byte,长度是16。
实际运用中,可将byte[] 转为hex,参见此文http://blog.csdn.net/anerle2012/article/details/52328298 byte[]转hex的方法。或使用如下方法转化为String。
int RADIX = 10 + 26; // 10 digits + 26 letters
//md5 16*8bit int 4*8bit
//md5 4*int
byte[] md5 = hash;
BigInteger bi = new BigInteger(md5).abs();
return bi.toString(RADIX);