I enter the name of archive in a textbox to get the message of this archive.
I write password in a textbox
I Calculate the salt.
Button Click
private void button1_Click_1(object sender, EventArgs e)
{
String message;
String password;
String result;
String resultSalt;
String nameResult;
byte[] salt;
password = textBox2.Text;
nameResult = textBox3.Text;
new RNGCryptoServiceProvider().GetBytes(salt = new byte[16]);
resultSalt = Convert.ToBase64String(salt);
if (radioButton1.Checked == true)
{
message = readArchive();
result = Encrypt(message,password,resultSalt);
try
{
File.WriteAllText(nameResult, result);
MessageBox.Show("Encrypt Ok");
}
catch
{
MessageBox.Show("Error");
}
}
else
{
message = readArchive();
result = Decrypt(message,password,result);
try
{
File.WriteAllText(nameResult, resultSalt);
MessageBox.Show("Decrypt OK");
}
catch
{
MessageBox.Show("Error");
}
}
}
Method Encrypt
public static string Encrypt(string message, string pass, string salt)
{
AesCryptoServiceProvider aes = new AesCryptoServiceProvider();
DeriveBytes rgb = new Rfc2898DeriveBytes(pass, Encoding.Unicode.GetBytes(salt), 9);
byte[] key = rgb.GetBytes(aes.KeySize >> 3);
byte[] iv = rgb.GetBytes(aes.BlockSize >> 3);
aes.Mode = CipherMode.CBC;
aes.Key = key;
aes.IV = iv;
ICryptoTransform encryptor = aes.CreateEncryptor();
byte[] data = Encoding.Unicode.GetBytes(message);
byte[] dataencrypt = encryptor.TransformFinalBlock(data, 0, data.Length);
return Convert.ToBase64String(dataencrypt);
}
Method decrypt
public static string Decrypt(string message, string pass, string salt)
{
AesCryptoServiceProvider aes = new AesCryptoServiceProvider();
DeriveBytes rgb = new Rfc2898DeriveBytes(pass, Encoding.Unicode.GetBytes(salt), 9);
byte[] key = rgb.GetBytes(aes.KeySize >> 3);
byte[] iv = rgb.GetBytes(aes.BlockSize >> 3);
aes.Mode = CipherMode.CBC;
aes.Key = key;
aes.IV = iv;
ICryptoTransform decryptor = aes.CreateDecryptor();
byte[] data = Convert.FromBase64String(message);
byte[] datadecrypt = decryptor.TransformFinalBlock(data, 0, data.Length);
return Encoding.Unicode.GetString(datadecrypt);
}
Method readArchive
private string readArchive()
{
String nameArchive = textBox1.Text;
String text = "";
try
{
text = File.ReadAllText(@nameArchive);
}
catch
{
MessageBox.Show("Error.");
}
return text;
}
Error line
byte[] datadecrypt = decryptor.TransformFinalBlock(data, 0, data.Length);
Unhandled exception of type 'System.Security.Cryptography.CryptographicException' in System.Core.dll
Additional information: The padding between characters is not valid and can not be removed.