WPF AES 算法对用户输入的密码进行加密和解密
时间: 2024-09-18 10:08:59 浏览: 50
WPF (Windows Presentation Foundation) 是一种用于创建桌面应用程序的框架,而AES (Advanced Encryption Standard) 是一种高级的对称加密算法,通常用于保护数据的安全存储和传输。在WPF中,你可以利用.NET Framework提供的`System.Security.Cryptography.Aes`类来实现密码的加密和解密。
以下是基本步骤:
1. 导入所需命名空间:
```csharp
using System.IO;
using System.Security.Cryptography;
```
2. 创建AES密钥和初始化向量(IV):
```csharp
byte[] key = Encoding.UTF8.GetBytes("your_secret_key_here");
byte[] iv = new byte[Aes.BlockSize];
// 初始化向量随机生成或者从配置文件读取
RandomNumberGenerator rng = RandomNumberGenerator.Create();
rng.GetBytes(iv);
```
3. 加密过程:
```csharp
string passwordToEncrypt = "password_to_encrypt";
Aes aes = Aes.Create();
aes.Key = key;
aes.IV = iv;
MemoryStream ciphertextStream = new MemoryStream();
CryptoStream cryptoStream = new CryptoStream(ciphertextStream, aes.CreateEncryptor(), CryptoStreamMode.Write);
byte[] passwordBytes = Encoding.UTF8.GetBytes(passwordToEncrypt);
cryptoStream.Write(passwordBytes, 0, passwordBytes.Length);
cryptoStream.FlushFinalBlock();
byte[] encryptedPassword = ciphertextStream.ToArray();
```
4. 解密过程:
```csharp
Aes aes = Aes.Create();
aes.Key = key;
aes.IV = iv;
MemoryStream decryptedStream = new MemoryStream(encryptedPassword);
CryptoStream cryptoStream = new CryptoStream(decryptedStream, aes.CreateDecryptor(), CryptoStreamMode.Read);
StringBuilder decryptedTextBuilder = new StringBuilder();
int bytesRead;
while ((bytesRead = cryptoStream.Read(buffer, 0, buffer.Length)) > 0)
{
decryptedTextBuilder.Append(Encoding.UTF8.GetString(buffer, 0, bytesRead));
}
string decryptedPassword = decryptedTextBuilder.ToString();
```
注意:实际应用中,你应该将敏感信息(如钥匙和IV)妥善保管,而不是硬编码在代码中,最好使用安全的方式存储它们。
阅读全文