MD5相關類:
System.Security.Cryptography.MD5
System.Security.Cryptography.MD5CryptoServiceProvider()
System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile(strSource, "MD5")
SHA1相關類:
System.Security.Cryptography.SHA1
System.Security.Cryptography.SHA1CryptoServiceProvider()
System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile(strSource, "SHA1")
1/**//// <summary>
2 /// 方法一:通過使用 new 運算符建立對象
3 /// </summary>
4 /// <param name="strSource">需要加密的明文</param>
5 /// <returns>傳回16位加密結果,該結果取32位加密結果的第9位到25位</returns>
6 public string Get_MD5_Method1(string strSource)
7 {
8 //new
9 System.Security.Cryptography.MD5 md5 =
new System.Security.Cryptography.MD5CryptoServiceProvider();
10
11 //擷取密文位元組數組
12 byte[] bytResult = md5.ComputeHash(System.Text.Encoding.Default.GetBytes(strSource));
13
14 //轉換成字元串,并取9到25位
15 string strResult = BitConverter.ToString(bytResult, 4, 8);
16 //轉換成字元串,32位
17 //string strResult = BitConverter.ToString(bytResult);
18
19 //BitConverter轉換出來的字元串會在每個字元中間産生一個分隔符,需要去除掉
20 strResult = strResult.Replace("-", "");
21 return strResult;
22 }
23
24 /**//// <summary>
25 /// 方法二:通過調用特定加密算法的抽象類上的 Create 方法,建立實作特定加密算法的對象。
26 /// </summary>
27 /// <param name="strSource">需要加密的明文</param>
28 /// <returns>傳回32位加密結果</returns>
29 public string Get_MD5_Method2(string strSource)
30 {
31 string strResult = "";
32
33 //Create
34 System.Security.Cryptography.MD5 md5 = System.Security.Cryptography.MD5.Create();
35
36 //注意編碼UTF8、UTF7、Unicode等的選擇
37 byte[] bytResult = md5.ComputeHash(System.Text.Encoding.UTF8.GetBytes(strSource));
38
39 //位元組類型的數組轉換為字元串
40 for (int i = 0; i < bytResult.Length; i++)
41 {
42 //16進制轉換
43 strResult = strResult + bytResult[i].ToString("X");
44 }
45 return strResult;
46 }
47
48 /**//// <summary>
49 /// 方法三:直接使用HashPasswordForStoringInConfigFile生成
50 /// </summary>
51 /// <param name="strSource">需要加密的明文</param>
52 /// <returns>傳回32位加密結果</returns>
53 public string Get_MD5_Method3(string strSource)
54 {
55 return System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile(strSource,
"MD5");
56 }
部落格園大道至簡
<a href="http://www.cnblogs.com/jams742003/" target="_blank">http://www.cnblogs.com/jams742003/</a>
轉載請注明:部落格園