且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

asp.net 加密类

更新时间:2022-08-12 22:17:07

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 }

 

 

博客园大道至简

http://www.cnblogs.com/jams742003/

转载请注明:博客园