public class AesEncrypt
{
// 密码
private static string Password = "1234567890123456"; //AES的密钥长度可以为16、24或者32字节
/// <summary>
/// 加密
/// </summary>
public static byte[] EncryptAes(string text)
{
byte[] keyBytes = Encoding.UTF8.GetBytes(Password);
using(Aes aes = Aes.Create())
{
aes.Key = keyBytes;
aes.Mode = CipherMode.ECB;
aes.Padding = PaddingMode.PKCS7;
byte[] textBytes = Encoding.UTF8.GetBytes(text);
using(ICryptoTransform encryptor = aes.CreateEncryptor())
{
return encryptor.TransformFinalBlock(textBytes,0,textBytes.Length);
}
}
}
/// <summary>
/// 解密
/// </summary>
public static string DecryptAes(byte[] encrypted)
{
byte[] keyBytes = Encoding.UTF8.GetBytes(Password);
using(Aes aes = Aes.Create())
{
aes.Key = keyBytes;
aes.Mode = CipherMode.ECB;
aes.Padding = PaddingMode.PKCS7;
using(ICryptoTransform decryptor = aes.CreateDecryptor())
{
byte[] decryptedBytes = decryptor.TransformFinalBlock(encrypted, 0, encrypted.Length);
return Encoding.UTF8.GetString(decryptedBytes);
}
}
}
}