Encrypt and Decrypt are my button names.
RijndaelEnhanced is from
http://www.obviex.com/samples/EncryptionWithSalt.aspx
Thanks
TomB
private void Encrypt_Click(object sender, System.EventArgs e)
{
Cursor.Current=Cursors.WaitCursor;
Encrypt.Text="Encrypting...";
Encrypt.Refresh();
string IV;
IV=(Password.Text+"01234567890123456").Substring(0,16);
RijndaelEnhanced re=new RijndaelEnhanced(Password.Text,IV);
StreamReader _sr=new StreamReader(FileName.Text);
byte[] byteArray=re.EncryptToBytes(_sr.ReadToEnd());
string encryptedText=Convert.ToBase64String(byteArray);
//string encryptedText=re.Encrypt(_sr.ReadToEnd());
StreamWriter _sw;
try
{
_sw=new
StreamWriter(EncryptedFileLocation.Text,false,System.Text.Encoding.UTF8);
_sw.Write( encryptedText);
//_sw.Write(Convert.ToBase64String(byteArray));
_sw.Flush();
_sw.Close();
MessageBox.Show("Encrypted File saved as " +
EncryptedFileLocation.Text,"File
Encrypted",MessageBoxButtons.OK,MessageBoxIcon.Information);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
Encrypt.Text="&Encrypt";
Cursor.Current=Cursors.Default;
}
}
private void Decrypt_Click(object sender, System.EventArgs e)
{
try
{
Decrypt.Text="Decrypting...";
Cursor.Current=Cursors.WaitCursor;
string IV;
IV=(Password.Text+"01234567890123456").Substring(0,16);
RijndaelEnhanced re=new RijndaelEnhanced(Password.Text,IV);
StreamReader _sr=new
StreamReader(EncryptedFileLocation.Text,System.Text.Encoding.UTF8);
string encryptedText=_sr.ReadToEnd();
string DecryptedText=re.Decrypt(encryptedText);
StreamWriter _sw=new
StreamWriter(DecryptedFileLocation.Text,false,System.Text.Encoding.UTF8);
_sw.Write(Convert.FromBase64String(DecryptedText));
//_sw.Write(DecryptedText);
_sw.Flush();
_sw.Close();
MessageBox.Show("Decrypted File saved as '" + DecryptedFileLocation.Text +
"'.","File Decrypted",MessageBoxButtons.OK,MessageBoxIcon.Information);
}
catch (Exception ex)
{
// I imagine an exception would occur if the password is incorrect
//MessageBox.Show(ex.Message);
MessageBox.Show("The file '" + EncryptedFileLocation.Text + "' could not be
decrypted. Please ensure you entered the correct password and filename",
"Unable to decrypt file",
MessageBoxButtons.OK,
MessageBoxIcon.Warning );
}
finally
{
Decrypt.Text="Decrypt";
Cursor.Current=Cursors.Default;
}
}