I am downloading a binary file from a server and accessing it partially while the download progresses. I'd like to encrypt the file prior to uploading, and decrypt its content as my program receives it.
The file arrives in byte chunks of random size using the code below, so I think I need a method which acts on individual bytes, or at least a fixed number of bytes, and keeping the overall file size intact.
private void DownloadFile()
{
WebClient client = new WebClient();
Stream stream = client.OpenRead(address);
byte[] readBuffer = new byte[139043]; // File size known ahead of time
int totalBytesRead = 0;
int bytesRead;
int i = 0;
while ((bytesRead = stream.Read(readBuffer, totalBytesRead, readBuffer.Length - totalBytesRead)) > 0)
{
File.WriteAllBytes("file_" + i + ".ext", readBuffer); // Save partially downloaded file
totalBytesRead += bytesRead;
i++;
}
}
Solution: I opted for the simple XOR algorithm shown in my answer below. It works on individual bytes and considering I can generate a unique key for each file, I am comfortable with the level of protection.