Aes加密/解密示例项目

时间:2023-03-09 15:12:56
Aes加密/解密示例项目

#AesEncrypt:Aes加密/解密示例项目 <br>
  附件中的“AesEncrypt.zip”是本项目的exe文件,可直接下载下来运行和查看。
  *高级加密标准(英语:Advanced Encryption Standard,缩写:AES),在密码学中又称Rijndael加密法,是美国联邦*采用的一种区块加密标准。这个标准用来替代原先的DES,已经被多方分析且广为全世界所使用。经过五年的甄选流程,高级加密标准由美国国家标准与技术研究院(NIST)于2001年11月26日发布于FIPS PUB 197,并在2002年5月26日成为有效的标准。2006年,高级加密标准已然成为对称密钥加密中最流行的算法之一。*<br>
  好的百科已普及,现在来看看这Aes怎么使用,由于需要把加密后的byte[]输出成字符串,但是普通字符串无法兼容,所以这里使用的base64字符串。详见代码AesEncrypt\AesEncrypt.cs。<br>
  为了直观的看到Aes的加解密过程,现在给出几个示例,如下图<br>
  1.在“未加密”的文本框中输入一个普通的字符串,点击“加密”按钮,将在”已加密“的文本框中得到一个Aes加密后的base64字符串。**这个“已加密”的base64字符串就可以放到系统中使用了,例如可以填到数据库链接字符串,也可以存储得到数据中。**<br>
  2.第一步完成后,“已加密”文本框中已经被填写了Aes加密后的base64字符串,为了看到效果,可以把“未加密”文本框中的普通文本删掉,然后点击“解密”按钮,就可以在“未加密”文本框中看到之前的普通文本。<br>
  3.经过以上两步操作,我想这个窗体已经完成了示例的作用,Aes加密需要两个byte[],一个是IV,它是对称算法的初始化向量,一个是Key,它是对称算法的密钥。IV是一个Length=16的byte[],Key是一个Length=32的byte[],**因此可以在AesEncrypt\AesEncrypt.cs类中设置自己的固定密钥用以在程序中加密/解密,如以下代码中所示,可以填写任意的数字,来当做密钥。**<br>
```C#
/// <summary>
/// 对称算法的密钥
/// </summary>
private readonly static byte[] aesKey = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32 };
/// <summary>
/// 对称算法的初始化向量
/// </summary>
private readonly static byte[] aesIV = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16 };
```

Aes加密/解密示例项目

  以上步骤是在程序中的基本使用方式,Aes还可以有更多的用途,以下来个抛砖引玉。<br>
  1.在“玩玩解密”窗体中点击“发送”按钮之后,将把“未加密”中的文本使用Aes加密后转换成base64字符串填写到“已加密”文本框中,同时将利用以下代码将Aes类可随机生成的IV和Key(注意IV和Key都是byte[]),转换为base64后分别填写到“向量(IV)”和“密钥(Key)”中。<br>
```C#
private void button1_Click(object sender, EventArgs e)
{
    using (Aes myAes = Aes.Create())
    {
        AesEncryptExtension aes = new AesEncryptExtension();
        textBox2.Text = aes.Encrypt(textBox1.Text, myAes.Key, myAes.IV);
        textBox3.Text = Convert.ToBase64String(myAes.IV);
        textBox4.Text = Convert.ToBase64String(myAes.Key);
    }
    Form3 form = new Form3();
    form.Show();
}

```

Aes加密/解密示例项目

  2.第一步完成后,同时会弹出“接收密文”窗体,如下图。将“玩玩解密”窗体中的“已加密”、“向量(IV)”和“密钥(key)”填写到“接收密文”窗体对应文本框中,将获取到未加密的普通文本。<br>
Aes加密/解密示例项目

  3.以上所示,是手动填写密文、IV和key来获取内容。当然你也可以自动传过去,只要两个系统的iv和key相同就可以实现解密,前提是两个系统中的动态密钥规律要相同,说到这里我想聪明的你应该已经知道Aes加密怎么玩了,好好想想,可以有多种应用。<br>
  举个例子,图例解释,IV和key合称为钥匙,IV和Key生成算法称为钥匙机,每一把被生产出来的钥匙都刻着钥匙编号,Aes本身称为保险柜,被加密内容则会被放进“保险柜”。两方同时使用钥匙机生产钥匙,每一把钥匙都刻着钥匙编号,运输的时候只运输保险柜和钥匙编号,接收到保险柜的一方,用钥匙编号从钥匙机中拿钥匙打开保险柜,取得加密内容。以上例可称为一个较为简单的Aes应用方式。

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks; namespace AesEncrypt
{
/// <summary>
/// Aes加密算法适用于固定的加解密
/// </summary>
public static class AesEncrypt
{
/// <summary>
/// 对称算法的密钥
/// </summary>
private readonly static byte[] aesKey = { , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , };
/// <summary>
/// 对称算法的初始化向量
/// </summary>
private readonly static byte[] aesIV = { , , , , , , , , , , , , , , , }; /// <summary>
/// 加密
/// </summary>
/// <param name="Text">被加密的字符串</param>
/// <returns>Base64</returns>
public static string Encrypt(string Text)
{
byte[] encrypted;
encrypted = EncryptStringToBytes_Aes(Text, aesKey, aesIV);
return Convert.ToBase64String(encrypted);
} private static byte[] EncryptStringToBytes_Aes(string plainText, byte[] Key, byte[] IV)
{
// Check arguments.
if (plainText == null || plainText.Length <= )
{
throw new ArgumentNullException("plainText");
}
if (Key == null || Key.Length <= )
{
throw new ArgumentNullException("Key");
}
if (IV == null || IV.Length <= )
{
throw new ArgumentNullException("IV");
}
byte[] encrypted;
// Create an Aes object
// with the specified key and IV.
using (Aes aesAlg = Aes.Create())
{
aesAlg.Key = Key;
aesAlg.IV = IV; // Create a decrytor to perform the stream transform.
ICryptoTransform encryptor = aesAlg.CreateEncryptor(aesAlg.Key, aesAlg.IV); // Create the streams used for encryption.
using (MemoryStream msEncrypt = new MemoryStream())
{
using (CryptoStream csEncrypt = new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write))
{
using (StreamWriter swEncrypt = new StreamWriter(csEncrypt))
{ //Write all data to the stream.
swEncrypt.Write(plainText);
}
encrypted = msEncrypt.ToArray();
}
}
}
// Return the encrypted bytes from the memory stream.
return encrypted;
} /// <summary>
/// 解密
/// </summary>
/// <param name="text">被Aes加密后的Base64</param>
/// <returns>字符串</returns>
public static string Decrypt(string text)
{
string roundtrip; byte[] myByte = Convert.FromBase64String(text);
roundtrip = DecryptStringFromBytes_Aes(myByte, aesKey, aesIV); return roundtrip;
}
private static string DecryptStringFromBytes_Aes(byte[] cipherText, byte[] Key, byte[] IV)
{
// Check arguments.
if (cipherText == null || cipherText.Length <= )
{
throw new ArgumentNullException("cipherText");
}
if (Key == null || Key.Length <= )
{
throw new ArgumentNullException("Key");
}
if (IV == null || IV.Length <= )
{
throw new ArgumentNullException("IV");
}
// Declare the string used to hold
// the decrypted text.
string plaintext; // Create an Aes object
// with the specified key and IV.
using (Aes aesAlg = Aes.Create())
{
aesAlg.Key = Key;
aesAlg.IV = IV; // Create a decrytor to perform the stream transform.
ICryptoTransform decryptor = aesAlg.CreateDecryptor(aesAlg.Key, aesAlg.IV); // Create the streams used for decryption.
using (MemoryStream msDecrypt = new MemoryStream(cipherText))
{
using (CryptoStream csDecrypt = new CryptoStream(msDecrypt, decryptor, CryptoStreamMode.Read))
{
using (StreamReader srDecrypt = new StreamReader(csDecrypt))
{ // Read the decrypted bytes from the decrypting stream
// and place them in a string.
plaintext = srDecrypt.ReadToEnd();
}
}
}
}
return plaintext;
}
}
}
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks; namespace AesEncrypt
{
/// <summary>
/// Aes扩展方法
/// </summary>
public class AesEncryptExtension
{ /// <summary>
/// 加密
/// </summary>
/// <param name="Text">被加密的字符串</param>
/// <param name="aesKey">对称算法的密钥</param>
/// <param name="aesIV">设置对称算法的初始化向量</param>
/// <returns>Base64</returns>
public string Encrypt(string Text, byte[] aesKey, byte[] aesIV)
{
byte[] encrypted;
encrypted = EncryptStringToBytes_Aes(Text, aesKey, aesIV);
return Convert.ToBase64String(encrypted);
} private byte[] EncryptStringToBytes_Aes(string plainText, byte[] Key, byte[] IV)
{
// Check arguments.
if (plainText == null || plainText.Length <= )
{
throw new ArgumentNullException("plainText");
}
if (Key == null || Key.Length <= )
{
throw new ArgumentNullException("Key");
}
if (IV == null || IV.Length <= )
{
throw new ArgumentNullException("IV");
}
byte[] encrypted;
// Create an Aes object
// with the specified key and IV.
using (Aes aesAlg = Aes.Create())
{
aesAlg.Key = Key;
aesAlg.IV = IV; // Create a decrytor to perform the stream transform.
ICryptoTransform encryptor = aesAlg.CreateEncryptor(aesAlg.Key, aesAlg.IV); // Create the streams used for encryption.
using (MemoryStream msEncrypt = new MemoryStream())
{
using (CryptoStream csEncrypt = new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write))
{
using (StreamWriter swEncrypt = new StreamWriter(csEncrypt))
{ //Write all data to the stream.
swEncrypt.Write(plainText);
}
encrypted = msEncrypt.ToArray();
}
}
}
// Return the encrypted bytes from the memory stream.
return encrypted;
} /// <summary>
/// 解密
/// </summary>
/// <param name="text">被Aes加密后的Base64</param>
/// <param name="aesKey">对称算法的密钥</param>
/// <param name="aesIV">设置对称算法的初始化向量</param>
/// <returns>字符串</returns>
public string Decrypt(string text, byte[] aesKey, byte[] aesIV)
{
string roundtrip; byte[] myByte = Convert.FromBase64String(text);
roundtrip = DecryptStringFromBytes_Aes(myByte, aesKey, aesIV); return roundtrip;
}
private string DecryptStringFromBytes_Aes(byte[] cipherText, byte[] Key, byte[] IV)
{
// Check arguments.
if (cipherText == null || cipherText.Length <= )
{
throw new ArgumentNullException("cipherText");
}
if (Key == null || Key.Length <= )
{
throw new ArgumentNullException("Key");
}
if (IV == null || IV.Length <= )
{
throw new ArgumentNullException("IV");
}
// Declare the string used to hold
// the decrypted text.
string plaintext; // Create an Aes object
// with the specified key and IV.
using (Aes aesAlg = Aes.Create())
{
aesAlg.Key = Key;
aesAlg.IV = IV; // Create a decrytor to perform the stream transform.
ICryptoTransform decryptor = aesAlg.CreateDecryptor(aesAlg.Key, aesAlg.IV); // Create the streams used for decryption.
using (MemoryStream msDecrypt = new MemoryStream(cipherText))
{
using (CryptoStream csDecrypt = new CryptoStream(msDecrypt, decryptor, CryptoStreamMode.Read))
{
using (StreamReader srDecrypt = new StreamReader(csDecrypt))
{ // Read the decrypted bytes from the decrypting stream
// and place them in a string.
plaintext = srDecrypt.ReadToEnd();
}
}
}
}
return plaintext;
}
}
}
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms; namespace AesEncrypt
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
} private void button1_Click(object sender, EventArgs e)
{ textBox2.Text = AesEncrypt.Encrypt(textBox1.Text);
} private void button2_Click(object sender, EventArgs e)
{ textBox1.Text = AesEncrypt.Decrypt(textBox2.Text);
} private void 玩玩解密ToolStripMenuItem_Click(object sender, EventArgs e)
{
Form2 form = new Form2();
form.Show();
}
}
}
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms; namespace AesEncrypt
{
public partial class Form2 : Form
{
public Form2()
{
InitializeComponent();
} private void button1_Click(object sender, EventArgs e)
{
using (Aes myAes = Aes.Create())
{
AesEncryptExtension aes = new AesEncryptExtension();
textBox2.Text = aes.Encrypt(textBox1.Text, myAes.Key, myAes.IV);
textBox3.Text = Convert.ToBase64String(myAes.IV);
textBox4.Text = Convert.ToBase64String(myAes.Key);
}
Form3 form = new Form3();
form.Show();
}
}
}
using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms; namespace AesEncrypt
{
public partial class Form3 : Form
{
public Form3()
{
InitializeComponent();
} private void button1_Click(object sender, EventArgs e)
{
AesEncryptExtension aes = new AesEncryptExtension();
byte[] aesIV = Convert.FromBase64String(textBox3.Text);
byte[] aesKey = Convert.FromBase64String(textBox4.Text); textBox1.Text = aes.Decrypt(textBox2.Text, aesKey, aesIV);
}
}
}

Advanced Encryption Standard,缩写:AES),在密码学中又称Rijndael加密法