用C#窗体实现AES加密和解密
时间: 2023-07-12 14:15:11 浏览: 177
首先,需要引入System.Security.Cryptography命名空间。
以下是C#窗体实现AES加密和解密的示例代码:
```
using System;
using System.IO;
using System.Security.Cryptography;
using System.Text;
using System.Windows.Forms;
namespace AesDemo
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void btnEncrypt_Click(object sender, EventArgs e)
{
try
{
// 获取密钥和向量
string key = txtKey.Text.Trim();
string iv = txtIV.Text.Trim();
byte[] keyBytes = Encoding.UTF8.GetBytes(key);
byte[] ivBytes = Encoding.UTF8.GetBytes(iv);
// 获取明文
string plaintext = txtPlaintext.Text.Trim();
byte[] plaintextBytes = Encoding.UTF8.GetBytes(plaintext);
// 创建AES加密器
using (Aes aes = Aes.Create())
{
aes.Key = keyBytes;
aes.IV = ivBytes;
// 创建加密流
using (MemoryStream msEncrypt = new MemoryStream())
{
using (CryptoStream csEncrypt = new CryptoStream(msEncrypt, aes.CreateEncryptor(), CryptoStreamMode.Write))
{
// 将明文写入加密流
csEncrypt.Write(plaintextBytes, 0, plaintextBytes.Length);
csEncrypt.FlushFinalBlock();
// 获取加密结果
byte[] ciphertextBytes = msEncrypt.ToArray();
string ciphertext = Convert.ToBase64String(ciphertextBytes);
// 显示加密结果
txtCiphertext.Text = ciphertext;
}
}
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
private void btnDecrypt_Click(object sender, EventArgs e)
{
try
{
// 获取密钥和向量
string key = txtKey.Text.Trim();
string iv = txtIV.Text.Trim();
byte[] keyBytes = Encoding.UTF8.GetBytes(key);
byte[] ivBytes = Encoding.UTF8.GetBytes(iv);
// 获取密文
string ciphertext = txtCiphertext.Text.Trim();
byte[] ciphertextBytes = Convert.FromBase64String(ciphertext);
// 创建AES解密器
using (Aes aes = Aes.Create())
{
aes.Key = keyBytes;
aes.IV = ivBytes;
// 创建解密流
using (MemoryStream msDecrypt = new MemoryStream(ciphertextBytes))
{
using (CryptoStream csDecrypt = new CryptoStream(msDecrypt, aes.CreateDecryptor(), CryptoStreamMode.Read))
{
// 读取解密结果
byte[] plaintextBytes = new byte[ciphertextBytes.Length];
int bytesRead = csDecrypt.Read(plaintextBytes, 0, plaintextBytes.Length);
// 显示解密结果
string plaintext = Encoding.UTF8.GetString(plaintextBytes, 0, bytesRead);
txtPlaintext.Text = plaintext;
}
}
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
}
}
```
在窗体上添加三个TextBox控件和两个Button控件,分别命名为txtKey、txtIV、txtPlaintext、txtCiphertext、btnEncrypt和btnDecrypt。用户输入密钥、向量和明文,点击“加密”按钮进行加密,点击“解密”按钮进行解密。加密和解密过程中,采用AES算法进行加密和解密,使用Base64编码将密文转换为字符串。
阅读全文