在ASP.NET中,使用AES加密和解密数据需要遵循以下步骤:
using System.Security.Cryptography;
using System.Text;
public static string Encrypt(string plainText, string key, string iv)
{
byte[] plainBytes = Encoding.UTF8.GetBytes(plainText);
using (Aes aes = Aes.Create())
{
aes.Key = Encoding.UTF8.GetBytes(key);
aes.IV = Encoding.UTF8.GetBytes(iv);
ICryptoTransform encryptor = aes.CreateEncryptor(aes.Key, aes.IV);
byte[] encryptedBytes = encryptor.TransformFinalBlock(plainBytes, 0, plainBytes.Length);
return Convert.ToBase64String(encryptedBytes);
}
}
public static string Decrypt(string cipherText, string key, string iv)
{
byte[] cipherBytes = Convert.FromBase64String(cipherText);
using (Aes aes = Aes.Create())
{
aes.Key = Encoding.UTF8.GetBytes(key);
aes.IV = Encoding.UTF8.GetBytes(iv);
ICryptoTransform decryptor = aes.CreateDecryptor(aes.Key, aes.IV);
byte[] decryptedBytes = decryptor.TransformFinalBlock(cipherBytes, 0, cipherBytes.Length);
return Encoding.UTF8.GetString(decryptedBytes);
}
}
string plainText = "Hello, World!";
string key = "your_key_here"; // 请确保密钥长度为16、24或32字节
string iv = "your_iv_here"; // 初始化向量长度必须与AES密钥长度相同
string encryptedText = Encrypt(plainText, key, iv);
Console.WriteLine("Encrypted Text: " + encryptedText);
string decryptedText = Decrypt(encryptedText, key, iv);
Console.WriteLine("Decrypted Text: " + decryptedText);
请注意,为了确保数据安全,您应该使用安全的密钥和初始化向量。在实际应用中,建议将密钥和初始化向量存储在安全的地方,而不是硬编码在代码中。