检索加密的富文本文件并将其显示在 RichTextBox 中

发布于 2024-08-28 02:57:13 字数 2208 浏览 3 评论 0原文

好的,我在这里的需要是将富文本框中输入的任何内容保存到文件中,进行加密,并再次从文件中检索文本并将其显示回富文本框中。这是我的保存代码。

private void cmdSave_Click(object sender, EventArgs e)
{
    FileStream fs = new FileStream(filePath, FileMode.Create, FileAccess.Write);

    AesCryptoServiceProvider aes = new AesCryptoServiceProvider();

    aes.GenerateIV();
    aes.GenerateKey();
    aes.Mode = CipherMode.CBC;

    TextWriter twKey = new StreamWriter("key");
    twKey.Write(ASCIIEncoding.ASCII.GetString(aes.Key));
    twKey.Close();

    TextWriter twIV = new StreamWriter("IV");
    twIV.Write(ASCIIEncoding.ASCII.GetString(aes.IV));
    twIV.Close();

    ICryptoTransform aesEncrypt = aes.CreateEncryptor();

    CryptoStream cryptoStream = new CryptoStream(fs, aesEncrypt, CryptoStreamMode.Write);

    richTextBox1.SaveFile(cryptoStream, RichTextBoxStreamType.RichText);
}

我知道将密钥和 iv 保存在文件中的安全后果,但这只是为了测试:)

好吧,保存部分工作正常,这意味着没有例外...文件是在 filePath 中创建的,并且密钥和 IV 文件创建得很好太...

现在可以检索我陷入困境的部分了:S

private void cmdOpen_Click(object sender, EventArgs e)
{
    OpenFileDialog openFile = new OpenFileDialog();

    openFile.ShowDialog();

    FileStream openRTF = new FileStream(openFile.FileName, FileMode.Open, FileAccess.Read);

    AesCryptoServiceProvider aes = new AesCryptoServiceProvider();

    TextReader trKey = new StreamReader("key");
    byte[] AesKey = ASCIIEncoding.ASCII.GetBytes(trKey.ReadLine());

    TextReader trIV = new StreamReader("IV");
    byte[] AesIV = ASCIIEncoding.ASCII.GetBytes(trIV.ReadLine());

    aes.Key = AesKey;
    aes.IV = AesIV;

    ICryptoTransform aesDecrypt = aes.CreateDecryptor();

    CryptoStream cryptoStream = new CryptoStream(openRTF, aesDecrypt, CryptoStreamMode.Read);

    StreamReader fx = new StreamReader(cryptoStream);

    richTextBox1.Rtf = fx.ReadToEnd();

    //richTextBox1.LoadFile(fx.BaseStream, RichTextBoxStreamType.RichText);        
} 

但是 richTextBox1.Rtf = fx.ReadToEnd(); 抛出一个加密异常“填充无效且无法删除。 “

while richTextBox1.LoadFile(fx.BaseStream, RichTextBoxStreamType.RichText); 抛出 NotSupportedException“Stream 不支持查找。”

关于我能做什么的任何建议如何从加密文件中加载数据并将其显示在富文本框中?

OK, my need here is to save whatever typed in the rich text box to a file, encrypted, and also retrieve the text from the file again and show it back on the rich textbox. Here is my save code.

private void cmdSave_Click(object sender, EventArgs e)
{
    FileStream fs = new FileStream(filePath, FileMode.Create, FileAccess.Write);

    AesCryptoServiceProvider aes = new AesCryptoServiceProvider();

    aes.GenerateIV();
    aes.GenerateKey();
    aes.Mode = CipherMode.CBC;

    TextWriter twKey = new StreamWriter("key");
    twKey.Write(ASCIIEncoding.ASCII.GetString(aes.Key));
    twKey.Close();

    TextWriter twIV = new StreamWriter("IV");
    twIV.Write(ASCIIEncoding.ASCII.GetString(aes.IV));
    twIV.Close();

    ICryptoTransform aesEncrypt = aes.CreateEncryptor();

    CryptoStream cryptoStream = new CryptoStream(fs, aesEncrypt, CryptoStreamMode.Write);

    richTextBox1.SaveFile(cryptoStream, RichTextBoxStreamType.RichText);
}

I know the security consequences of saving the key and iv in a file but this just for testing :)

Well, the saving part works fine which means no exceptions... The file is created in filePath and the key and IV files are created fine too...

OK now for retrieving part where I am stuck :S

private void cmdOpen_Click(object sender, EventArgs e)
{
    OpenFileDialog openFile = new OpenFileDialog();

    openFile.ShowDialog();

    FileStream openRTF = new FileStream(openFile.FileName, FileMode.Open, FileAccess.Read);

    AesCryptoServiceProvider aes = new AesCryptoServiceProvider();

    TextReader trKey = new StreamReader("key");
    byte[] AesKey = ASCIIEncoding.ASCII.GetBytes(trKey.ReadLine());

    TextReader trIV = new StreamReader("IV");
    byte[] AesIV = ASCIIEncoding.ASCII.GetBytes(trIV.ReadLine());

    aes.Key = AesKey;
    aes.IV = AesIV;

    ICryptoTransform aesDecrypt = aes.CreateDecryptor();

    CryptoStream cryptoStream = new CryptoStream(openRTF, aesDecrypt, CryptoStreamMode.Read);

    StreamReader fx = new StreamReader(cryptoStream);

    richTextBox1.Rtf = fx.ReadToEnd();

    //richTextBox1.LoadFile(fx.BaseStream, RichTextBoxStreamType.RichText);        
} 

But the richTextBox1.Rtf = fx.ReadToEnd(); throws an cryptographic exception "Padding is invalid and cannot be removed."

while richTextBox1.LoadFile(fx.BaseStream, RichTextBoxStreamType.RichText); throws an NotSupportedException "Stream does not support seeking."

Any suggestions on what i can do to load the data from the encrypted file and show it in the rich text box?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

梦里兽 2024-09-04 02:57:13

你的 IV 和 Key 从来没有写在文件中(从你的 save_cmd 来看),

你的打开也是如此。您的(“Key”流和您的文件之间没有任何链接...)

更新:

这是您的代码的更好版本:

        private void button1_Click(object sender, EventArgs e)
    {


        AesCryptoServiceProvider aes = new AesCryptoServiceProvider();

        aes.GenerateIV();
        aes.GenerateKey();
        aes.Mode = CipherMode.CBC;


        File.WriteAllBytes("Key",aes.Key);
        File.WriteAllBytes("IV",aes.IV);


        ICryptoTransform aesEncrypt = aes.CreateEncryptor();
        using (FileStream fs = new FileStream("file.crypt", FileMode.Create, FileAccess.Write))
        {
            using (CryptoStream cryptoStream = new CryptoStream(fs, aesEncrypt, CryptoStreamMode.Write))
            {

                richTextBox1.SaveFile(cryptoStream, RichTextBoxStreamType.RichText);
            }
        }

    }

       private void button2_Click(object sender, EventArgs e)
    {
        OpenFileDialog openFile = new OpenFileDialog();

        openFile.ShowDialog();



        AesCryptoServiceProvider aes = new AesCryptoServiceProvider();


        byte[] AesKey = File.ReadAllBytes("Key");
        byte[] AesIV = File.ReadAllBytes("IV");

        aes.Key = AesKey;
        aes.IV = AesIV;

        ICryptoTransform aesDecrypt = aes.CreateDecryptor();
        using (FileStream openRTF = new FileStream(openFile.FileName, FileMode.Open, FileAccess.Read))
        {
            using (CryptoStream cryptoStream = new CryptoStream(openRTF, aesDecrypt, CryptoStreamMode.Read))
            {

                using (StreamReader fx = new StreamReader(cryptoStream))
                {
                    richTextBox1.Rtf = fx.ReadToEnd();
                }
            }
        }

    }

它有效。

Your IV and Key are never written in the file to begin with (judging from your save_cmd)

And same goes for your opening. There's no link at ALL between between your ("Key" stream and your file anywhere...)

Updated :

Here is a better version of your code :

        private void button1_Click(object sender, EventArgs e)
    {


        AesCryptoServiceProvider aes = new AesCryptoServiceProvider();

        aes.GenerateIV();
        aes.GenerateKey();
        aes.Mode = CipherMode.CBC;


        File.WriteAllBytes("Key",aes.Key);
        File.WriteAllBytes("IV",aes.IV);


        ICryptoTransform aesEncrypt = aes.CreateEncryptor();
        using (FileStream fs = new FileStream("file.crypt", FileMode.Create, FileAccess.Write))
        {
            using (CryptoStream cryptoStream = new CryptoStream(fs, aesEncrypt, CryptoStreamMode.Write))
            {

                richTextBox1.SaveFile(cryptoStream, RichTextBoxStreamType.RichText);
            }
        }

    }

       private void button2_Click(object sender, EventArgs e)
    {
        OpenFileDialog openFile = new OpenFileDialog();

        openFile.ShowDialog();



        AesCryptoServiceProvider aes = new AesCryptoServiceProvider();


        byte[] AesKey = File.ReadAllBytes("Key");
        byte[] AesIV = File.ReadAllBytes("IV");

        aes.Key = AesKey;
        aes.IV = AesIV;

        ICryptoTransform aesDecrypt = aes.CreateDecryptor();
        using (FileStream openRTF = new FileStream(openFile.FileName, FileMode.Open, FileAccess.Read))
        {
            using (CryptoStream cryptoStream = new CryptoStream(openRTF, aesDecrypt, CryptoStreamMode.Read))
            {

                using (StreamReader fx = new StreamReader(cryptoStream))
                {
                    richTextBox1.Rtf = fx.ReadToEnd();
                }
            }
        }

    }

It works.

夜唯美灬不弃 2024-09-04 02:57:13

由于您从未在 Save 中关闭 CryptoStream,因此它从未调用 FlushFinalBlock 来完成数据写入。因此,并未保存所有数据。

Since you never closed the CryptoStream in Save, it never called FlushFinalBlock to finish writing the data. Therefore, not all of the data was saved.

若能看破又如何 2024-09-04 02:57:13

好吧,我完美地实现了我想要实现的目标。我的代码中有几个关键错误......
首先,感谢 SLAks 和 Jipy,我发现“你应该关闭所有打开的流”:)

我犯的第二个主要错误是试图将密钥和 iv 保存在一个文件中,而实际上保存或加载它并没有工作!因此,我只有两个字节[]来保存密钥和IV,

我将填充方案更改为ISO10126,并确保在打开和关闭命令时模式都是CBC。

另外,我要做的就是添加代码以打开命令,它起作用了:) :) :)

        StreamReader fx = new StreamReader(cryptoStream);

        fx.Read(fileContent, 0, Convert.ToInt32(fileContent.Length));

        fx.Close();

        cryptoStream.Close();

        richTextBox1.Rtf = new String(fileContent);

无论如何,欢迎任何其他愚蠢的性能问题:)

这是向任何感兴趣的人提供的完整打开和关闭命令。

    byte[] globalKey = new byte[32];
    byte[] globalIV = new byte[16];

    private void cmdSave_Click(object sender, EventArgs e)
    {


        FileStream fs = new FileStream(filePath, FileMode.Create, FileAccess.Write);

        AesCryptoServiceProvider aes = new AesCryptoServiceProvider();

        aes.GenerateIV();
        aes.GenerateKey();
        aes.Mode = CipherMode.CBC;
        aes.Padding = PaddingMode.ISO10126;

        globalKey = aes.Key;
        globalIV = aes.IV;


        ICryptoTransform aesEncrypt = aes.CreateEncryptor();

        CryptoStream cryptoStream = new CryptoStream(fs, aesEncrypt, CryptoStreamMode.Write);

        richTextBox1.SaveFile(cryptoStream, RichTextBoxStreamType.RichText);

        cryptoStream.Close();
        fs.Close();

        richTextBox1.Clear();


    }

    private void cmdOpen_Click(object sender, EventArgs e)
    {
        OpenFileDialog openFile = new OpenFileDialog();

        openFile.ShowDialog();

        FileStream openRTF = new FileStream(openFile.FileName, FileMode.Open, FileAccess.Read);

        AesCryptoServiceProvider aes = new AesCryptoServiceProvider();


        aes.Key = globalKey;
        aes.IV = globalIV;
        aes.Mode = CipherMode.CBC;
        aes.Padding = PaddingMode.ISO10126;


        ICryptoTransform aesDecrypt = aes.CreateDecryptor();

        CryptoStream cryptoStream = new CryptoStream(openRTF, aesDecrypt, CryptoStreamMode.Read);

        FileInfo fileNFO = new FileInfo(openFile.FileName);

        char[] fileContent = new char[fileNFO.Length];

        StreamReader fx = new StreamReader(cryptoStream);

        fx.Read(fileContent, 0, Convert.ToInt32(fileContent.Length));

        fx.Close();

        cryptoStream.Close();

        richTextBox1.Rtf = new String(fileContent); 



    } 

OK, i achieved perfectly what i wanted to achieve. There were several key failures in my code...
First, thanx to SLaks and Jipy i figured out that "thou shall close all streams that were open" :)

And the second major blunder i did was trying to save the key and iv in a file where actually saving or loading it back did not work! Thus i just had two byte[] to save the key and IV

I changed the padding scheme to ISO10126 and made sure that the Mode was CBC when both opening and closing commands.

And else i had to do was add the code to open command and it worked :) :) :)

        StreamReader fx = new StreamReader(cryptoStream);

        fx.Read(fileContent, 0, Convert.ToInt32(fileContent.Length));

        fx.Close();

        cryptoStream.Close();

        richTextBox1.Rtf = new String(fileContent);

Anyway any other stupid performance issues are welcome :)

Here is the complete open and close commands to anyone who is interested.

    byte[] globalKey = new byte[32];
    byte[] globalIV = new byte[16];

    private void cmdSave_Click(object sender, EventArgs e)
    {


        FileStream fs = new FileStream(filePath, FileMode.Create, FileAccess.Write);

        AesCryptoServiceProvider aes = new AesCryptoServiceProvider();

        aes.GenerateIV();
        aes.GenerateKey();
        aes.Mode = CipherMode.CBC;
        aes.Padding = PaddingMode.ISO10126;

        globalKey = aes.Key;
        globalIV = aes.IV;


        ICryptoTransform aesEncrypt = aes.CreateEncryptor();

        CryptoStream cryptoStream = new CryptoStream(fs, aesEncrypt, CryptoStreamMode.Write);

        richTextBox1.SaveFile(cryptoStream, RichTextBoxStreamType.RichText);

        cryptoStream.Close();
        fs.Close();

        richTextBox1.Clear();


    }

    private void cmdOpen_Click(object sender, EventArgs e)
    {
        OpenFileDialog openFile = new OpenFileDialog();

        openFile.ShowDialog();

        FileStream openRTF = new FileStream(openFile.FileName, FileMode.Open, FileAccess.Read);

        AesCryptoServiceProvider aes = new AesCryptoServiceProvider();


        aes.Key = globalKey;
        aes.IV = globalIV;
        aes.Mode = CipherMode.CBC;
        aes.Padding = PaddingMode.ISO10126;


        ICryptoTransform aesDecrypt = aes.CreateDecryptor();

        CryptoStream cryptoStream = new CryptoStream(openRTF, aesDecrypt, CryptoStreamMode.Read);

        FileInfo fileNFO = new FileInfo(openFile.FileName);

        char[] fileContent = new char[fileNFO.Length];

        StreamReader fx = new StreamReader(cryptoStream);

        fx.Read(fileContent, 0, Convert.ToInt32(fileContent.Length));

        fx.Close();

        cryptoStream.Close();

        richTextBox1.Rtf = new String(fileContent); 



    } 
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文