Java中提供了MessageDigest類來實現MD5算法。下面是一個簡單的示例代碼:
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
public class MD5Example {
public static void main(String[] args) {
String input = "Hello World";
try {
// 創建MD5算法實例
MessageDigest md = MessageDigest.getInstance("MD5");
// 將輸入轉換為字節數組
byte[] inputBytes = input.getBytes();
// 計算MD5摘要
byte[] mdBytes = md.digest(inputBytes);
// 將摘要轉換為十六進制字符串
StringBuilder sb = new StringBuilder();
for (byte b : mdBytes) {
sb.append(String.format("%02x", b));
}
String md5String = sb.toString();
System.out.println("MD5摘要:" + md5String);
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
}
}
}
運行上述代碼將輸出以下結果:
MD5摘要:7b502c3a1f48c8609ae212cdfb639dee