WPF实现AES加密算法
时间: 2023-11-10 22:16:11 浏览: 117
WPF可以使用.NET Framework提供的System.Security.Cryptography命名空间中的Aes类来实现AES加密算法。以下是一个简单的示例代码:
```csharp
using System;
using System.IO;
using System.Security.Cryptography;
using System.Text;
using System.Windows;
namespace WpfApp1
{
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
private void EncryptButton_Click(object sender, RoutedEventArgs e)
{
string plaintext = PlainTextBox.Text;
string password = PasswordTextBox.Text;
byte[] salt = new byte[16];
using (RNGCryptoServiceProvider rngCsp = new RNGCryptoServiceProvider())
{
rngCsp.GetBytes(salt);
}
byte[] encrypted = EncryptStringToBytes_Aes(plaintext, password, salt);
string base64Encrypted = Convert.ToBase64String(encrypted);
string base64Salt = Convert.ToBase64String(salt);
EncryptedTextBox.Text = base64Encrypted;
SaltTextBox.Text = base64Salt;
}
private void DecryptButton_Click(object sender, RoutedEventArgs e)
{
string base64Encrypted = EncryptedTextBox.Text;
string base64Salt = SaltTextBox.Text;
string password = PasswordTextBox.Text;
byte[] encrypted = Convert.FromBase64String(base64Encrypted);
byte[] salt = Convert.FromBase64String(base64Salt);
string plaintext = DecryptStringFromBytes_Aes(encrypted, password, salt);
PlainTextBox.Text = plaintext;
}
static byte[] EncryptStringToBytes_Aes(string plaintext, string password, byte[] salt)
{
byte[] key = new Rfc2898DeriveBytes(password, salt, 1000).GetBytes(32);
byte[] iv = new Rfc2898DeriveBytes(password, salt, 1000).GetBytes(16);
byte[] encrypted;
using (Aes aesAlg = Aes.Create())
{
aesAlg.Key = key;
aesAlg.IV = iv;
ICryptoTransform encryptor = aesAlg.CreateEncryptor(aesAlg.Key, aesAlg.IV);
using (MemoryStream msEncrypt = new MemoryStream())
{
using (CryptoStream csEncrypt = new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write))
{
using (StreamWriter swEncrypt = new StreamWriter(csEncrypt))
{
swEncrypt.Write(plaintext);
}
encrypted = msEncrypt.ToArray();
}
}
}
return encrypted;
}
static string DecryptStringFromBytes_Aes(byte[] encrypted, string password, byte[] salt)
{
byte[] key = new Rfc2898DeriveBytes(password, salt, 1000).GetBytes(32);
byte[] iv = new Rfc2898DeriveBytes(password, salt, 1000).GetBytes(16);
string plaintext = null;
using (Aes aesAlg = Aes.Create())
{
aesAlg.Key = key;
aesAlg.IV = iv;
ICryptoTransform decryptor = aesAlg.CreateDecryptor(aesAlg.Key, aesAlg.IV);
using (MemoryStream msDecrypt = new MemoryStream(encrypted))
{
using (CryptoStream csDecrypt = new CryptoStream(msDecrypt, decryptor, CryptoStreamMode.Read))
{
using (StreamReader srDecrypt = new StreamReader(csDecrypt))
{
plaintext = srDecrypt.ReadToEnd();
}
}
}
}
return plaintext;
}
}
}
```
此代码使用用户提供的密码和随机生成的盐值对输入字符串进行AES加密,并将结果显示在界面上。用户可以将加密结果和盐值保存下来,并使用相同的密码和盐值对其进行解密。
阅读全文