The problem is that the following line
halabella wrote:
rc2.GenerateIV();
every time is called generates a
new random vector.
Quick fix:
Add the following class member variable:
byte [] iv =null;
then modify the function this way:
private string rc(string text, string key, bool enc)
{
string plainText = text;
byte[] buffer = ASCIIEncoding.ASCII.GetBytes(plainText);
RC2CryptoServiceProvider rc2 = new RC2CryptoServiceProvider();
rc2.Key = ASCIIEncoding.ASCII.GetBytes(key);
if (iv == null)
{
rc2.GenerateIV();
iv = rc2.IV;
}
else
{
rc2.IV = iv;
}
if (enc)
{
string encryptedString = Convert.ToBase64String(
rc2.CreateEncryptor().TransformFinalBlock(
buffer, 0, buffer.Length));
return encryptedString;
}
else
{
buffer = Convert.FromBase64String(text);
byte[] b_dec = rc2.CreateDecryptor().TransformFinalBlock(buffer, 0, buffer.Length);
string decryptedString = ASCIIEncoding.ASCII.GetString(b_dec);
return decryptedString;
}
}
Of course you may find a more elegant soultion depending on your needs