首页 > 其他 > 详细

Des加密解密(公共方法)

时间:2019-09-23 22:57:47      阅读:138      评论:0      收藏:0      [点我收藏+]
 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     }

 

Des加密解密(公共方法)

原文:https://www.cnblogs.com/hugeboke/p/11574831.html

(1)
(1)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!