c# Aes加密解密

 1 注:key的字符串长度必须为32  iv的字符长度必须为16
 2 
 3 using System;
 4 using System.Collections.Generic;
 5 using System.IO;
 6 using System.Linq;
 7 using System.Security.Cryptography;
 8 using System.Text;
 9 
10 namespace Des加密
11 {
12     public static class AESClass
13     {
14         /// <summary>
15         /// AES加密
16         /// </summary>
17         /// <param name="inputdata">输入的数据</param>
18         /// <param name="iv">向量128位(Iv的字符串长度为16)</param>
19         /// <param name="key">加密密钥(key的长度为32)</param>
20         /// <returns></returns>
21         public static byte[] AESEncrypt(string encryptString, string key, string iv)
22         {
23             //分组加密算法   
24             SymmetricAlgorithm Aes = Rijndael.Create();
25             byte[] inputByteArray = Encoding.UTF8.GetBytes(encryptString);//得到需要加密的字节数组       
26             //设置密钥及密钥向量
27             Aes.Key = Encoding.UTF8.GetBytes(key);
28             Aes.IV = Encoding.UTF8.GetBytes(iv); ;
29             using (MemoryStream ms = new MemoryStream())
30             {
31                 using (CryptoStream cs = new CryptoStream(ms, Aes.CreateEncryptor(), CryptoStreamMode.Write))
32                 {
33                     cs.Write(inputByteArray, 0, inputByteArray.Length);
34                     cs.FlushFinalBlock();
35                     byte[] cipherBytes = ms.ToArray();//得到加密后的字节数组   
36                     cs.Close();
37                     ms.Close();
38                     return cipherBytes;
39                     //return Convert.ToBase64String(cipherBytes); //返回字符串
40                 }
41             }
42         }
43 
44 
45         /// <summary>
46         /// AES解密
47         /// </summary>
48         /// <param name="inputdata">输入的数据</param>
49         /// <param name="iv">向量128位(Iv的字符串长度为16)</param>
50         /// <param name="key">加密密钥(key的长度为32)</param>
51         /// <returns></returns>
52         public static byte[] AESDecrypt(string decryptString, string key, string iv)
53         {
54             SymmetricAlgorithm Aes = Rijndael.Create();
55             Aes.Key = Encoding.UTF8.GetBytes(key);
56             Aes.IV = Encoding.UTF8.GetBytes(iv);
57             byte[] inputByteArray = Convert.FromBase64String(decryptString);//得到需要加密的字节数组
58             byte[] decryptBytes = new byte[inputByteArray.Length];
59             using (MemoryStream ms = new MemoryStream(inputByteArray))
60             {
61                 using (CryptoStream cs = new CryptoStream(ms, Aes.CreateDecryptor(), CryptoStreamMode.Read))
62                 {
63                     cs.Read(decryptBytes, 0, decryptBytes.Length);
64                     cs.Close();
65                     ms.Close();
66                 }
67             }
68             return decryptBytes;
69             //return Encoding.UTF8.GetString(decryptBytes); //返回字符串
70         }
71     }
72 }

 

posted @ 2014-09-21 23:18  以沫浅夏  阅读(1523)  评论(0编辑  收藏  举报