1

I'm trying to encrypt/decrypt a file using AES 256 bit with the code I got from here. The full code I am using is seen here. I was wondering how I could calculated the percentage done of both encryption/decryption in the while loop as it writes to the file. For example in encryption:

while ((read = fsIn.Read(buffer, 0, buffer.Length)) > 0)
{
    cs.Write(buffer, 0, read);
    //int percentage = Calculate percentage done here?
}

And in decryption:

while ((read = cs.Read(buffer, 0, buffer.Length)) > 0)
{
    fsOut.Write(buffer, 0, read);
    //int percentage = Calculate percentage done here?
}
Community
  • 1
  • 1
Justin G
  • 172
  • 3
  • 19

2 Answers2

1

You can compute the percentage complete as follows:

var percentComplete = (float)fsIn.Position * 100 / fsIn.Length;

How you display it is up to you. You can update a form control (you may need to use invoke if your cypto runs on a worker thread) or raise a custom event (e.g. ProgressChanged) and consume it in your UI thread.

Community
  • 1
  • 1
John Wu
  • 50,556
  • 8
  • 44
  • 80
  • Thank you, I've used this in my final answer where I also include how to show percentage for file decryption :) – Justin G Aug 20 '16 at 19:52
1

I was able to get it worked with both encryption and decryption. For encryption, I used:

var percentComplete = (float)fsIn.Position * 100 / fsIn.Length;

As John Wu stated. For decryption, I used:

var percentComplete = (float)fsOut.Position * 100 / fsCrypt.Length;

This works because it divides the Position(x100) by the total length of the encrypted file, as opposed to fsOut.Length; which only returns the data that's been written out to the new decrypted file.

Community
  • 1
  • 1
Justin G
  • 172
  • 3
  • 19