C# DESC加密

DESC加密方法

直接上代码:

1、加密

 1     public static string Encrypt(string str, string key)
 2     {
 3         if (string.IsNullOrEmpty(str))
 4         {
 5             return "";
 6         }
 7         try
 8         {
 9             DESCryptoServiceProvider descsp = new DESCryptoServiceProvider();
10             byte[] keyBytes = Encoding.Unicode.GetBytes(key);//定义字节数组用来存储密钥
11             byte[] data = Encoding.Unicode.GetBytes(str);//定义字节数组,用来存储加密对象
12             using (MemoryStream memoryStream = new MemoryStream())
13             {
14                 using (CryptoStream cryptoStream = new CryptoStream(memoryStream, descsp.CreateEncryptor(keyBytes, keyBytes), CryptoStreamMode.Write))
15                 {
16                     cryptoStream.Write(data, 0, data.Length);
17                     cryptoStream.FlushFinalBlock();//释放解秘流
18                     return Convert.ToBase64String(memoryStream.ToArray());
19                 }
20             }
21         }
22         catch (Exception ex)
23         {
24             // ignored
25         }
26         return string.Empty;
27     }

2、解密

 1     public static string Decrypt(string str, string key)
 2     {
 3         try
 4         {
 5             //实例化加密对象
 6             DESCryptoServiceProvider descsp = new DESCryptoServiceProvider();
 7             byte[] keyBytes = Encoding.Unicode.GetBytes(key);//定义字节数组用来存储密钥
 8             byte[] strBytes = Convert.FromBase64String(str);//定义字节数组,用来存储加密对象
 9             //实例化内存对象
10             using (MemoryStream stream = new MemoryStream())
11             {
12                 using (CryptoStream stream2 = new CryptoStream(stream, descsp.CreateDecryptor(keyBytes, keyBytes), CryptoStreamMode.Write))
13                 {
14                     stream2.Write(strBytes, 0, strBytes.Length);
15                     stream2.FlushFinalBlock();//释放解秘流
16                 }
17                 return Encoding.Unicode.GetString(stream.ToArray());
18             }
19         }
20         catch
21         {
22             return string.Empty;
23         }
24     }

设置一个_securityKey字符串,加密、解密的密钥要同一个才行。

因此正如其它人加密后的文件,用常用方法是打不开的,密钥不一样~

注:密钥不能超过8个字节,比如“1234”

posted @ 2016-08-28 23:38  唐宋元明清2188  阅读(1259)  评论(1编辑  收藏  举报