using System.Web.Security;
public static string MD5(string toCryString)
{
// 內部呼叫 MD5CryptoServiceProvider 並轉為十六進位大寫字串
return FormsAuthentication.HashPasswordForStoringInConfigFile(toCryString, "MD5");
}
特點:
using System;
using System.Security.Cryptography;
using System.Text;
public static string MD5(string input)
{
// 1. 建立演算法實例 (實作 IDisposable)
using (MD5 md5 = MD5.Create()) // 推薦用工廠方法,自動選擇最佳實作 (非 FIPS 環境)
{
// 2. 將字串編碼為位元組陣列 (指定編碼!預設 UTF-8)
byte[] inputBytes = Encoding.UTF8.GetBytes(input);
// 3. 計算雜湊
byte[] hashBytes = md5.ComputeHash(inputBytes);
// 4. 轉為十六進位字串 (小寫,符合 RFC 4648)
var sb = new StringBuilder(hashBytes.Length * 2);
foreach (byte b in hashBytes)
{
sb.Append(b.ToString("x2")); // "x2" = 兩位十六進位小寫
}
return sb.ToString();
}
}
// 使用範例
string hash = MD5("123456"); // 輸出: e10adc3949ba59abbe56e057f20f883e (小寫)
| 項目 | FormsAuthentication | MD5.Create() + 手動格式化 |
|---|---|---|
| 編碼 | 預設 `Encoding.Default` (系統 ANSI 頁面碼,中文環境為 Big5/GBK) | **明確指定** `Encoding.UTF8` (跨平台一致) |
| 輸出大小寫 | **大寫** | 可控制 (範例為小寫 `x2`,大寫用 `X2`) |
| 相依組件 | `System.Web.dll` | `System.Security.Cryptography` (標準庫) |
| 跨平台 | ❌ (需 .NET Framework) | ✅ (.NET Core / 5+ / Standard / Mono / Unity) |
| FIPS 相容性 | 內部使用 MD5CryptoServiceProvider (非 FIPS) | `MD5.Create()` 會在 FIPS 環境拋例外,需改用 `new MD5Cng()` (Windows) 或接受非合規 |
可接受用途:非安全性關鍵的檔案校驗和 (Checksum)、快取鍵產生、非機敏資料指紋、相容舊系統整合。
// 註冊服務
services.AddIdentityCore()
.AddPasswordHasher>(); // 內建 PBKDF2 + HMAC-SHA256
// 使用
var hasher = new PasswordHasher();
string hashed = hasher.HashPassword(null, "userPassword123"); // 自動產生 Salt + 迭代
bool verified = hasher.VerifyHashedPassword(null, hashed, "userPassword123")
== PasswordVerificationResult.Success;
若僅需快速相容舊系統 MD5 雜湊,**方法一** 最省事但受限於 .NET Framework;**方法二** 為標準、跨平台、可控制編碼與輸出格式的正規寫法。**嚴禁將 MD5 用於密碼儲存或安全性敏感場景**,請改用專門的慢速雜湊演算法。