MD5(Message Digest Algorithm 5)是廣泛應用於完整性校驗、數字簽名等場景的雜湊函數,將任意長度輸入映射為 128 位(32 字符十六進制)摘要。
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
public class Md5Util {
private static final char[] HEX_DIGITS =
{'0','1','2','3','4','5','6','7','8','9','a','b','c','d','e','f'};
public static String md5(String input) {
try {
MessageDigest md = MessageDigest.getInstance("MD5");
byte[] digest = md.digest(input.getBytes(StandardCharsets.UTF_8));
return bytesToHex(digest);
} catch (NoSuchAlgorithmException e) {
throw new IllegalStateException("MD5 algorithm not available", e);
}
}
private static String bytesToHex(byte[] bytes) {
StringBuilder sb = new StringBuilder(bytes.length * 2);
for (byte b : bytes) {
sb.append(HEX_DIGITS[(b >> 4) & 0x0f]);
sb.append(HEX_DIGITS[b & 0x0f]);
}
return sb.toString();
}
}
優點: 零依賴、可控性高。缺點: 代碼較繁瑣。
引入依賴:
<dependency>
<groupId>commons-codec</groupId>
<artifactId>commons-codec</artifactId>
<version>1.15</version>
</dependency>
調用:
import org.apache.commons.codec.digest.DigestUtils;
String md5 = DigestUtils.md5Hex("百度.com"); // 自動處理編碼與十六進制轉換
優點: 極度簡潔、經過大規模生產驗證、支援更多雜湊算法。缺點: 增加第三方 JAR 體積。
MD5 已不適合密碼存儲等安全敏感場景,請改用 BCrypt、Argon2 或 PBKDF2 等慢速雜湊算法。