using System;
using System.Collections.Generic;
using System.Security.Cryptography;
using System.Text;
namespace AESTool
{
public class AES
{
private const string AES_IV = "0cAoMbN7xEM0uZVf";
private const string AES_Key = "phMfB4YDfcgBRIXL";
///
/// 加密
///
///
///
///
///
public static string AESEncrypt(string text, string key = AES_Key, string iv = AES_IV)
{
RijndaelManaged rijndaelCipher = new RijndaelManaged();
rijndaelCipher.Mode = CipherMode.CBC;
rijndaelCipher.Padding = PaddingMode.PKCS7;
rijndaelCipher.KeySize = 128;
rijndaelCipher.BlockSize = 128;
byte[] pwdBytes = Encoding.UTF8.GetBytes(key);
byte[] keyBytes = new byte[32];
int len = pwdBytes.Length;
if (len > keyBytes.Length) len = keyBytes.Length;
Array.Copy(pwdBytes, keyBytes, len);
rijndaelCipher.Key = keyBytes;
byte[] ivBytes = Encoding.UTF8.GetBytes(iv);
rijndaelCipher.IV = ivBytes;
ICryptoTransform transform = rijndaelCipher.CreateEncryptor();
byte[] plainText = Encoding.UTF8.GetBytes(text);
byte[] cipherBytes = transform.TransformFinalBlock(plainText, 0, plainText.Length);
return Convert.ToBase64String(cipherBytes);
}
///
/// 解密
///
///
///
///
///
public static string AESDecrypt(string text, string key = AES_Key, string iv = AES_IV)
{
RijndaelManaged rijndaelCipher = new RijndaelManaged();
rijndaelCipher.Mode = CipherMode.CBC;
rijndaelCipher.Padding = PaddingMode.PKCS7;
rijndaelCipher.KeySize = 128;
rijndaelCipher.BlockSize = 128;
byte[] encryptedData = Convert.FromBase64String(text);
byte[] pwdBytes = Encoding.UTF8.GetBytes(key);
byte[] keyBytes = new byte[32];
int len = pwdBytes.Length;
if (len > keyBytes.Length) len = keyBytes.Length;
Array.Copy(pwdBytes, keyBytes, len);
rijndaelCipher.Key = keyBytes;
byte[] ivBytes = Encoding.UTF8.GetBytes(iv);
rijndaelCipher.IV = ivBytes;
ICryptoTransform transform = rijndaelCipher.CreateDecryptor();
byte[] plainText = transform.TransformFinalBlock(encryptedData, 0, encryptedData.Length);
return Encoding.UTF8.GetString(plainText);
}
}
}