码迷,mamicode.com
首页 > Windows程序 > 详细

C# 128位AES 加密解密 (转)

时间:2016-10-14 16:41:48      阅读:283      评论:0      收藏:0      [点我收藏+]

标签:

/// AES加密
2         /// </summary>
3         /// <param name="inputdata">输入的数据</param>
4         /// <param name="iv">向量128位</param>
5         /// <param name="strKey">加密密钥</param>
6         /// <returns></returns>
7         public static byte[] AESEncrypt(byte[] inputdata, byte[] iv, string strKey)
8         {
9             //分组加密算法  
10             SymmetricAlgorithm des = Rijndael.Create();
11             byte[] inputByteArray = inputdata;//得到需要加密的字节数组      
12             //设置密钥及密钥向量
13             des.Key = Encoding.UTF8.GetBytes(strKey.Substring(0, 32));
14             des.IV = iv;
15             using (MemoryStream ms = new MemoryStream())
16             {
17                 using (CryptoStream cs = new CryptoStream(ms, des.CreateEncryptor(), CryptoStreamMode.Write))
18                 {
19                     cs.Write(inputByteArray, 0, inputByteArray.Length);
20                     cs.FlushFinalBlock();
21                     byte[] cipherBytes = ms.ToArray();//得到加密后的字节数组  
22                     cs.Close();
23                     ms.Close();                  
24                     return cipherBytes;
25                 }
26             }
27         }
28
29
30         /// <summary>
31         /// AES解密
32         /// </summary>
33         /// <param name="inputdata">输入的数据</param>
34         /// <param name="iv">向量128</param>
35         /// <param name="strKey">key</param>
36         /// <returns></returns>
37         public static byte[] AESDecrypt(byte[] inputdata, byte[] iv, string strKey)
38         {
39             SymmetricAlgorithm des = Rijndael.Create();
40             des.Key = Encoding.UTF8.GetBytes(strKey.Substring(0, 32));
41             des.IV = iv;
42             byte[] decryptBytes = new byte[inputdata.Length];
43             using (MemoryStream ms = new MemoryStream(inputdata))
44             {
45                 using (CryptoStream cs = new CryptoStream(ms, des.CreateDecryptor(), CryptoStreamMode.Read))
46                 {
47                     cs.Read(decryptBytes, 0, decryptBytes.Length);
48                     cs.Close();
49                     ms.Close();
50                 }
51             }
52             return decryptBytes;
53         }

C# 128位AES 加密解密 (转)

标签:

原文地址:http://www.cnblogs.com/jason-davis/p/5960636.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!