溫馨提示×

基于Java如何實現(xiàn)MD5算法

小億
108
2023-08-02 23:00:32
欄目: 編程語言

Java中提供了MessageDigest類來實現(xiàn)MD5算法。下面是一個簡單的示例代碼:

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
public class MD5Example {
public static void main(String[] args) {
String input = "Hello World";
try {
// 創(chuàng)建MD5算法實例
MessageDigest md = MessageDigest.getInstance("MD5");
// 將輸入轉(zhuǎn)換為字節(jié)數(shù)組
byte[] inputBytes = input.getBytes();
// 計算MD5摘要
byte[] mdBytes = md.digest(inputBytes);
// 將摘要轉(zhuǎn)換為十六進制字符串
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();
}
}
}

運行上述代碼將輸出以下結(jié)果:

MD5摘要:7b502c3a1f48c8609ae212cdfb639dee

0