0

我加密了一个文件并将加密的内容写入同一个文件。但是当我解密文件并尝试将其写入相同文件时,我无法清除旧内容,即我的加密文本。我怎么能那样做。

加密代码

static void EncryptFile(string sInputFilename,string sKey)
    {
        FileStream fsInput = new FileStream(sInputFilename,
           FileMode.Open,
           FileAccess.ReadWrite);

        DESCryptoServiceProvider DES = new DESCryptoServiceProvider();
        DES.Key = ASCIIEncoding.ASCII.GetBytes(sKey);
        DES.IV = ASCIIEncoding.ASCII.GetBytes(sKey);
        ICryptoTransform desencrypt = DES.CreateEncryptor();
        CryptoStream cryptostream = new CryptoStream(fsInput,
           desencrypt,
           CryptoStreamMode.Write);

        byte[] bytearrayinput = new byte[fsInput.Length];
        fsInput.Read(bytearrayinput, 0, bytearrayinput.Length);
        fsInput.SetLength(0);
        cryptostream.Write(bytearrayinput, 0, bytearrayinput.Length);
        cryptostream.Close();
        fsInput.Close();
    }

解密代码

static void DecryptFile(string sInputFilename,
     string sKey)
    {
        DESCryptoServiceProvider DES = new DESCryptoServiceProvider();
        DES.Key = ASCIIEncoding.ASCII.GetBytes(sKey);
        DES.IV = ASCIIEncoding.ASCII.GetBytes(sKey);
        FileStream fsread = new FileStream(sInputFilename,
           FileMode.Open,
           FileAccess.ReadWrite);

        ICryptoTransform desdecrypt = DES.CreateDecryptor();

        CryptoStream cryptostreamDecr = new CryptoStream(fsread,
           desdecrypt,
           CryptoStreamMode.Read);
        int data;

        while ((data = cryptostreamDecr.ReadByte()) != -1)
        {
            fsread.WriteByte((byte)data);
        }

        fsread.Close();
        cryptostreamDecr.Close();
    } 
4

1 回答 1

1

您在解密时尝试将加密文件写入适当的位置,因此您最终会在完成读取之前将额外的未加密数据添加到末尾。

假设由于某种原因你不能只接受 lcryder 的建议,如果你真的需要在最后将数据写回同一个文件,你可以在内存中解密它并在完成后写入:

private static void DecryptFile(string sInputFilename,
    string sKey)
{
    var DES = new DESCryptoServiceProvider();
    DES.Key = Encoding.ASCII.GetBytes(sKey);
    DES.IV = Encoding.ASCII.GetBytes(sKey);
    ICryptoTransform desdecrypt = DES.CreateDecryptor();

    using(var fsread = new FileStream(sInputFilename,
        FileMode.Open,
        FileAccess.ReadWrite))
    {
        using(var cryptostreamDecr = new CryptoStream(fsread,
            desdecrypt,
            CryptoStreamMode.Read))
        {
            int data;

            fsread.Flush();

            using(var ms = new MemoryStream())
            {
                while((data = cryptostreamDecr.ReadByte()) != -1)
                {
                    ms.WriteByte((byte) data);
                }

                cryptostreamDecr.Close();

                using(var fsWrite = new FileStream(sInputFilename, FileMode.Truncate))
                {
                    ms.WriteTo(fsWrite);
                    ms.Flush();
                }
            }
        }
    }
}

当您关闭读取文件流并打开一个新文件流进行写入时,内存流会保存未加密的数据(使用 FileMode.Truncate 因此原始内容被破坏)。

于 2013-05-23T14:05:21.307 回答