c#加密解密方法

 1 using System;
 2 using System.Text;
 3 using System.IO;
 4 using System.Security.Cryptography;
 5 
 6 namespace Logistics 
 7 {
 8     /// <summary>
 9     /// 字符串加密解密类
10     /// </summary>
11     public sealed class StringSecurity
12     {
13         private StringSecurity() { }
14 
15         #region DES 加密/解密
16 
17         private static byte[] key = ASCIIEncoding.ASCII.GetBytes("uiertysd");
18         private static byte[] iv = ASCIIEncoding.ASCII.GetBytes("99008855");
19 
20         /// <summary>
21         /// DES加密。
22         /// </summary>
23         /// <param name="inputString">输入字符串。</param>
24         /// <returns>加密后的字符串。</returns>
25         public static string DESEncrypt(string inputString)
26         {
27             MemoryStream ms = null;
28             CryptoStream cs = null;
29             StreamWriter sw = null;
30 
31             DESCryptoServiceProvider des = new DESCryptoServiceProvider();
32             try
33             {
34                 ms = new MemoryStream();
35                 cs = new CryptoStream(ms, des.CreateEncryptor(key, iv), CryptoStreamMode.Write);
36                 sw = new StreamWriter(cs);
37                 sw.Write(inputString);
38                 sw.Flush();
39                 cs.FlushFinalBlock();
40                 return Convert.ToBase64String(ms.GetBuffer(), 0, (int)ms.Length);
41             }
42             finally
43             {
44                 if (sw != null) sw.Close();
45                 if (cs != null) cs.Close();
46                 if (ms != null) ms.Close();
47             }
48         }
49 
50         /// <summary>
51         /// DES解密。
52         /// </summary>
53         /// <param name="inputString">输入字符串。</param>
54         /// <returns>解密后的字符串。</returns>
55         public static string DESDecrypt(string inputString)
56         {
57             MemoryStream ms = null;
58             CryptoStream cs = null;
59             StreamReader sr = null;
60 
61             DESCryptoServiceProvider des = new DESCryptoServiceProvider();
62             try
63             {
64                 ms = new MemoryStream(Convert.FromBase64String(inputString));
65                 cs = new CryptoStream(ms, des.CreateDecryptor(key, iv), CryptoStreamMode.Read);
66                 sr = new StreamReader(cs);
67                 return sr.ReadToEnd();
68             }
69             finally
70             {
71                 if (sr != null) sr.Close();
72                 if (cs != null) cs.Close();
73                 if (ms != null) ms.Close();
74             }
75         }
76 
77         #endregion
78     }
79 }

猜你喜欢

转载自www.cnblogs.com/leizhui/p/11750408.html