c# AES加密完成代码
时间: 2024-09-28 14:06:04 浏览: 38
C#代码实现对AES加密解密
在C#中,可以使用`System.Security.Cryptography.Aes`类来实现AES加密。以下是一个基本的示例,展示了如何创建一个AES密钥、初始化加密上下文并加密数据:
```csharp
using System;
using System.IO;
using System.Security.Cryptography;
public static class AesEncryption
{
public static string Encrypt(string plainText, string password)
{
byte[] salt = new byte[16]; // Salt for PBKDF2 key derivation
using (RNGCryptoServiceProvider rng = new RNGCryptoServiceProvider())
{
rng.GetBytes(salt);
}
byte[] keyAndIV = GenerateKeyAndIV(password, salt);
using (Aes aes = Aes.Create())
{
aes.Key = keyAndIV.Take(16).ToArray(); // Key is first part of the derived bytes
aes.IV = keyAndIV.Skip(16).Take(16).ToArray(); // IV is the second part
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);
}
return Convert.ToBase64String(ms.ToArray());
}
}
}
private static byte[] GenerateKeyAndIV(string password, byte[] salt)
{
Rfc2898DeriveBytes pdb = new Rfc2898DeriveBytes(password, salt);
return pdb.GetBytes(32); // AES uses a 256-bit key, so we derive 32 bytes
}
// 示例:加密字符串
public static void Main()
{
string plainText = "This is an example text to be encrypted.";
string encryptedText = Encrypt(plainText, "MySecretPassword");
Console.WriteLine("Encrypted Text: " + encryptedText);
}
}
```
在这个例子中,我们首先生成一个随机盐值,然后使用`Rfc2898DeriveBytes`类从密码和盐值通过PBKDF2算法生成密钥和初始向量(IV)。接着,我们创建一个`Aes`对象,并设置其密钥和IV,然后使用`CreateEncryptor`方法创建一个加密器。最后,我们将明文写入加密流中。
阅读全文