Java如何计算字符串的MD5摘要?
在本文中,您将学习如何计算字符串的MD5摘要。在应用程序中,此功能最常用的一种是保护密码。出于安全原因,您永远不会希望将用户密码以纯文本格式存储在应用程序数据库中。还有其他更安全的哈希算法,例如SHA-1(安全哈希算法),但是与SHA-1相比,MD5消息摘要提供了更快的实现。
您可以使用JavaStandardEdition库提供的消息摘要库来计算MD5摘要,但是ApacheCommonsCodec库为您提供了一个简单易用的API来生成MD5哈希。在下面的示例中,您将看到如何生成哈希以保护密码以及如何为更长的文本生成哈希。文本是您可能希望通过电子邮件发送给朋友的内容。为了确保您的朋友在不做任何修改的情况下收到您的原始邮件,您可以将生成的哈希发送到单独的电子邮件中,以用于验证邮件。
package org.nhooo.example.commons.codec; import org.apache.commons.codec.digest.DigestUtils; public class MD5HashDemo { public static void main(String[] args) { //计算密码文本的MD5摘要并返回 //该值是一个32个字符的十六进制字符串。 String password = "s3cretw0rd**"; String digest = DigestUtils.md5Hex(password); //打印纯文本密码,摘要和密码的长度 //摘要。 System.out.println("Password = " + password); System.out.println("Password Digest = " + digest); System.out.println("Length = " + digest.length()); //计算长文本的MD5摘要。 String md5 = "The MD5 message-digest algorithm is a formerly " + "widely used cryptographic hash function that produces " + "a 128-bit (16-byte) hash value. Specified in RFC 1321, " + "MD5 has been utilized in a wide variety of security " + "applications, and is also commonly used to check data " + "integrity. MD5 was designed by Ron Rivest in 1991 to " + "replace an earlier hash function, MD4. An MD5 hash value " + "is typically expressed as a hexadecimal number, 32 " + "digits long."; String fingerprint = DigestUtils.md5Hex(md5); //打印文本,指纹和摘要的长度/ //指纹。 System.out.println("Text = " + md5); System.out.println("Fingerprint = " + fingerprint); System.out.println("Length = " + fingerprint.length()); } }
从上面的代码示例中可以看出,我们使用该DigestUtils.md5Hex()方法生成MD5摘要。此类是该org.apache.commons.codec.digest软件包下ApacheCommonsCodec的 一部分。该方法是静态方法,因此在使用该方法之前,无需创建类的实例。该md5Hex()方法采用字符串参数,并生成一个32个字符的十六进制字符串。该长度始终为32个字符,而不管所处理的文本/字符串的长度如何。
除了接受字符串参数之外,该DigestUtils.md5Hex()方法的重载版本还可以接受byte或java.io.InputStream对象的数组作为参数。
这是输出产生的示例:
Password = s3cretw0rd** Password Digest = 203c603a7330ab3ea032f4b9f140cf95 Length = 32 Text = The MD5 message-digest algorithm is a formerly widely used cryptographic hash function that produces a 128-bit (16-byte) hash value. Specified in RFC 1321, MD5 has been utilized in a wide variety of security applications, and is also commonly used to check data integrity. MD5 was designed by Ron Rivest in 1991 to replace an earlier hash function, MD4. An MD5 hash value is typically expressed as a hexadecimal number, 32 digits long. Fingerprint = 3434955eecba50de487890d493ebaddd Length = 32
Maven依赖
<!-- https://search.maven.org/remotecontent?filepath=commons-codec/commons-codec/1.12/commons-codec-1.12.jar --> <dependency> <groupId>commons-codec</groupId> <artifactId>commons-codec</artifactId> <version>1.12</version> </dependency>