static void Main(string[] args)
{
string original = "Here is some data to encrypt!";
string key = GenerateRandomKey(); // 必须是16字节(128位)
string iv = GenerateRandomIV(); // 必须是16字节(128位)
//encrypted为加密后的字符串
string encrypted = EncryptString(original, key, iv);
//decrypted为解密后的字符串
string decrypted = DecryptString(encrypted, key, iv);
Console.WriteLine($"Original: {original}");
Console.WriteLine($"Encrypted: {encrypted}");
Console.WriteLine($"Decrypted: {decrypted}");
Console.ReadKey();
}
private static string GenerateRandomKey()
{
// 生成一个随机的16字节(128位)密钥
byte[] key = new byte[12];
using (RandomNumberGenerator rng = RandomNumberGenerator.Create())
{
rng.GetBytes(key);
}
return Convert.ToBase64String(key);
}
private static string GenerateRandomIV()
{
// 生成一个随机的16字节(128位)初始化向量
byte[] iv = new byte[12];
using (RandomNumberGenerator rng = RandomNumberGenerator.Create())
{
rng.GetBytes(iv);
}
return Convert.ToBase64String(iv);
}
灵感来自:文心一言