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

Posted Jason_davis

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了C# 128位AES 加密解密 (转)相关的知识,希望对你有一定的参考价值。

/// 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 加密解密 (转)的主要内容,如果未能解决你的问题,请参考以下文章

[转]AES加密遇到的问题

用c#做aes加密 为啥在线解密解不了

AES 加密位: 128位,加密模式:CBC, 填充模式:Zeros

在 C# 中使用 AES 加密

AES加密算法256位密钥与128位密钥的不同是啥?

AES加密解密通用版Object-C / C# / JAVA