C# AES CBC加密解密

2022/5/27 1:20:04

本文主要是介绍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         }

 

搜索

复制



这篇关于C# AES CBC加密解密的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!


扫一扫关注最新编程教程