开发者

Two CryptoStreams associated with one file in C#

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)开发者_如何学Python, 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!


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.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜