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加密解密的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!
- 2022-03-01沐雪多租宝商城源码从.NetCore3.1升级到.Net6的步骤
- 2024-11-18微软研究:RAG系统的四个层次提升理解与回答能力
- 2024-11-15C#中怎么从PEM格式的证书中提取公钥?-icode9专业技术文章分享
- 2024-11-14云架构设计——如何用diagrams.net绘制专业的AWS架构图?
- 2024-05-08首个适配Visual Studio平台的国产智能编程助手CodeGeeX正式上线!C#程序员必备效率神器!
- 2024-03-30C#设计模式之十六迭代器模式(Iterator Pattern)【行为型】
- 2024-03-29c# datetime tryparse
- 2024-02-21list find index c#
- 2024-01-24convert toint32 c#
- 2024-01-24Advanced .Net Debugging 1:你必须知道的调试工具