在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
),這兩個值必須是相同的才能正確解密。