加密和解密后损坏的word文件(doc,docx)

时间:2018-06-01 04:10:46

标签: c# asp.net encryption aes

我尝试使用asp.net c#rijndael managed加密和解密文件以下代码。所有图像记事本都被成功加密和解密,当涉及到doc或docx文件时,它总是在我试图打开时显示损坏的文件。但如果我单击在Microsoft Word中单击解决此问题,则文件将返回。代码中可能出错的地方。请帮帮我

    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 个答案:

没有答案