好的,我需要将在富文本框中键入的任何内容保存到文件中,加密,并再次从文件中检索文本并将其显示在富文本框中。这是我的保存代码。
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();
引发加密异常“填充无效且无法删除”。
whilerichTextBox1.LoadFile(fx.BaseStream, RichTextBoxStreamType.RichText);
抛出NotSupportedException “Stream 不支持搜索”。
关于如何从加密文件加载数据并将其显示在富文本框中的任何建议?