I use AES encryption. It’s ok when I encrypt and then decrypt whole file. I want to add multiple files to one encrypted. That’s where the problem is. Encryption is fine, but decryption causes CryptographicException – bad data length. Is it even possible to decrypt part of file or is it encrypted as whole ? I used one cryptostream and passed there all files I want to encrypt to single file. I am trying to do opposite:
AesManaged aes = AES.InitAes(key, salt);
ICryptoTransform transform = aes.CreateDecryptor(aes.Key, aes.IV);
int defChunkSize = 1024 * 1024 * 50;
using (FileStream source = new FileStream(header.data.filename, FileMode.Open))
{
foreach (CryptHeader.fileStruct file in header.data.files)
{
preparePath(file.filename);
using (FileStream target = new FileStream(file.filename, FileMode.Create))
{
using (CryptoStream cryptoStream = new CryptoStream(target, transform, CryptoStreamMode.Write))
{
long padding = source.Length - header.data.files.Sum(x => x.length);//Just test
int chunkSize = (defChunkSize > (int)file.length) ? (int)file.length : defChunkSize;
byte[] chunkData = new byte[chunkSize];
int bytesRead = 0;
int totalRead = 0;
while (totalRead < file.length)
{
bytesRead = source.Read(chunkData, 0, chunkSize);
if (bytesRead <= 0) break;
totalRead += bytesRead;
cryptoStream.Write(chunkData, 0, bytesRead);
}
chunkData = null;
}
}
}
}
I’ve done the same few years ago without any problem. The logic I used is the following:
Encryption
define number of files
define array for keeping encrypted sizes
open output stream
seek (forced) to (number of files * 4) + 4 (assuming lengths are integers)
loop for encryption (encrypt- write encrypted data -assigned encrypted size)
seek to 0 (begin)
write number of files
write encrypted size array
close output stream
Decryption
open input stream
read number of files
define-read-fill array with encrypted sizes
loop for decryption (read using known sizes)
close output stream
I hope that this helps.