开发者

Please Advise on Performance in C# File Encryption

I have created a test (not real) encryption function which takes a byte[] and replaces all the bytes with 0xff and returns

private byte[] encrypt(byte[] input)
        {


            for (int i = 0; i < input.Length; i++)
            {
                input[i] = 0xff;
            }

            return input;



        }

Now i want to try this test encryption procedure on a file. But i want to be able to read and write to the SAME file.

This is what I have done so far

using (FileStream myfileStream = new FileStream(openFile, FileMode.Open,FileAccess.ReadWrite))

    {   

    byte[] buffer = new byte[16]; 



        while (myfileStream.Position < myfileStream.Length)
        {

          myfileStream.Read(buffer, 0, 16);

          buffer = encrypt(buffer);

          myfileStream.Position -= 16;

          myfileStream.Write(buffer, 0, 16);

         }

         myfileStream.Close();            

    }

This works fine but I know I am not doing this right. This seems to have VERY serious performance issues where it took 24 seconds for a 1 MB file. (Tested with a StopWatch in a WinMo 6 Pro emulator).

What am I doing wrong here? What can I do to increase the performance when reading and writing to/from the same file at the same time ? Please advise. Thanx a lot in advance :)


UPDATE:

I reduced the time it took significantly (from 24 seconds, down to 6 seconds) by using 2 FileStream objects pointing to the same file with FileShare.ReadWrite proper开发者_JS百科ty.

Is this safe to do? Is this ok?

UPDATE AGAIN

Although I have used a fake encryption algorithm, I am hoping to use AES with CBC + CTS.


A couple of things come to mind immediately:

  1. Use a larger buffer - why only 16 bytes?
  2. Don't write to the same file - you can delete/rename after encrypting.

Update

Even with EAS and the 16 byte constraint, you can do the encryption in memory (for large files, use a large buffer instead of encrypting the whole file in memory).

You should not be using two filesteams like that - you may end up writing parts of the file that you will be reading on later.

In regards to the buffers - you can read large chunks from disk, then operate on 16 bytes at a time in memory before writing back large chunks of encrypted data.


Do not check the file length in the while block (i.e. myfileStream.Length), as this results in a system call to check the file length on each iteration. Instead put the file length in a variable before the while loop, and use the variable instead.

Whilst a larger buffer will help, remember that some buffering will already be taken care of by:

  1. The stream class itself.
  2. The operating system disk cache.
  3. The drive buffer.

Reading the file length repeatedly in the while block is likely to be the major problem.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜