Click here to Skip to main content
15,909,897 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
private void button1_Click_1(object sender, EventArgs e)
{
    string enc = rc("some string", "some key", true);
    MessageBox.Show(enc);
    string dec = rc(enc, "some key", false);
    MessageBox.Show(dec);
}



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);
    rc2.GenerateIV();
    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;
    }
}

Why:
- encrypted string is different each time
- decrypted string is wrong(all characters before 'ing' are unreadable)
?
Please, help.
Posted

rc2.GenerateIV() was needed to replace with something fixed as this:
rc2.IV = new byte[] { 23, 10, 99, 73, 44, 69, 35, 80 };
 
Share this answer
 
I don't know much about RC2, but are you sure that it is not supposed to make a new encrypted string everytime? Probably not, but I've heard of it before.
 
Share this answer
 
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
 
Share this answer
 
v2

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900