public class Protector
{
//盐
private static readonly byte[] salt = Encoding.Unicode.GetBytes("7BANANAS");
//迭代
private static readonly int iterations = 2000;
public static string Encrypt(string plainText, string password)
{
byte[] encryptedBytes;
byte[] plainBytes = Encoding.Unicode.GetBytes(plainText);
Rijndael aes = Rijndael.Create();
var pbkdf2 = new Rfc2898DeriveBytes(password, salt, iterations);
aes.Key = pbkdf2.GetBytes(32);
aes.IV = pbkdf2.GetBytes(16);
using (MemoryStream ms = new MemoryStream())
{
using (CryptoStream cryptoS = new CryptoStream(ms, aes.CreateEncryptor(), CryptoStreamMode.Write))
{
cryptoS.Write(plainBytes, 0, plainBytes.Length);
}
encryptedBytes = ms.ToArray();
}
return Convert.ToBase64String(encryptedBytes);
}
public static string Decrypt(string cryptoText, string password)
{
byte[] plainBytes;
byte[] cryptoBytes = Convert.FromBase64String(cryptoText);
Rijndael aes = Rijndael.Create();
Rfc2898DeriveBytes pbkdf2 = new Rfc2898DeriveBytes(password, salt, iterations);
aes.Key = pbkdf2.GetBytes(32);
aes.IV = pbkdf2.GetBytes(16);
using (MemoryStream ms = new MemoryStream())
{
using (CryptoStream cryptoS = new CryptoStream(ms, aes.CreateDecryptor(), CryptoStreamMode.Write))
{
cryptoS.Write(cryptoBytes, 0, cryptoBytes.Length);
}
plainBytes = ms.ToArray();
}
return Encoding.Unicode.GetString(plainBytes);
}
}
}
```自测用着还可以
C#中实现AES算法 备忘
最新推荐文章于 2024-08-08 20:27:33 发布