Rajeshwar
Rajeshwar

Reputation: 11651

Copying from memory stream to File Stream fails

I am attempting to copy a memory stream to a file stream. I noticed that the output exe is corrupt when decrypted. I am certain there is no issue with the decrypt function. Here is the code

 private MemoryStream My_Encrypt(Stream inputFile)
        {

                //FileStream fsCrypt = new FileStream(cryptFile, FileMode.Create);
                MemoryStream fsCrypt = new MemoryStream();

                RijndaelManaged RMCrypto = new RijndaelManaged();

                CryptoStream cs = new CryptoStream(fsCrypt, RMCrypto.CreateEncryptor(key, key), CryptoStreamMode.Write);

                int data;
                while ((data = inputFile.ReadByte()) != -1)
                    cs.WriteByte((byte)data);

                inputFile.Flush();

                return fsCrypt;

        }


        MemoryStream ms = My_Encrypt(bundleStream);
        ms.Seek(0, SeekOrigin.Begin);

        FileStream atest = new FileStream("c:\\Somefile.exe",FileMode.Create);
        ms.Seek(0, SeekOrigin.Begin);
        ms.CopyTo(atest);

        atest.Close();

More details: The reason I am saying that the memory stream method is not working is because in My_Encrypt method if I replace fsCrypt with FileStream instead of Memory Stream and close fsCrypt at the end of the method and then reopen the saved file and write it to another file it works. My question is why is the memory stream method not working.

Upvotes: 1

Views: 759

Answers (1)

Igor
Igor

Reputation: 62213

I believe you have to call FlushFinalBlock on the CryptoStream.

private MemoryStream My_Encrypt(Stream inputFile)
{
    //FileStream fsCrypt = new FileStream(cryptFile, FileMode.Create);
    MemoryStream fsCrypt = new MemoryStream();

    RijndaelManaged RMCrypto = new RijndaelManaged();

    CryptoStream cs = new CryptoStream(fsCrypt, RMCrypto.CreateEncryptor(key, key), CryptoStreamMode.Write);

    int data;
    while ((data = inputFile.ReadByte()) != -1)
        cs.WriteByte((byte)data);

    cs.FlushFinalBlock();

    return fsCrypt;
}

Upvotes: 2

Related Questions