MD 是 Message Digest Algorithm 的简称,中文名消息摘要算法,目前最新为第五版即 MD5,历史版本有 MD4、MD2 等,由于存在缺陷都已不再使用。消息摘要算法各个版本间的结果是不一样的。
1992年8月,罗纳德·李维斯特向互联网工程任务组(IETF)提交了一份重要文件,描述了 MD5 算法的原理。由于这种算法的公开性和安全性,在 90 年代被广泛使用在各种程序语言中,用以确保资料传递无误等。
MD5 由 MD4、MD3、MD2 改进而来,主要增强算法复杂度和不可逆性。MD5 算法因其普遍、稳定、快速的特点,仍广泛应用于普通数据的加密保护领域。
MD5 是目前广泛使用的版本,不过其安全性多年前就开始被质疑(碰撞算法)。于是在 2008 年提出了 MD6 算法,其后 MD6 历经数次改进,目前还是试行方案阶段,未被正式使用。
JDK 自带的 MessageDigest 类为应用程序提供信息摘要算法的功能,如 MD5 或 SHA 算法。信息摘要是安全的单向哈希函数,它接收任意大小的数据,并输出固定长度的哈希值。
实例:使用 JDK 的 MessageDigest 实现消息摘要。
import org.apache.commons.codec.binary.Hex;
import java.security.MessageDigest;
public class CryptMd5Demo1 {
public static void main(String[] args) throws Exception {
String str = "hello world";
MessageDigest digest = MessageDigest.getInstance("MD5");
byte[] result = digest.digest(str.getBytes());
System.out.println(Hex.encodeHexString(result));
}
}输出结果:
5eb63bbbe01eeed093cb22bb8f5acdc3
Apache Commons Codec 提供的 DigestUtils 类用于简化常见 MessageDigest(消息摘要)任务的操作。此类是不可变的并且是线程安全的。
实例1:使用 DigestUtils 的 md5 静态方法实现 md5 消息摘要。
import org.apache.commons.codec.binary.Hex;
import org.apache.commons.codec.digest.DigestUtils;
import java.io.ByteArrayInputStream;
import java.io.IOException;
public class CryptMd5Demo2 {
public static void main(String[] args) {
String val = "Hello World";
String result1 = DigestUtils.md5Hex(val);
System.out.println("md5Hex字符串参数:" + result1);
byte[] bytes = val.getBytes();
String result2 = DigestUtils.md5Hex(bytes);
System.out.println("md5Hex字节数组参数:" + result2);
byte[] result3 = DigestUtils.md5(val);
System.out.println("md5字符串参数:" + Hex.encodeHexString(result3));
byte[] result4 = DigestUtils.md5(bytes);
System.out.println("md5字节数组参数:" + Hex.encodeHexString(result4));
try {
byte[] result5 = DigestUtils.md5(new ByteArrayInputStream(bytes));
System.out.println("md5输入流参数:" + Hex.encodeHexString(result5));
} catch (IOException e) {
e.printStackTrace();
}
}
}输出结果:
md5Hex字符串参数:b10a8db164e0754105b7a99be72e3fe5 md5Hex字节数组参数:b10a8db164e0754105b7a99be72e3fe5 md5字符串参数:b10a8db164e0754105b7a99be72e3fe5 md5字节数组参数:b10a8db164e0754105b7a99be72e3fe5 md5输入流参数:b10a8db164e0754105b7a99be72e3fe5
实例2:使用 DigestUtils 的通用方法进行 md5 消息摘要计算。
import org.apache.commons.codec.binary.Hex;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.codec.digest.MessageDigestAlgorithms;
public class CryptMd5Demo3 {
public static void main(String[] args) {
String val = "Hello World";
DigestUtils digest = new DigestUtils(MessageDigestAlgorithms.MD5);
byte[] bytes = digest.digest(val.getBytes());
System.out.println(Hex.encodeHexString(bytes));
}
}输出结果:
b10a8db164e0754105b7a99be72e3fe5
注意:更多关于 DigestUtils 的用法,请参考官网API:
http://commons.apache.org/proper/commons-codec/apidocs/index.html