在C#中实现AES加密可以通过使用AesManaged
类来实现。下面是一个简单的示例代码:
using System;
using System.IO;
using System.Security.Cryptography;
using System.Text;
public class AesEncryption
{
public static string Encrypt(string plainText, string key, string iv)
{
byte[] keyBytes = Encoding.UTF8.GetBytes(key);
byte[] ivBytes = Encoding.UTF8.GetBytes(iv);
byte[] encryptedBytes;
using (AesManaged aes = new AesManaged())
{
aes.Key = keyBytes;
aes.IV = ivBytes;
ICryptoTransform encryptor = aes.CreateEncryptor(aes.Key, aes.IV);
using (MemoryStream ms = new MemoryStream())
{
using (CryptoStream cs = new CryptoStream(ms, encryptor, CryptoStreamMode.Write))
{
using (StreamWriter sw = new StreamWriter(cs))
{
sw.Write(plainText);
}
encryptedBytes = ms.ToArray();
}
}
}
return Convert.ToBase64String(encryptedBytes);
}
public static string Decrypt(string encryptedText, string key, string iv)
{
byte[] keyBytes = Encoding.UTF8.GetBytes(key);
byte[] ivBytes = Encoding.UTF8.GetBytes(iv);
byte[] encryptedBytes = Convert.FromBase64String(encryptedText);
string decryptedText;
using (AesManaged aes = new AesManaged())
{
aes.Key = keyBytes;
aes.IV = ivBytes;
ICryptoTransform decryptor = aes.CreateDecryptor(aes.Key, aes.IV);
using (MemoryStream ms = new MemoryStream(encryptedBytes))
{
using (CryptoStream cs = new CryptoStream(ms, decryptor, CryptoStreamMode.Read))
{
using (StreamReader sr = new StreamReader(cs))
{
decryptedText = sr.ReadToEnd();
}
}
}
}
return decryptedText;
}
}
使用以上代码,你可以通过调用AesEncryption.Encrypt
方法进行加密,调用AesEncryption.Decrypt
方法进行解密。请注意,你需要提供一个密钥(key
)和一个初始化向量(iv
),这两个值必须是相同的才能正确解密。