Сложно тут понять, что надо получить в финале. Во-первых, у вас мешанина в работе с файлами - почему FileMode.Append
? Это ведь означет дозапись в конец существующего файла. Во-вторых, здесь дыра в безопасности. Ключ шифрования в для AES вы записываете в открытом виде.
Вот в доказательство рабочий код. Мне вообще не потребовалось RSA чтобы расшифровать файл. Испытайте исправление, подумайте, как залатать дыру в безопасности, и если не получится - задайте другой вопрос.
static void Main(string[] args)
{
AESEncrypt("file.txt", "file.aes");
AESDecrypt("file.aes", "file_out.txt");
}
public static void AESEncrypt(string inputFile, string outFile)
{
try
{
byte[] salt = new byte[32];
using (var inputFileStream = File.OpenRead(inputFile))
using (var outFileStream = File.Create(outFile))
using (var aes = Aes.Create())
{
aes.KeySize = 256;
aes.BlockSize = 128;
aes.Mode = CipherMode.CBC;
byte[] encrypted = RSAEncrypt("password", File.ReadAllText("PublicKey.xml"));
outFileStream.Write(encrypted, 0, encrypted.Length);
using (var rfc2898DeriveBytes = new Rfc2898DeriveBytes(encrypted, salt, 1000))
{
aes.Key = rfc2898DeriveBytes.GetBytes(aes.KeySize / 8);
aes.IV = rfc2898DeriveBytes.GetBytes(aes.BlockSize / 8);
}
using (var cryptoStream = new CryptoStream(outFileStream, aes.CreateEncryptor(), CryptoStreamMode.Write))
{
inputFileStream.CopyTo(cryptoStream);
}
}
}
catch (Exception ex) { Console.WriteLine(ex.ToString()); }
}
public static void AESDecrypt(string encryptedFile, string originalFile)
{
byte[] salt = new byte[32];
using (var fsRead = File.OpenRead(encryptedFile))
using (var outFileStream = File.Create(originalFile))
using (var aes = Aes.Create())
{
aes.KeySize = 256;
aes.BlockSize = 128;
aes.Mode = CipherMode.CBC;
byte[] decrypted = new byte[256];
fsRead.Read(decrypted, 0, decrypted.Length);
using (var rfc2898DeriveBytes = new Rfc2898DeriveBytes(decrypted, salt, 1000))
{
aes.Key = rfc2898DeriveBytes.GetBytes(aes.KeySize / 8);
aes.IV = rfc2898DeriveBytes.GetBytes(aes.BlockSize / 8);
}
using (var cryptoStream = new CryptoStream(fsRead, aes.CreateDecryptor(), CryptoStreamMode.Read))
{
cryptoStream.CopyTo(outFileStream);
}
}
}
public static byte[] RSAEncrypt(string text, string publicKey)
{
byte[] bytes = Encoding.UTF8.GetBytes(text);
using RSACryptoServiceProvider rsa = new(2048);
rsa.FromXmlString(publicKey);
return rsa.Encrypt(bytes, true);
}
public static byte[] RSADecrypt(byte[] rgb, string privateKey)
{
using RSACryptoServiceProvider rsa = new(2048);
rsa.FromXmlString(privateKey);
return rsa.Decrypt(rgb, true);
}
Как сделать чтобы если пароль будет разным, то скорее всего и длина разная будет для загрузки (как это зафиксировать и читать столько байтов сколько было записано?
Записать длину массива в тот же поток перед данными
int x = 42;
byte[] header = new byte[sizeof(int)]; // 4
BinaryPrimitives.WriteInt32LittleEndian(header, x);
int y = BinaryPrimitives.ReadInt32LittleEndian(header);
Как записать массив в поток, вы знаете
Ну что, давайте разбираться. Дыра получилась из-за того что вы зачем-то придумали какой-то "пароль" вместо того чтобы шифровать ключ AES с помощью RSA.
- Когда создаете новый AES
Aes.Create()
, он заполняет свой ключ и IV рандомными байтами сам, используя безопасный рандом-генератор, подходящий для создания ключей. Так что ключ, как и IV выдумывать не надо, он будет создан автоматически.
- Далее
KeySize = 256
, BlockSize = 128
, Mode = CipherMode.CBC
это значения по умолчанию, я проверил, незачем их явно задавать.
- Рандомный AES вектор дает приятный эффект всегда разного результата при AES-шифровании, зачем упускать такой шанс? Сам по себе IV можно передавать в открытую, знание IV никак не упрощает взлом шифра. Во всяком случае, я не знаю прецендентов, и опытные разработчики соведуют передавать его вместе с данными. Конечно, если включить режим параноика, то можно его так же шифрануть с помощью RSA, никто не запрещает.
- Добавил пример как передавать массив вариативной длины, но в случае с шифрованием 32-байтового ключа, на выходе будет всегда одно и то же по длине.
Затем причесал немного код, получается как-то так:
static void Main(string[] args)
{
try
{
RSAEncryptFile("file.txt", "file.aes", File.ReadAllText("PublicKey.xml"));
RSADecryptFile("file.aes", "file_out.txt", File.ReadAllText("PrivateKey.xml"));
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
}
}
public static void RSAEncryptFile(string originalFile, string encryptedFile, string publicKey)
{
using var input = File.OpenRead(originalFile);
using var output = File.Create(encryptedFile);
using var aes = Aes.Create();
output.Write(aes.IV);
byte[] encryptedAesKey = RSAEncrypt(aes.Key, publicKey);
byte[] lengthBytes = new byte[sizeof(int)];
BinaryPrimitives.WriteInt32LittleEndian(lengthBytes, encryptedAesKey.Length);
output.Write(lengthBytes);
output.Write(encryptedAesKey);
using CryptoStream cs = new(output, aes.CreateEncryptor(), CryptoStreamMode.Write);
input.CopyTo(cs);
}
public static void RSADecryptFile(string encryptedFile, string originalFile, string privateKey)
{
using var input = File.OpenRead(encryptedFile);
using var output = File.Create(originalFile);
using var aes = Aes.Create();
byte[] iv = new byte[aes.BlockSize / 8];
input.Read(iv);
aes.IV = iv;
byte[] lengthBytes = new byte[sizeof(int)];
input.Read(lengthBytes);
int length = BinaryPrimitives.ReadInt32LittleEndian(lengthBytes);
byte[] encryptedAesKey = new byte[length];
input.Read(encryptedAesKey);
aes.Key = RSADecrypt(encryptedAesKey, privateKey);
using CryptoStream cs = new(input, aes.CreateDecryptor(), CryptoStreamMode.Read);
cs.CopyTo(output);
}
public static byte[] RSAEncrypt(byte[] data, string publicKey)
{
using RSACryptoServiceProvider rsa = new(2048);
rsa.FromXmlString(publicKey);
return rsa.Encrypt(data, true);
}
public static byte[] RSADecrypt(byte[] rgb, string privateKey)
{
using RSACryptoServiceProvider rsa = new(2048);
rsa.FromXmlString(privateKey);
return rsa.Decrypt(rgb, true);
}
Версия для .NET Framework 4.x (для некромантов)
public static void RSAEncryptFile(string originalFile, string encryptedFile, string publicKey)
{
using (var input = File.OpenRead(originalFile))
using (var output = File.Create(encryptedFile))
using (var aes = Aes.Create())
{
output.Write(aes.IV, 0, aes.IV.Length);
byte[] encryptedAesKey = RSAEncrypt(aes.Key, publicKey);
byte[] lengthBytes = BitConverter.GetBytes(encryptedAesKey.Length);
output.Write(lengthBytes, 0, lengthBytes.Length);
output.Write(encryptedAesKey, 0, encryptedAesKey.Length);
using (var cs = new CryptoStream(output, aes.CreateEncryptor(), CryptoStreamMode.Write))
{
input.CopyTo(cs);
}
}
}
public static void RSADecryptFile(string encryptedFile, string originalFile, string privateKey)
{
using (var input = File.OpenRead(encryptedFile))
using (var output = File.Create(originalFile))
using (var aes = Aes.Create())
{
byte[] iv = new byte[aes.BlockSize / 8];
input.Read(iv, 0, iv.Length);
aes.IV = iv;
byte[] lengthBytes = new byte[sizeof(int)];
input.Read(lengthBytes, 0, lengthBytes.Length);
int length = BitConverter.ToInt32(lengthBytes, 0);
byte[] encryptedAesKey = new byte[length];
input.Read(encryptedAesKey, 0, encryptedAesKey.Length);
aes.Key = RSADecrypt(encryptedAesKey, privateKey);
using (var cs = new CryptoStream(input, aes.CreateDecryptor(), CryptoStreamMode.Read))
{
cs.CopyTo(output);
}
}
}
public static byte[] RSAEncrypt(byte[] data, string publicKey)
{
using (var rsa = new RSACryptoServiceProvider(2048))
{
rsa.FromXmlString(publicKey);
return rsa.Encrypt(data, true);
}
}
public static byte[] RSADecrypt(byte[] rgb, string privateKey)
{
using (var rsa = new RSACryptoServiceProvider(2048))
{
rsa.FromXmlString(privateKey);
return rsa.Decrypt(rgb, true);
}
}