(转)C# MD5

 本文原地址:http://blog.csdn.net/zhoufoxcn/article/details/1497099 作者:周公

代码如下:

[c-sharp] view plaincopy
  1. using System;  
  2. using System.Text;  
  3. using System.Security.Cryptography;  
  4.   
  5. namespace Common  
  6. {  
  7.     /// <summary>  
  8.     /// 一个实现MD5散列字符串的类  
  9.     /// 作者:周公  
  10.     /// 日期:2007  
  11.     /// </summary>  
  12.     public sealed class MD5Hashing  
  13.     {  
  14.         private static MD5 md5 = MD5.Create();  
  15.         //私有化构造函数  
  16.         private MD5Hashing()  
  17.         {  
  18.         }  
  19.         /// <summary>  
  20.         /// 使用utf8编码将字符串散列  
  21.         /// </summary>  
  22.         /// <param name="sourceString">要散列的字符串</param>  
  23.         /// <returns>散列后的字符串</returns>  
  24.        public static string HashString(string sourceString)  
  25.        {  
  26.             return HashString(Encoding.UTF8, sourceString);  
  27.        }  
  28.        /// <summary>  
  29.        /// 使用指定的编码将字符串散列  
  30.        /// </summary>  
  31.        /// <param name="encode">编码</param>  
  32.        /// <param name="sourceString">要散列的字符串</param>  
  33.        /// <returns>散列后的字符串</returns>  
  34.         public static string HashString(Encoding encode, string sourceString)  
  35.         {  
  36.             byte[] source = md5.ComputeHash(encode.GetBytes(sourceString));  
  37.             StringBuilder sBuilder = new StringBuilder();  
  38.             for (int i = 0; i < source.Length; i++)  
  39.             {  
  40.                 sBuilder.Append(source[i].ToString("x2"));  
  41.             }  
  42.             return sBuilder.ToString();  
  43.         }  
  44.     }  
  45. }  
  

2010-04-05日注:

上面的代码对字符串进行MD5哈希计算的结果与下面的一句话等效:

System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile(str, "MD5").ToLower())

其中str是要进行哈希计算的字符串,如果在ASP.NET应用中倒也罢了,如果在非ASP.NET应用中还需要增加对System.Web.dll的引用。

其它参考文章:http://www.cnblogs.com/94cool/archive/2010/05/25/1743642.html

       http://www.cnblogs.com/ahui/archive/2010/12/23/1914586.html

        http://www.cnblogs.com/Ruiky/archive/2012/04/16/2451663.html

原文地址:https://www.cnblogs.com/hhhh2010/p/3666401.html