- 介绍
- 效果图
- 代码
1.介绍
在使用之前我们先了解一下什么是AES标准。这个标准用来替代原先的DES(Data Encryption Standard),已经被多方分析且广为全世界所使用。经过五年的甄选流程,高级加密标准由美国国家标准与技术研究院 (NIST)于2001年11月26日发布于FIPS PUB 197,并在2002年5月26日成为有效的标准。2006年,高级加密标准已然成为对称密钥加密中最流行的算法之一 。
- 效果图
我这里使用的是WPF实现的,首先我们创建一个WPF项目,创建过程就不演示了。
先进行排版,左边为输入右边为输出,使用button的点击事件(Click Event)。
输入左边文本点击加密,加密后的文本则显示在右侧,右侧同理。
点击加密按钮,为显示明显这里再加个Message Box.Show();。
点击解密同理。
3. 代码
XAML代码
// XAML 代码
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition/>
<ColumnDefinition/>
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>
<RowDefinition Height="300"/>
<RowDefinition/>
</Grid.RowDefinitions>
<TextBox x:Name="Textbox1" Grid.Row="0" Grid.Column="0" Text="请输入加密文本" TextWrapping ="Wrap"/>
<TextBox x:Name="Textbox2" Grid.Row="0" Grid.Column="1" Text="请输入解密文本" TextWrapping="Wrap" />
<Button x:Name="btn1" Click="btn1_Click" Grid.Row="1" Width="200" Height="100" Content="加密"/>
<Button x:Name="btn2" Click="btn2_Click" Grid.Row="1" Grid.Column="1" Width="200" Height="100" Content="解密"/>
</Grid>
AES类
// 加密
public static string Encrypt(string plainText, string key)
{
byte[] keyBytes = Encoding.UTF8.GetBytes(key);
byte[] iv = new byte[16]; // 使用默认的初始化向量
using (Aes aesAlg = Aes.Create())
{
aesAlg.Key = keyBytes;
aesAlg.IV = iv;
ICryptoTransform encryptor = aesAlg.CreateEncryptor(aesAlg.Key, aesAlg.IV);
using (var msEncrypt = new System.IO.MemoryStream())
{
using (var csEncrypt = new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write))
{
using (var swEncrypt = new System.IO.StreamWriter(csEncrypt))
{
swEncrypt.Write(plainText);
}
byte[] encryptedBytes = msEncrypt.ToArray();
return Convert.ToBase64String(encryptedBytes);
}
}
}
}
//解密
public static string Decrypt(string cipherText, string key)
{
byte[] keyBytes = Encoding.UTF8.GetBytes(key);
byte[] iv = new byte[16]; // 使用默认的初始化向量
byte[] cipherBytes = Convert.FromBase64String(cipherText);
using (Aes aesAlg = Aes.Create())
{
aesAlg.Key = keyBytes;
aesAlg.IV = iv;
ICryptoTransform decryptor = aesAlg.CreateDecryptor(aesAlg.Key, aesAlg.IV);
using (var msDecrypt = new System.IO.MemoryStream(cipherBytes))
{
using (var csDecrypt = new CryptoStream(msDecrypt, decryptor, CryptoStreamMode.Read))
{
using (var srDecrypt = new System.IO.StreamReader(csDecrypt))
{
return srDecrypt.ReadToEnd();
}
}
}
}
}
XAML.CS代码
//定义密钥 用于加解密唯一标识 也可选择随机生成
public string Key { get; set; } = "MlN3BodcCF2h8llStWOKddrPYVEAFrOW";
// 加密
private void btn1_Click(object sender, RoutedEventArgs e)
{
string text = Textbox1.Text;
Textbox2.Text = AES.Encrypt(text, Key);
MessageBox.Show($"加密内容是: {AES.Encrypt(text, Key)}");
}
//解密
private void btn2_Click(object sender, RoutedEventArgs e)
{
Textbox1.Text = AES.Decrypt(Textbox2.Text, Key);
MessageBox.Show($"解密内容是: {AES.Decrypt(Textbox2.Text, Key)}");
}
输入的加密内容越多,得到的加密结果就越多。