using System.IO;
using System.Security;
using System.Security.Cryptography;
string passValue;
private void EncryptButton_Click(object sender, EventArgs e)
{
try
{
passValue = textBox1.Text;
RandomNumberGenerator rnd = RandomNumberGenerator.Create();
byte[] salt = new byte[16];
rnd.GetBytes(salt);
Rfc2898DeriveBytes derBytes = new Rfc2898DeriveBytes(passValue, salt);
byte[] key = derBytes.GetBytes(16);
Rijndael cryptoAlg = Rijndael.Create();
cryptoAlg.Key = key;
FileStream fs = new FileStream(@"C:\Hello\EncryptPass.txt", FileMode.Create);
fs.Write(salt, 0, salt.Length);
fs.Write(cryptoAlg.IV, 0, cryptoAlg.IV.Length);
CryptoStream cryptStream = new CryptoStream(fs, cryptoAlg.CreateEncryptor(), CryptoStreamMode.Write);
//Converting a string to an byte array
byte[] ar = System.Text.Encoding.UTF8.GetBytes(passValue);
cryptStream.Write(ar, 0, ar.Length);
cryptStream.FlushFinalBlock();
cryptStream.Close();
MessageBox.Show("Data Encrypted");
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
private void DecryptButton_Click(object sender, EventArgs e)
{
try
{
Rijndael deCryptoAlg = Rijndael.Create();
FileStream fs3 = new FileStream(@"C:\Hello\DecryptPass.txt", FileMode.OpenOrCreate);
FileStream fs2 = new FileStream(@"C:\Hello\EncryptPass.txt", FileMode.Open);
byte[] salt = new byte[16];
byte[] IV = new byte[deCryptoAlg.IV.Length];
fs2.Read(salt, 0, salt.Length);
fs2.Read(IV, 0, IV.Length);
Rfc2898DeriveBytes derByte = new Rfc2898DeriveBytes(passValue, salt);
byte[] key = derByte.GetBytes(16);
deCryptoAlg.Key = key;
deCryptoAlg.IV = IV;
CryptoStream cryStream = new CryptoStream(fs2, deCryptoAlg.CreateDecryptor(), CryptoStreamMode.Read);
int bytesRead = 0;
byte[] buffer = new byte[256];
do
{
bytesRead = cryStream.Read(buffer, 0, 256);
} while (bytesRead > 0);
fs3.Write(buffer, 0, 256);
fs3.Flush();
cryStream.Close();
MessageBox.Show("File Decrypted");
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
No comments:
Post a Comment