Digester

Introduction

Introduction to Digest Algorithms

A digest algorithm is a type of algorithm that produces a specific output format. The characteristic of this algorithm is that no matter what length of original data the user inputs, the encrypted output after calculation is always a fixed length. The principle of this algorithm is to extract certain forms of the original data according to certain operational rules. This extraction is the digest, and the content of the data being digested is closely related to the original data. As long as the original data is slightly changed, the output “digest” will be completely different. Therefore, algorithms based on this principle can provide relatively robust protection for data integrity.

However, since the output ciphertext is a fixed-length value obtained by processing the original data, it cannot be restored to the original data, i.e., the message digest algorithm is irreversible, and it is theoretically impossible to obtain the original data content through reverse operation. Therefore, it is usually only used for data integrity verification.

Types of Digest Algorithms Supported by Hutool

Without introducing third-party libraries, the JDK supports a limited number of digest algorithms:

For details, see: https://docs.oracle.com/javase/7/docs/technotes/guides/security/StandardNames.html#MessageDigest

Digest Algorithms

  • MD2
  • MD5
  • SHA-1
  • SHA-256
  • SHA-384
  • SHA-512

Usage

Digester

Taking MD5 as an example:

Digester md5 = new Digester(DigestAlgorithm.MD5);

// 5393554e94bf0eb6436f240a4fd71282
String digestHex = md5.digestHex(testStr);

Of course, as the most commonly used method, MD5 and other methods are encapsulated as tool methods in DigestUtil. The above code can be further simplified as:

// 5393554e94bf0eb6436f240a4fd71282
String md5Hex1 = DigestUtil.md5Hex(testStr);

More Digest Algorithms

SM3

After 4.2.1, Hutool can support national cryptography algorithms with the help of the Bouncy Castle library, taking SM3 as an example:

We first need to introduce the Bouncy Castle library:

<dependency>
  <groupId>org.bouncycastle</groupId>
  <artifactId>bcprov-jdk15to18</artifactId>
  <version>1.66</version>
</dependency>

Then we can call the SM3 algorithm. The calling method is consistent with other digest algorithms:

Digester digester = DigestUtil.digester("sm3");

//136ce3c86e4ed909b76082055a61586af20b4dab674732ebd4b599eef080c9be
String digestHex = digester.digestHex("aaaaa");

The java.security package of the Java standard library provides a standard mechanism that allows third-party providers to seamlessly access it. When the jar of the Bouncy Castle library is introduced, Hutool will automatically detect and connect to it. For specific methods, see SecureUtil.createMessageDigest.