本文介绍了ByteArray加密后文件损坏的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我加密/解密文本文档,我写的这种加密方法。

然后我尝试加密word文档纯文本(内容),遗憾的是某些字符不受支持。

所以我决定加密整个文件字节。

我认为这种方法可以加密任何文件,因为现在我加密了整个字节。

但是在我加密之后解密,文件损坏,文本文件除外。

这是我的代码。



This encryption method I write working if I encrypt / decrypt text document.
Then I tried to encrypt word document plain text (content), and sadly some character was unsupported.
So I decided to encrypt the whole file bytes.
I thought this method can encrypt any file because now I encrypt the whole bytes.
But after I encrypt and decrypt, the file corrupted except text document.
This is my code.

byte[] b = null;

            b = System.IO.File.ReadAllBytes(this.txtFile.Text);

            string key = this.txtKey.Text;
            int keyIndex = 0;

            for (int i = 0; i < b.Length; i++)
            {
                if (keyIndex >= key.Length)
                {
                    keyIndex = 0; //key will repeat all over again
                }

                string fileBIN = Convert.ToString(b[i], 2);
                string keyBIN = Convert.ToString(Convert.ToInt32(Convert.ToChar(key[keyIndex])), 2);
                string newBIN = string.Empty;

                keyIndex += 1;

                if (fileBIN.Length > keyBIN.Length)
                {
                    for (int x = 0; x < Math.Abs(fileBIN.Length - keyBIN.Length); x++) { keyBIN = "0" + keyBIN; x -= 1; } //add 0 to binary that was shorter
                }
                else
                {
                    for (int x = 0; x < Math.Abs(fileBIN.Length - keyBIN.Length); x++) { fileBIN = "0" + fileBIN; x -= 1; } //add 0 to binary that was shorter
                }

                if (fileBIN == keyBIN)
                {
                    newBIN = fileBIN;
                }
                else
                {
                    for (int x = 0; x < fileBIN.Length; x++)
                    {
                        if (fileBIN.Substring(x, 1).ToString() == keyBIN.Substring(x, 1).ToString()) { newBIN += "0"; }
                        else { newBIN += "1"; }
                    }
                }
                b[i] = Convert.ToByte(newBIN, 2);
            }

            System.IO.File.WriteAllBytes(this.txtFile.Text, b);

推荐答案



这篇关于ByteArray加密后文件损坏的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-20 08:46
查看更多