首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> .NET 網頁程式設計 >> 關於.NET

.NET MD5 與 SHA 雜湊加密實作:從 Base64 到十六進位輸出的正確姿勢

     編輯:關於.NET

網路上流傳的 MD5 範例多回傳 Base64 字串(含特殊符號),但資料庫常儲存 32 字元大寫十六進位格式(如 BABA327D241746EE0829E7E88117D4D5)。本文釐清輸出格式差異,提供標準實作並對比 FormsAuthentication.HashPasswordForStoringInConfigFile 內部原理。

常見誤區:Base64 ≠ 十六進位

// 錯誤示範:輸出 Base64(含 + / = 等符號)
public static string MD5(string input) {
  using (var md5 = MD5.Create()) {
    byte[] hash = md5.ComputeHash(Encoding.UTF8.GetBytes(input));
    return Convert.ToBase64String(hash); // 例:afw1fw3j=-
  }
}

資料庫儲存的通常是無分隔符的十六進位字串,需轉換格式。

正確實作:BitConverter.ToString + 移除連字號

public static string ComputeMD5(string input) {
  using (var md5 = MD5.Create()) {
    byte[] hash = md5.ComputeHash(Encoding.UTF8.GetBytes(input));
    // BitConverter 輸出 "BA-BA-32-7D...",移除 - 即得標準格式
    return BitConverter.ToString(hash).Replace("-", "");
  }
}

public static string ComputeSHA1(string input) {
  using (var sha1 = SHA1.Create()) {
    byte[] hash = sha1.ComputeHash(Encoding.UTF8.GetBytes(input));
    return BitConverter.ToString(hash).Replace("-", "");
  }
}

關鍵點:
1. 統一使用 Encoding.UTF8 處理中文無亂碼。
2. BitConverter.ToString 產生大寫十六進位並以 - 分隔,Replace("-", "") 效能足夠。
3. 建議使用 using 確保 HashAlgorithm 釋放資源。

進階:支援多種演算法的通用方法

public static string ComputeHash(string input, string algorithmName) {
  using (var alg = HashAlgorithm.Create(algorithmName.ToUpper())) {
    if (alg == null) throw new ArgumentException("Unsupported algorithm");
    byte[] hash = alg.ComputeHash(Encoding.UTF8.GetBytes(input));
    return BitConverter.ToString(hash).Replace("-", "");
  }
}
// 用法:ComputeHash("text", "MD5") / "SHA1" / "SHA256" / "SHA512"

內建工具:FormsAuthentication.HashPasswordForStoringInConfigFile

.NET Framework 內建此方法,僅支援 MD5/SHA1,內部實現:

public static string HashPasswordForStoringInConfigFile(string password, string format) {
  HashAlgorithm alg;
  if (format.Equals("sha1", StringComparison.OrdinalIgnoreCase))
    alg = SHA1.Create();
  else if (format.Equals("md5", StringComparison.OrdinalIgnoreCase))
    alg = MD5.Create();
  else
    throw new ArgumentException("Invalid format");
  // 內部呼叫 MachineKeySection.ByteArrayToHexString 輸出十六進位
  return ByteArrayToHexString(alg.ComputeHash(Encoding.UTF8.GetBytes(password)));
}

注意:ASP.NET Core 已標記過時,建議改用 Microsoft.AspNetCore.Cryptography.KeyDerivation 或上述通用方法。

線上驗證工具推薦

ASP.NET Resources Password Hash Tool 可快速驗證 MD5/SHA1/SHA256 輸出,方便除錯比對。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved