public class AES_EnorDecrypt
{
private const int KEY_SIZE = 256;
private const int BLOCK_SIZE = 128;
private const string KEY_CHARS = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
private const string IV_CHARS = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
public static string Encrypt(string plainText)
{
byte[] keyBytes = Encoding.UTF8.GetBytes(DatabaseConfiguration.key);
byte[] ivBytes = Encoding.UTF8.GetBytes(DatabaseConfiguration.iv);
using (Aes aes = Aes.Create())
{
aes.KeySize = KEY_SIZE;
aes.BlockSize = BLOCK_SIZE;
aes.Key = keyBytes;
aes.IV = ivBytes;
aes.Mode = CipherMode.CBC;
ICryptoTransform encryptor = aes.CreateEncryptor(aes.Key, aes.IV);
byte[] plainBytes = Encoding.UTF8.GetBytes(plainText);
using (MemoryStream ms = new MemoryStream())
{
using (CryptoStream cs = new CryptoStream(ms, encryptor, CryptoStreamMode.Write))
{
cs.Write(plainBytes, 0, plainBytes.Length);
}
byte[] encryptedBytes = ms.ToArray();
return Convert.ToBase64String(encryptedBytes);
}
}
}
/// <summary>
/// 解密
/// </summary>
/// <param name="cipherText"></param>
/// <returns></returns>
public static string Decrypt(string cipherText)
{
byte[] keyBytes = Encoding.UTF8.GetBytes(DatabaseConfiguration.key);
byte[] ivBytes = Encoding.UTF8.GetBytes(DatabaseConfiguration.iv);
using (Aes aes = Aes.Create())
{
aes.KeySize = KEY_SIZE;
aes.BlockSize = BLOCK_SIZE;
aes.Key = keyBytes;
aes.IV = ivBytes;
aes.Mode = CipherMode.CBC;
ICryptoTransform decryptor = aes.CreateDecryptor(aes.Key, aes.IV);
byte[] cipherBytes = Convert.FromBase64String(cipherText);
using (MemoryStream ms = new MemoryStream())
{
using (CryptoStream cs = new CryptoStream(ms, decryptor, CryptoStreamMode.Write))
{
cs.Write(cipherBytes, 0, cipherBytes.Length);
}
byte[] decryptedBytes = ms.ToArray();
return Encoding.UTF8.GetString(decryptedBytes);
}
}
}
public static string GenerateKey()
{
Random random = new Random();
StringBuilder sb = new StringBuilder();
for (int i = 0; i < KEY_SIZE / 8; i++)
{
int index = random.Next(KEY_CHARS.Length);
sb.Append(KEY_CHARS[index]);
}
return sb.ToString();
}
public static string GenerateIV()
{
Random random = new Random();
StringBuilder sb = new StringBuilder();
for (int i = 0; i < BLOCK_SIZE / 8; i++)
{
int index = random.Next(IV_CHARS.Length);
sb.Append(IV_CHARS[index]);
}
return sb.ToString();
}
}