找回密碼
 註冊
搜索
查看: 4572|回復: 0

C# MD5 <=> MSSQL MD5

[複製鏈接]
發表於 2014-8-5 11:19:18 | 顯示全部樓層 |閱讀模式
  1. public string CalculateMD5Hash(string input)
  2. {
  3.         //MD5 Encode但不轉Base64 String
  4.         //        MSSQL 使用
  5.         //        select SUBSTRING(sys.fn_sqlvarbasetostr(HASHBYTES('MD5','加密字串')),3,32)
  6.         //        可得同樣結果

  7.         // step 1, calculate MD5 hash from input
  8.         MD5 md5 = System.Security.Cryptography.MD5.Create();
  9.         byte[] inputBytes = System.Text.Encoding.ASCII.GetBytes(input);
  10.         byte[] hash = md5.ComputeHash(inputBytes);

  11.         // step 2, convert byte array to hex string
  12.         StringBuilder sb = new StringBuilder();
  13.         for (int i = 0; i < hash.Length; i++)
  14.         {
  15.                 sb.Append(hash[i].ToString("x2"));
  16.         }
  17.         return sb.ToString();
  18. }
複製代碼
  • 以上範例是用ASCII方式進行編碼,如果要修改為Unicode,則要改為System.Text.Encoding.Unicode.GetBytes,相對的MSSQL的加密字串前面也要加N Ex: N'加密字串'。
  • 如果要將產生的MD5改為大寫輸出,則要修改 sb.Append(hash[i ].ToString("x2")) 中的 x2,將之改為 X2,就會變大寫。

Reference:
C# - How do I calculate a MD5 hash from a string?
http://blogs.msdn.com/b/csharpfa ... a-string_3f00_.aspx
您需要登錄後才可以回帖 登錄 | 註冊

本版積分規則

Archiver|手機版|彩色筆小沛的知識庫

GMT+8, 2024-4-20 03:11 , Processed in 0.016223 second(s), 9 queries , Gzip On, MemCache On.

Powered by Discuz! X3.5

© 2001-2024 Discuz! Team.

快速回復 返回頂部 返回列表