繁体   English   中英

BinaryRead / Write / FileStream.Read / Write / File.Read / WriteAllBytes之后文件损坏

[英]File corrupt after BinaryRead/Write / FileStream.Read/Write /File.Read/WriteAllBytes

我正在做文件加密/解密应用程序,并且卡了很长时间。 我不敢相信读写文件会如此困难。

这是变量

    byte[] FileBytes = null; //file bytes
    byte[] KeyBytes = null; //key bytes
    byte[] ResBytes = null; //result bytes

读取文件中的所有字节

    private void ReadFile()
    {
        using (BinaryReader br = new BinaryReader(File.Open(this.txtFilePath.Text, FileMode.Open, FileAccess.Read)))
        {
            int x = 0;

            this.FileBytes = new byte[(int)br.BaseStream.Length];
            int length = (int)br.BaseStream.Length;

            while (x < length)
            {
                this.FileBytes[x] = br.ReadByte();

                x++;
            }

            br.Close();
        }
    }

写文件

    private void WriteFile()
    {
        using (BinaryWriter bw = new BinaryWriter(File.Open(this.OutputPath, FileMode.Create)))
        {
            // 3. Use foreach and write all 12 integers.
            foreach (byte b in this.ResBytes)
            {
                bw.Write(b);
            }

            bw.Flush();
            bw.Close();
        }
    }

加密方式

    public byte ApplyVernam(byte inByte, byte keyByte)
    {
        if (inByte == keyByte) { return inByte; }
        else { return (byte)(inByte ^ keyByte); }
    }

这是执行按钮单击事件(我将FileBytes [1]作为键),是的,除文本文档外,文件已损坏。 我以为BinaryWriter可以很好地进行文件加密,但是为什么它不起作用? 我的代码有问题吗? 我需要在这里解释。 非常感谢你。

    private void btnExecute_Click(object sender, EventArgs e)
    {
        try
        {
            this.ReadFile();
            this.ResBytes = new byte[this.FileBytes.Length];

            int x = 0;

            while (x < this.FileBytes.Length)
            {
                this.ResBytes[x] = this.ApplyVernam(this.FileBytes[x], this.FileBytes[1]);
                x++;
            }

            this.WriteFile();
        }
        catch
        {
            throw;
        }
    }

您的加密方法是不可逆的,因此您无法使用它可靠地解密常规二进制消息。 发生问题是因为两个不同的纯文本值可能会加密为相同的密文值,并且发生这种情况时,您无法确定何时解密哪个是正确的输入值。

例:

if inByte = 100 and keyByte = 100:
    ApplyVernam(100, 100) = 100

if inByte = 0, keyByte = 100:
    ApplyVernam(0, 100) = 100

现在,在尝试解密时,无法确定原始明文字节是0还是100

我建议删除该行: if (inByte == keyByte) { return inByte; } if (inByte == keyByte) { return inByte; }从您的ApplyVernam方法,以便它始终对输入与键进行XORs ,因此是完全可逆的。

如我的评论中所述,您的“密钥”是输入中位置1的字节,但是它也已被加密,因此当您解密时,位置1的字节不再是原始密钥。 更改以下行可能会解决此问题:

从:

this.ResBytes[x] = this.ApplyVernam(this.FileBytes[x], this.FileBytes[1]);

至:

this.ResBytes[x] = x == 1 ? this.FileBytes[x] : this.ApplyVernam(this.FileBytes[x], this.FileBytes[1]);

这将确保密钥字节未加密地写入输出。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM