1

i have tried the following code to encrypt and decrypt files using asp.net c# rijndael managed. all of the images notepad is encrypted and decrypted successfully, when it comes to doc or docx file it always showing damaged file when i tried to open. but if i click resolve this issue in microsoft word, then the file is back. what could go wrong in the code. please help me

    public void EncryptFile(string password, string inputFile, string outputFile)
    {

        try
        {

            UnicodeEncoding UE = new UnicodeEncoding();
            byte[] key = UE.GetBytes(password.Trim());

            string cryptFile = outputFile;
            FileStream fsCrypt = new FileStream(cryptFile, FileMode.Create);

            RijndaelManaged RMCrypto = new RijndaelManaged();

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

            FileStream fsIn = new FileStream(inputFile, FileMode.Open);

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


            fsIn.Close();
            cs.Close();
            fsCrypt.Close();
        }
        catch(Exception err)
        {
            System.Diagnostics.Debug.WriteLine(err);
        }
    }

    public void DecryptFile(string password, string inputFile, string outputFile)
    {
        try
        {


            UnicodeEncoding UE = new UnicodeEncoding();
            byte[] key = UE.GetBytes(password.Trim());

            FileStream fsCrypt = new FileStream(inputFile, FileMode.Open);

            RijndaelManaged RMCrypto = new RijndaelManaged();

            CryptoStream cs = new CryptoStream(fsCrypt,
                RMCrypto.CreateDecryptor(key, key),
                CryptoStreamMode.Read);

            FileStream fsOut = new FileStream(outputFile, FileMode.Create);

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

            fsOut.Close();
            cs.Close();
            fsCrypt.Close();
        }
        catch(Exception err)
        {
            System.Diagnostics.Debug.WriteLine(err);
        }

    }

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Browse other questions tagged or ask your own question.