In actual projects, sometimes it is necessary to calculate the MD5 value of the specified string. Usually, this approach is adopted.
import java.security.MessageDigest;
...................
String originalMessage = xxxxxxx;
MessageDigest messageDigest = MessageDigest.getInstance("MD5");
messageDigest.reset();
messageDigest.update(originalMessage.getBytes(Charset.forName("UTF8")));
byte[] resultByte = messageDigest.digest();
However, the MD5 value obtained by this method is in the form of a byte array. When comparing the MD5 value, the MD5 value is more often compared in the form of a string. We can write a method to convert it to a string in the form of Hex, or we can Hex class using commons-codec library
import org.apache.commons.codec.binary.Hex;
String md5Str = new String(Hex.encodeHex(resultByte));
This converts the resulting MD5 value into an MD5 string.
The commons-codec library also provides a DigestUtils class, which directly calculates the MD5 value string of the string. Using this class, we can calculate the MD5 value string of the string using the following methods
import org.apache.commons.codec.digest.DigestUtils;
String originalMessage = xxxxxxx;
String md5Str = DigestUtils.md5Hex(originalMessage.getBytes(Charset.forName("UTF-8"));
The Spring-Core library also provides a DigestUtils class that can be used to calculate MD5 value strings as follows
import org.springframework.util.DigestUtils;
String originalMessage = xxxxxxx;
String md5Str = DigestUtils.md5DigestAsHex(originalMessage.getBytes(Charset.forName("UTF-8")));
These two classes can also calculate the MD5 value of the InputStream, just replace the byte array of the method parameter with the InputStream object.