MD5(Message Digest Algorithm 5)是一種廣泛使用的雜湊函數,常用於密碼儲存、檔案完整性驗證等場合。以下提供一個完整、可直接使用的 Java MD5 加密工具類。
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
public class MD5Util {
/**
* 取得字串的 MD5 雜湊值(十六進位大寫)
* @param input 待加密字串
* @return 32 位十六進位字串,失敗回傳 null
*/
public static String encode(String input) {
try {
MessageDigest md = MessageDigest.getInstance("MD5");
byte[] inputBytes = input.getBytes();
md.update(inputBytes);
byte[] digestBytes = md.digest();
return bytesToHex(digestBytes);
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
return null;
}
}
/**
* 將位元組陣列轉為十六進位字串
*/
private static String bytesToHex(byte[] bytes) {
char[] hexDigits = {'0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F'};
char[] result = new char[bytes.length * 2];
int index = 0;
for (byte b : bytes) {
result[index++] = hexDigits[b >>> 4 & 0xF];
result[index++] = hexDigits[b & 0xF];
}
return new String(result);
}
}
public class Main {
public static void main(String[] args) {
String password = "mySecret123";
String md5 = MD5Util.encode(password);
System.out.println("原文:" + password);
System.out.println("MD5:" + md5);
// 輸出範例:MD5:A1B2C3D4E5F6...
}
}
>>> 4、& 0xF)轉換十六進位,效能優於字串格式化。若需快速驗證,可使用線上 MD5 加密工具:MD5 在線加密工具