using System.Security.Cryptography;
using System.Text;
namespace AESStu01;
public class AesHelper
{
// AES加密密钥和向量(需要保密)
private static readonly string Key = "";//16长度字符串+数字混合
private static readonly string IV = "";//16长度字符串+数字混合
// 加密字节数组
public static byte[] Encrypt(byte[] plainBytes)
{
using (Aes aesAlg = Aes.Create())
{
aesAlg.Key = Encoding.UTF8.GetBytes(Key);
aesAlg.IV = Encoding.UTF8.GetBytes(IV);
ICryptoTransform encryptor = aesAlg.CreateEncryptor(aesAlg.Key, aesAlg.IV);
using (MemoryStream msEncrypt = new MemoryStream())
{
using (CryptoStream csEncrypt = new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write))
{
csEncrypt.Write(plainBytes, 0, plainBytes.Length);
csEncrypt.Close();
}
return msEncrypt.ToArray();
}
}
}
// 解密字节数组
public static byte[] Decrypt(byte[] cipherBytes)
{
using (Aes aesAlg = Aes.Create())
{
aesAlg.Key = Encoding.UTF8.GetBytes(Key);
aesAlg.IV = Encoding.UTF8.GetBytes(IV);
ICryptoTransform decryptor = aesAlg.CreateDecryptor(aesAlg.Key, aesAlg.IV);
using (MemoryStream msDecrypt = new MemoryStream())
{
using (CryptoStream csDecrypt = new CryptoStream(msDecrypt, decryptor, CryptoStreamMode.Write))
{
csDecrypt.Write(cipherBytes, 0, cipherBytes.Length);
csDecrypt.Close();
}
return msDecrypt.ToArray();
}
}
}
}
测试
using AESStu01;
var orginData = new byte[]
{
1, 2, 3, 4, 5
};
Console.WriteLine("AES加密");
var enData = AesHelper.Encrypt(orginData);
Console.WriteLine("加密后的的数据");
Console.WriteLine(string.Join(",",enData));
var deData = AesHelper.Decrypt(enData);
Console.WriteLine("解密后的的数据");
Console.WriteLine(string.Join(",",deData));