Windows Forms: Encryption and Decryption using RC4 in C#

This tutorial shows you how to encrypt and decrypt string using RC4 (Rivest Cipher 4) algorithm in C#.NET Windows Forms Application.

To play the demo, you can drag the textbox, label and button from the visual studio toolbox into your winform, then you can design a simple UI that allows you to encrypt and decrypt a string using the RC4 algorithm as shown below.

c# rc4 encryption algorithm

You can see the picture below, to see how the rc4 algorithm works.

rc4 algorithm

The output byte is selected by looking up the values of S(i) and S(j), adding them together modulo 256, and then looking up the sum in S, S(S(i) + S(j)) is used as a byte of the key-stream, K.

OK, Now we will implement the RC4 algorithm in c# by creating an RC4 method to encrypt your data using RC4 algorithm as shown below.

//c# encrypt string rc4
public string RC4(string input, string key)
{
    StringBuilder result = new StringBuilder();
    int x, y, j = 0;
    int[] box = new int[256];
    for (int i = 0; i < 256; i++)
        box[i] = i;
    for (int i = 0; i < 256; i++)
    {
        j = (key[i % key.Length] + box[i] + j) % 256;
        x = box[i];
        box[i] = box[j];
        box[j] = x;
    }
    for (int i = 0; i < input.Length; i++)
    {
        y = i % 256;
        j = (box[y] + j) % 256;
        x = box[y];
        box[y] = box[j];
        box[j] = x;
        result.Append((char)(input[i] ^ box[(box[y] + box[j]) % 256]));
    }
    return result.ToString();
}

RC4 algorithm performs encryption and decryption in c# with key. So you can add code to the Encrypt button click event as the following c# code.

private void btnEncrypt_Click(object sender, EventArgs e)
{
    txtEncrypt.Text = RC4(txtInput.Text, "123");
}

Finally, Add code to the Decrypt button

private void btnDecrypt_Click(object sender, EventArgs e)
{
    txtDecrypt.Text = RC4(txtEncrypt.Text, "123");
}

You can also use the RC4 algorithm to encrypt and decrypt password using c# code.