所以这是我的烂摊子。它返回随机的 Unicode 字符。我让它对这两种方法使用相同的密钥,以及相同的 IV,并且我对它们都使用相同的编码。是什么导致随机响应?
using System;
using System.IO;
using System.Security.Cryptography;
using System.Text;
namespace FileFish
{
class Program
{
public static void Main()
{
AesCryptoServiceProvider aes = new AesCryptoServiceProvider();
aes.GenerateIV();
Console.WriteLine(Decrypt(Encoding.UTF8.GetBytes("APPLEAPPLEAPPLEAPPLEAPPLEAPPLEAP"), aes.IV, Encrypt(Encoding.UTF8.GetBytes("APPLEAPPLEAPPLEAPPLEAPPLEAPPLEAP"), aes.IV, "cheese")));
Console.ReadKey(true);
}
private static byte[] Encrypt(byte[] key, byte[] iv, string plaintext)
{
AesCryptoServiceProvider aes = new AesCryptoServiceProvider();
aes.Key = key;
aes.IV = iv;
ICryptoTransform encryptor = aes.CreateEncryptor();
MemoryStream ms = new MemoryStream();
StreamWriter sw = new StreamWriter(new CryptoStream(ms, encryptor, CryptoStreamMode.Write));
sw.Write(plaintext);
return ms.ToArray();
}
private static string Decrypt(byte[] key, byte[] iv, byte[] ciphertext)
{
AesCryptoServiceProvider aes = new AesCryptoServiceProvider();
aes.Key = key;
aes.IV = iv;
ICryptoTransform decryptor = aes.CreateEncryptor();
MemoryStream ms = new MemoryStream(ciphertext);
StreamReader sr = new StreamReader(new CryptoStream(ms, decryptor, CryptoStreamMode.Read));
return sr.ReadToEnd();
}
}
}