Click here to Skip to main content
15,892,965 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
C#
private void button1_Click(object sender, EventArgs e)
{
    byte[] key = UnicodeEncoding.Unicode.GetBytes("a");
    byte[] data = UnicodeEncoding.Unicode.GetBytes(richTextBox1.Text);
    RC4(ref data, key);
    richTextBox1.Text = UnicodeEncoding.Unicode.GetString(data);
}

private void button2_Click(object sender, EventArgs e)
{
    byte[] key = UnicodeEncoding.Unicode.GetBytes("a");
    byte[] data = UnicodeEncoding.Unicode.GetBytes(richTextBox1.Text);
    RC4(ref data, key);
    richTextBox1.Text = UnicodeEncoding.Unicode.GetString(data);
}

public void RC4(ref Byte[] bytes, Byte[] key)
{
    Byte[] s = new Byte[256];
    Byte[] k = new Byte[256];
    Byte temp;
    int i, j;

    for (i = 0; i < 256; i++)
    {
        s[i] = (Byte)i;
        k[i] = key[i % key.GetLength(0)];
    }

    j = 0;
    for (i = 0; i < 256; i++)
    {
        j = (j + s[i] + k[i]) % 256;
        temp = s[i];
        s[i] = s[j];
        s[j] = temp;
    }

    i = j = 0;
    for (int x = 0; x < bytes.GetLength(0); x++)
    {
        i = (i + 1) % 256;
        j = (j + s[i]) % 256;
        temp = s[i];
        s[i] = s[j];
        s[j] = temp;
        int t = (s[i] + s[j]) % 256;
        bytes[x] ^= s[t];
    }
}


I am doing this RC4 encryption, i don't know why but when i do the decryption for some reason it doesnt go back to the original text (most of the text does, but some letter doesnt). Do you have any idea why ?
Posted

1 solution

Try the following article : RC4 Encryption Algorithm: C# Version[^]
 
Share this answer
 

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