public class MD5Util {
/**
* 生成一个字符串的 MD5 哈希值。
*
* @param input 待哈希的字符串
* @return MD5 哈希值的十六进制字符串表示形式
*/
public static String generateMD5(String input) {
try {
MessageDigest md = MessageDigest.getInstance("MD5");
byte[] messageDigest = md.digest(input.getBytes(StandardCharsets.UTF_8));
BigInteger no = new BigInteger(1, messageDigest);
StringBuilder hashText = new StringBuilder(no.toString(16));
// 如果生成的哈希值不足32位,则前面补零
while (hashText.length() < 32) {
hashText.insert(0, "0");
}
return hashText.toString();
} catch (NoSuchAlgorithmException e) {
throw new RuntimeException("MD5 algorithm not found", e);
}
}
public static void main(String[] args) {
String input = "Hello, World!";
String md5Hash = generateMD5(input);
System.out.println("MD5 hash of '" + input + "': " + md5Hash);
}
}
09-07
1168
09-07
1190
08-28