C# AES CBC加密解密

 1         public static string Decrypt(string combinedString, string keyString)
 2         {
 3             string plainText;
 4             byte[] combinedData = Convert.FromBase64String(combinedString);
 5             Aes aes = Aes.Create();
 6             aes.Key = Encoding.UTF8.GetBytes(keyString);
 7             byte[] iv = new byte[aes.BlockSize / 8];
 8             byte[] cipherText = new byte[combinedData.Length - iv.Length];
 9             Array.Copy(combinedData, iv, iv.Length);
10             Array.Copy(combinedData, iv.Length, cipherText, 0, cipherText.Length);
11             aes.IV = iv;
12             aes.Mode = CipherMode.CBC;
13             ICryptoTransform decipher = aes.CreateDecryptor(aes.Key, aes.IV);
14 
15             using (MemoryStream ms = new MemoryStream(cipherText))
16             {
17                 using (CryptoStream cs = new CryptoStream(ms, decipher, CryptoStreamMode.Read))
18                 {
19                     using (StreamReader sr = new StreamReader(cs))
20                     {
21                         plainText = sr.ReadToEnd();
22                     }
23                 }
24 
25                 return plainText;
26             }
27         }
28 
29         public static string Encrypt(string plainText, string keyString)
30         {
31             byte[] cipherData;
32             Aes aes = Aes.Create();
33             aes.Key = Encoding.UTF8.GetBytes(keyString);
34             aes.GenerateIV();
35             aes.Mode = CipherMode.CBC;
36             ICryptoTransform cipher = aes.CreateEncryptor(aes.Key, aes.IV);
37 
38             using (MemoryStream ms = new MemoryStream())
39             {
40                 using (CryptoStream cs = new CryptoStream(ms, cipher, CryptoStreamMode.Write))
41                 {
42                     using (StreamWriter sw = new StreamWriter(cs))
43                     {
44                         sw.Write(plainText);
45                     }
46                 }
47 
48                 cipherData = ms.ToArray();
49             }
50 
51             byte[] combinedData = new byte[aes.IV.Length + cipherData.Length];
52             Array.Copy(aes.IV, 0, combinedData, 0, aes.IV.Length);
53             Array.Copy(cipherData, 0, combinedData, aes.IV.Length, cipherData.Length);
54             return Convert.ToBase64String(combinedData);
55         }

 

posted @ 2022-05-26 22:46  dongzhaosheng73  阅读(584)  评论(0编辑  收藏  举报