Question

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.

Was it helpful?

Solution

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().

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top