使用方法:
建立c#控制台應用程式,將下面的代碼拷貝進去就可以使用了。代碼解釋見注釋。
例1
using System;<br />using System.Security.Cryptography;<br />using System.Text;</p><p>class Example<br />{<br /> // Hash an input string and return the hash as<br /> // a 32 character hexadecimal string.<br /> static string getMd5Hash(string input)<br /> {<br /> // Create a new instance of the MD5CryptoServiceProvider object.<br /> MD5CryptoServiceProvider md5Hasher = new MD5CryptoServiceProvider();<br /> // Convert the input string to a byte array and compute the hash.<br /> byte[] data = md5Hasher.ComputeHash(Encoding.Default.GetBytes(input));<br /> // Create a new Stringbuilder to collect the bytes<br /> // and create a string.<br /> StringBuilder sBuilder = new StringBuilder();<br /> // Loop through each byte of the hashed data<br /> // and format each one as a hexadecimal string.<br /> for (int i = 0; i < data.Length; i++)<br /> {<br /> sBuilder.Append(data[i].ToString("x2"));<br /> }<br /> // Return the hexadecimal string.<br /> // return sBuilder.ToString();//返回32位的MD5值<br /> return sBuilder.ToString().Substring(8, 16);//返回16位的MD5值<br /> /*String.SubString(int index,int length)<br /> * index:開始位置,從0開始<br /> * length:你要取的子字串的長度<br /> */<br /> }<br /> // Verify a hash against a string.<br /> static bool verifyMd5Hash(string input, string hash)<br /> {<br /> // Hash the input.<br /> string hashOfInput = getMd5Hash(input);<br /> // Create a StringComparer an comare the hashes.<br /> StringComparer comparer = StringComparer.OrdinalIgnoreCase;<br /> if (0 == comparer.Compare(hashOfInput, hash))<br /> {<br /> return true;<br /> }<br /> else<br /> {<br /> return false;<br /> }<br /> }<br /> static void Main()<br /> {<br /> string source = "Hello World!";<br /> string hash = getMd5Hash(source);<br /> Console.WriteLine("The MD5 hash of " + source + " is: " + hash + ".");<br /> Console.WriteLine("Verifying the hash...");<br /> if (verifyMd5Hash(source, hash))<br /> {<br /> Console.WriteLine("The hashes are the same.");<br /> }<br /> else<br /> {<br /> Console.WriteLine("The hashes are not same.");<br /> }<br /> }<br />}<br />// This code example produces the following output:<br />//<br />// The MD5 hash of Hello World! is: ed076287532e86365e841e92bfc50d8c.<br />// Verifying the hash...<br />// The hashes are the same.<br />/*<br /> * Encoding.ASCII.GetBytes(inputString)用於以ASCII方式將一個字串轉換成一個位元組數組,<br /> * 原因是ComputeHash方法只接收Byte[]參數,後面的內容就是將加密後的Byte[]連成一個字串,<br /> * AppendFormat中的格式字串{0:x2}是指將數組中每一個字元格式設定化為十六進位,精度為2<br /> */
例2:和例1基本相同
using System;<br />using System.Collections.Generic;<br />using System.Text;<br />using System.Security.Cryptography;</p><p>namespace ConsoleApplication1<br />{<br /> class Program<br /> {<br /> public static void Main(string[] args)<br /> {<br /> Console.WriteLine("hello world !");<br /> string str = Encryption.StringToMD5Hash("xuwei");//靜態方法可以直接通過類名來調用<br /> Console.WriteLine(str);<br /> }<br /> }<br /> class Encryption//32為的md5加密<br /> {<br /> public static string StringToMD5Hash(string inputString)<br /> {<br /> MD5CryptoServiceProvider md5 = new MD5CryptoServiceProvider();<br /> byte[] encryptedBytes = md5.ComputeHash(Encoding.ASCII.GetBytes(inputString));<br /> StringBuilder sb = new StringBuilder();<br /> for (int i = 0; i < encryptedBytes.Length; i++)<br /> {<br /> sb.AppendFormat("{0:x2}", encryptedBytes[i]);<br /> }<br /> return sb.ToString();<br /> }</p><p> }</p><p>}<br />
3月8號更新
整理部落格的時候發現MD5的求法其實已經內建了,代碼如下:
//註:自加求md5密碼的靜態方法<br />public static string GetMd5(string str)//求MD5<br />{<br /> return System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile(str, "MD5").ToLower().Substring(8,16);<br />}<br />