I am new to encryption and am encrypting files using the following method:
private static void encryptFile(string filePath, byte[] password, byte[] salt)
{
Rfc2898DeriveBytes rdb = new Rfc2898DeriveBytes(password, salt, 1000);
AesManaged algorithm = new AesManaged();
byte[] rgbKey = rdb.GetBytes(algorithm.KeySize / 8);
byte[] rgbIV = rdb.GetBytes(algorithm.BlockSize / 8);
GCHandle keyHandle = GCHandle.Alloc(rgbKey, GCHandleType.Pinned);
GCHandle IVHandle = GCHandle.Alloc(rgbIV, GCHandleType.Pinned);
ICryptoTransform cryptoAlgorithm = algorithm.CreateEncryptor(rgbKey, rgbIV);
using (FileStream readStream = File.Open(filePath, FileMode.Open))
{
using (FileStream writeStream = new FileStream(filePath + ".enc", FileMode.Create, FileAccess.Write))
{
using (CryptoStream cryptoStream = new CryptoStream(writeStream, cryptoAlgorithm, CryptoStreamMode.Write))
{
while (readStream.Position < readStream.Length)
{
byte[] buffer = new byte[4096];
int amountRead = readStream.Read(buffer, 0, buffer.Length);
cryptoStream.Write(buffer, 0, amountRead);
}
cryptoStream.Flush();
}
}
}
UtilityMethods.destroyBytes(rgbKey);
UtilityMethods.destroyBytes(rgbIV);
keyHandle.Free();
IVHandle.Free();
}
What I want to do is multithread the process for faster encryption. Using a single thread, this has taken over 5 min to encrypt a ~3GB file. I'm looking to be able to do that encryption in under 1 min if possible (under 30 seconds would be fantastic, but I think I might be stretching).
I believe the answer is to create multiple streams (although I'm not sure), assigning each stream a chunk of the file to encrypt, but I'm not sure how to "break the file apart" to assign a chunk to each stream, or "put the file back together" after each part has gone through the stream that it was assigned to. Could someone point me in the right direction?
Thanks very much!
P.S. I've viewed this (Rijndael algorithm and CryptoStream: is it possible to encrypt / decrypt multithreaded?), but I don't understand the answer (ECB, CBC?). If the answer to my question lies there, could you possibly provide some sample code to get me going in the right direction?
Thanks again!