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?