Des加密解密(公共方法)

 1 public class Des
 2     {
 3         public static string Encrypt(string message, string key)
 4         {
 5             DES des = new DESCryptoServiceProvider();
 6             des.Key = Encoding.UTF8.GetBytes(key);
 7             des.IV = Encoding.UTF8.GetBytes(key);
 8             //des.Mode = CipherMode.ECB;
 9 
10             byte[] inputByteArray = Encoding.UTF8.GetBytes(message);
11 
12             System.IO.MemoryStream ms = new System.IO.MemoryStream();
13             CryptoStream cs = new CryptoStream(ms, des.CreateEncryptor(), CryptoStreamMode.Write);
14             cs.Write(inputByteArray, 0, inputByteArray.Length);
15             cs.FlushFinalBlock();
16             ms.Close();
17             StringBuilder ret = new StringBuilder();
18             foreach (byte b in ms.ToArray())
19             {
20                 ret.AppendFormat("{0:X2}", b);
21             }
22             return ret.ToString();
23 
24         }
25 
26         //DES解密
27         public static string Decrypt(string content, string key)
28         {
29             try
30             {
31                 DESCryptoServiceProvider provider = new DESCryptoServiceProvider();
32                 // 密钥
33                 provider.Key = Encoding.UTF8.GetBytes(key);
34                 // 偏移量
35                 provider.IV = Encoding.UTF8.GetBytes(key);
36                 byte[] buffer = new byte[content.Length / 2];
37                 for (int i = 0; i < (content.Length / 2); i++)
38                 {
39                     int num2 = Convert.ToInt32(content.Substring(i * 2, 2), 0x10);
40                     buffer[i] = (byte)num2;
41                 }
42                 using(MemoryStream stream = new MemoryStream())
43                 {
44                     CryptoStream stream2 = new CryptoStream(stream, provider.CreateDecryptor(), CryptoStreamMode.Write);
45                     stream2.Write(buffer, 0, buffer.Length);
46                     stream2.FlushFinalBlock();
47                     stream.Close();
48                     return Encoding.UTF8.GetString(stream.ToArray());
49                 }
50             }
51             catch (Exception) { return ""; }
52         }
53     }

 

posted @ 2019-09-23 21:07  醉酒三分醒  阅读(1240)  评论(0编辑  收藏  举报