RijndaelManaged类是.NET框架中用于对称加密和解密数据的类。下面是一个简单的示例,演示如何使用RijndaelManaged类进行数据加密和解密:
using System;
using System.IO;
using System.Security.Cryptography;
using System.Text;
public class Program
{
static void Main()
{
string plainText = "Hello, world!";
string key = "0123456789abcdef";
string iv = "fedcba9876543210";
byte[] encryptedData = EncryptData(plainText, key, iv);
string decryptedText = DecryptData(encryptedData, key, iv);
Console.WriteLine("Encrypted Data: " + Convert.ToBase64String(encryptedData));
Console.WriteLine("Decrypted Text: " + decryptedText);
}
static byte[] EncryptData(string plainText, string key, string iv)
{
using (RijndaelManaged rijndael = new RijndaelManaged())
{
rijndael.Key = Encoding.UTF8.GetBytes(key);
rijndael.IV = Encoding.UTF8.GetBytes(iv);
ICryptoTransform encryptor = rijndael.CreateEncryptor(rijndael.Key, rijndael.IV);
using (MemoryStream ms = new MemoryStream())
{
using (CryptoStream cs = new CryptoStream(ms, encryptor, CryptoStreamMode.Write))
{
byte[] plainBytes = Encoding.UTF8.GetBytes(plainText);
cs.Write(plainBytes, 0, plainBytes.Length);
}
return ms.ToArray();
}
}
}
static string DecryptData(byte[] encryptedData, string key, string iv)
{
using (RijndaelManaged rijndael = new RijndaelManaged())
{
rijndael.Key = Encoding.UTF8.GetBytes(key);
rijndael.IV = Encoding.UTF8.GetBytes(iv);
ICryptoTransform decryptor = rijndael.CreateDecryptor(rijndael.Key, rijndael.IV);
using (MemoryStream ms = new MemoryStream(encryptedData))
{
using (CryptoStream cs = new CryptoStream(ms, decryptor, CryptoStreamMode.Read))
{
using (StreamReader sr = new StreamReader(cs))
{
return sr.ReadToEnd();
}
}
}
}
}
}
在上面的示例中,我们定义了EncryptData和DecryptData两个方法来分别进行数据的加密和解密。在Main方法中,我们演示了如何使用这两个方法来加密和解密数据。请注意,需要提供一个密钥和初始化向量(IV)来进行加密和解密操作。