views:

75

answers:

2

I would like to create a file "myFile" that encrypts the first part using a certain key, and the last part using a certain key. So far I have something like this:

cs1 = new CryptoStream(myFile, symmetricKey1.CreateEncryptor(key1, key1IV), CryptoStreamMode.Write);

cs2 = new CryptoStream(myFile, symmetricKey2.CreateEncryptor(key2, key2IV), CryptoStreamMode.Write);

And I would like to write to the first part of the file using cs1 and second with cs2 sort of like this:

while((data = fs1.readByte()) != -1){
    cs1.WriteByte(data);
}

while((data = fs2.readByte()) != -1){
    cs2.WriteByte(data);
}

This proceeds without error, but the second CryptoStream (cs2) does not actually write to the file. Does anyone know why this would happen? Is there a better way to do this? Thanks

edit: Closing the CryptoStream does seem to close myFile as well, but if I close and then reopen and then start the second CryptoStream, this seems to work though its not as clean as I had hoped for. Thanks for the help!

+1  A: 

I think you should at least call cs1.FlushFinalBlock() after the while loop (same for cs2).

And create cs2 after you are done with cs1. You may have to investigate if closing cs1 close the myFile stream, StreamReaders will do that but i saw no mention of it in the CryptoStream documentation.

Henk Holterman
A: 

Try the following after each while loop.

csX.Flush();
csX.Dispose();

Or even better, use a using block and create cs2 after cs1 has already been disposed.

Taylor Leese