0

okay so I have this code for decrypting files

    public static byte[] DecryptFile(string inputFile, string skey)
    {
        RijndaelManaged aes = new RijndaelManaged();

            byte[] key = ASCIIEncoding.UTF8.GetBytes(skey);

            using (FileStream fsCrypt = new FileStream(inputFile, FileMode.Open))
            {
                using (CryptoStream cs = 
    new CryptoStream(fsCrypt, aes.CreateDecryptor(key, key),
    CryptoStreamMode.Read))
                {
                    using (BinaryReader reader = new BinaryReader(cs))
                    {
                        byte[] str = reader.ReadBytes(Convert.ToInt32(cs.Length));
                        reader.Close();

                        cs.Close();

                        return (str);
                    }
                }
            }

        }
    }

NOW i've got a problem with it, i can't determine the byte length! I tried

cs.Length

but it says the Stream doesn't support seeking (something like tht) I also tried counting the bytes of the file by

File.ReadAllBytes(encrypted_file_path).Length

but it says the file is in use...it is indeed in use because of the FileStream fsCrypt

for the meantime I replaced cs.Length with some large integer to make it work..like 1000000..the maximum integer that doesn't cause any exception..it does work that way.

PeeHaa
  • 71,436
  • 58
  • 190
  • 262

1 Answers1

4

You cannot know the length until after you decrypt the entire file.

Therefore, you need to start with a small array, and make it bigger as it gets full.

The MemoryStream class does just that; you can just cs.CopyTo() into a new MemoryStream and call ToArray().

SLaks
  • 868,454
  • 176
  • 1,908
  • 1,964
  • Wait, I thought you could create a FileInfo object for the file and use it's length property. Although that might just be the size on disk. Honestly I would just make a byte list and call ToArray() at the end if it has to be in Array form. – Benjamin Danger Johnson Sep 30 '12 at 01:37
  • 3
    @BenjaminDangerJohnson: No. Ciphertext length ≠ plaintext length. – SLaks Sep 30 '12 at 01:58
  • well if i do that the position of the stream "cs" would go to end and resulting str to be null..and It is not allowed to seek in CryptoStream cs.. EDIT: so instead I didn't use the BinaryReader..and just set byte[] str to MemoryStream().ToArray..thanks! – Vince Jerald Villamora Sep 30 '12 at 02:20