標準實作(.NET Framework / .NET Core 通用)
using System;
using System.Security.Cryptography;
using System.Text;
public static class Md5Helper
{
public static string Compute(string input)
{
using (MD5 md5 = MD5.Create()) // 工廠模式,自動選擇最佳實作
{
byte[] hash = md5.ComputeHash(Encoding.UTF8.GetBytes(input));
return ByteArrayToHex(hash);
}
}
private static string ByteArrayToHex(byte[] bytes)
{
// 使用 StringBuilder 避免字串串接效能問題
var sb = new StringBuilder(bytes.Length * 2);
foreach (byte b in bytes)
sb.Append(b.ToString("x2")); // 小寫十六進位,兩位數
return sb.ToString();
}
}
進階:一次性雜湊大型檔案/串流
public static string ComputeFile(string filePath)
{
using (var md5 = MD5.Create())
using (var stream = File.OpenRead(filePath))
{
byte[] hash = md5.ComputeHash(stream);
return ByteArrayToHex(hash);
}
}
安全性提醒
- MD5 已被破解:碰撞攻擊可行,**不可用於數位簽章、憑證、密碼儲存**等安全敏感場景。
- 密碼儲存請用:PBKDF2 (
Rfc2898DeriveBytes)、bcrypt、Argon2、scrypt 等慢速雜湊演算法。
- 檔案完整性驗證:可用 SHA-256 (
SHA256.Create()) 替代,同樣簡單且更安全。
效能微調
| 場景 | 建議 |
| 高頻呼叫(百萬級) | 重用 MD5 實例(非執行緒安全),或改用 System.IO.Hashing.Md5 (.NET 6+ 非加密雜湊) |
| 大檔案 | ComputeHash(Stream) 避免一次載入記憶體 |
| 需大寫輸出 | "X2" 格式字串 |