In the field of cryptography, advanced encryption standards (AES) are a powerful and widely accepted algorithm for protecting sensitive data. However, understanding and implementing AES encryption in a programming language such as C# seems to be a difficult task.
rijndaelmanaged: built -in provider
Fortunately, the .NET framework provided an easy -to -use AES encryption implementation through the Rijndaelmanaged class. This provides a simplified way to process the complexity of AES encryption and decryption.
The example code of encryption and secret
In order to explain the working principle of Rijndaelmanaged, let's see a concise code example:
Summary
using System; using System.Security.Cryptography; using System.IO; namespace AES加密示例 { class Program { static void Main(string[] args) { // 要加密的原始数据 string original = "机密信息"; // 生成新的密钥和初始化向量 (IV) using (RijndaelManaged rijndael = new RijndaelManaged()) { rijndael.GenerateKey(); rijndael.GenerateIV(); // 加密 byte[] encryptedBytes = EncryptStringToBytes(original, rijndael.Key, rijndael.IV); // 解密 string decryptedString = DecryptStringFromBytes(encryptedBytes, rijndael.Key, rijndael.IV); // 显示结果 Console.WriteLine("原始数据:{0}", original); Console.WriteLine("加密后:{0}", Convert.ToBase64String(encryptedBytes)); Console.WriteLine("解密后:{0}", decryptedString); } } static byte[] EncryptStringToBytes(string plainText, byte[] key, byte[] iv) { using (RijndaelManaged rijndael = new RijndaelManaged()) { rijndael.Key = key; rijndael.IV = iv; using (ICryptoTransform encryptor = rijndael.CreateEncryptor()) using (MemoryStream msEncrypt = new MemoryStream()) using (CryptoStream csEncrypt = new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write)) using (StreamWriter swEncrypt = new StreamWriter(csEncrypt)) { swEncrypt.Write(plainText); return msEncrypt.ToArray(); } } } static string DecryptStringFromBytes(byte[] encryptedBytes, byte[] key, byte[] iv) { using (RijndaelManaged rijndael = new RijndaelManaged()) { rijndael.Key = key; rijndael.IV = iv; using (ICryptoTransform decryptor = rijndael.CreateDecryptor()) using (MemoryStream msDecrypt = new MemoryStream(encryptedBytes)) using (CryptoStream csDecrypt = new CryptoStream(msDecrypt, decryptor, CryptoStreamMode.Read)) using (StreamReader srDecrypt = new StreamReader(csDecrypt)) { return srDecrypt.ReadToEnd(); } } } } }
The above is the detailed content of How Can I Easily Implement AES Encryption and Decryption in C#?. For more information, please follow other related articles on the PHP Chinese website!