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

徹底解決 ASP.NET MD5 加密中文結果與 ASP 不一致問題

     編輯:關於ASP.NET

現象

  • 純英文:ASP.NET FormsAuthentication.HashPasswordForStoringInConfigFile 與 ASP MD5() 結果一致(大小寫差異)。
  • 含中文:結果**不一致**。

根因:ASP.NET 預設 UTF-8,經典 ASP 預設 GB2312,編碼不同導致雜湊不同。

解決:使用 MD5CryptoServiceProvider 指定編碼

// 產生與 ASP (GB2312) 相同結果
MD5CryptoServiceProvider md5 = new MD5CryptoServiceProvider();
string result = BitConverter.ToString(
    md5.ComputeHash(Encoding.GetEncoding("gb2312").GetBytes("木子屋"))
).Replace("-", "");
// 結果: 0A40A90190DA023AE7AA17771663A41E

// 產生 UTF-8 結果 (與 FormsAuthentication 一致)
string resultUtf8 = BitConverter.ToString(
    md5.ComputeHash(Encoding.GetEncoding("utf-8").GetBytes("木子屋"))
).Replace("-", "");
// 結果: 34D9CBD5164C47058DFA3AF832E2D1DC

進階問題:跨頁傳遞中文參數

  1. 無法知道對方頁面編碼。
  2. 若編碼不一致,Request 取得參數即亂碼,加密無意義。

建議:統一全站編碼(``),或雙方約定編碼並一致部署。

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