using System;
using System.Security.Cryptography;
using System.Text;
public class AesHelper
{
public static string Encrypt(string text, string key, string iv = "")
{
byte[] textBytes = Encoding.UTF8.GetBytes(text);
using (Aes aes = Aes.Create())
{
aes.Key = SHA256.Create().ComputeHash(Encoding.UTF8.GetBytes(key));
aes.IV = MD5.Create().ComputeHash(Encoding.UTF8.GetBytes(iv));
ICryptoTransform encryptor = aes.CreateEncryptor();
byte[] encryptedBytes = encryptor.TransformFinalBlock(textBytes, 0, textBytes.Length);
return Convert.ToBase64String(encryptedBytes);
}
}
public static string Decrypt(string text, string key, string iv = "")
{
byte[] textBytes = Convert.FromBase64String(text);
using (Aes aes = Aes.Create())
{
aes.Key = SHA256.Create().ComputeHash(Encoding.UTF8.GetBytes(key));
aes.IV = MD5.Create().ComputeHash(Encoding.UTF8.GetBytes(iv));
ICryptoTransform decryptor = aes.CreateDecryptor();
byte[] decryptedBytes = decryptor.TransformFinalBlock(textBytes, 0, textBytes.Length);
return Encoding.UTF8.GetString(decryptedBytes);
}
}
}
Console.Write("请输入要加密的文本:");
string text = Console.ReadLine();
Console.Write("请输入密钥(Key):");
string key = Console.ReadLine();
Console.Write("请输入初始化向量(IV):");
string iv = Console.ReadLine();
string encrypted = AesHelper.Encrypt(text, key, iv);
Console.WriteLine("【加密结果】{0}", encrypted);
string decrypted = AesHelper.Decrypt(encrypted, key, iv);
Console.WriteLine("【解密结果】{0}", decrypted);