加密和解密最终损坏的文件除了文本文档

时间:2014-04-15 09:47:52

标签: c# encryption cryptography

我正在使用XOR加密,我曾尝试使用以下命令进行读写。

-File.ReadAllBytes / File.WriteAllBytes
-FileStream.Read / FileStream.Write

除文本文档外,两者都会破坏加密文件。 文本文档完全解密,没有任何遗漏/错误值。

我需要建议和解释为什么我不能加密除文本文档之外的文件。 BinaryReader会工作吗?

谢谢你。

编辑:

首先,我读取文件并键入字节数组,然后循环使用ApplyVernam加密每字节字节并插入输出变量(字节数组也是) 最后我写了这个文件。

    private void btnExecute_Click(object sender, EventArgs e)
    {
        if (this.txtFileName.Text == string.Empty) { return; }

        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[x]);
                x++;
            }

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

在此处应用Vernam功能

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

这是我读写文件的方式(请忽略写文件路径)

    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)))
        {
            foreach (byte b in this.ResBytes)
            {
                bw.Write(b);
            }

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

0 个答案:

没有答案