Windows Forms: Encryption and Decryption using RC4 in C#
By FoxLearn 2/26/2024 9:12:56 AM 10.89K
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.
You can see the picture below, to see how the rc4 algorithm works.
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.
- Windows Forms: Encryption and Decryption using RSA in C#
- Windows Forms: MD5 encryption in C#
- Windows Forms: Encryption and Decryption using ROT13 in C#
- Windows Forms: Encryption and Decryption using Triple DES in C#
- Windows Forms: How to Encrypt and Decrypt ConnectionString in App.config file in C#
- Windows Forms: How to Encrypt and Decrypt files using AES encryption algorithm in C#
- Windows Forms: Encrypt and Decrypt a String in C#