RC4 Encryption in C#

by Gong Liu January 19, 2009 21:46

Recently I have involved in converting an ASP project to an ASP.NET project. A part of it is to translate the RC4 encryption algorithm from VB Script to C#. The VB Script implementation was taken from the article RC4 Encryption Using ASP & VBScript by Mike Shaffer published on 4guysfromrolla.com. I thought the work might be useful for someone else. So here you go...

The C# implementation of the RC4 algorithm consists of a single class RC4, which has the following public properties and methods:

  • Text property - the text to be encrypted or decrypted,
  • Password property - the password you use for the encryption or decryption,
  • EnDeCrypt method - this is the method you use to encrypt or decrypt the Text with the given Password,
  • StrToHexStr method - a utility method used to convert an encrypted string to a hex string so that it can be stored in a database or transmitted over a URL safely,
  • HexStrToStr method - a utility method used to convert a hex string to a string. It has the opposite effect as StrToHexStr method.

Now let's see some code. The following is the code snip for the EnDeCrypt method: 

        public string EnDeCrypt()
        {
            RC4Initialize();

            int i = 0, j = 0, k  = 0;
            StringBuilder cipher = new StringBuilder();
            for (int a = 0; a < text.Length; a++)
            {
                i = (i + 1) % N;
                j = (j + sbox[i]) % N;
                int tempSwap = sbox[i];
                sbox[i] = sbox[j];
                sbox[j] = tempSwap;

                k = sbox[(sbox[i] + sbox[j]) % N];
                int cipherBy = ((int)text[a]) ^ k;  //xor operation
                cipher.Append(Convert.ToChar(cipherBy));
            }
            return cipher.ToString();
        }

        private void RC4Initialize()
        {
            sbox = new int[N];
            int[] key = new int[N];
            int n = password.Length;
            for (int a = 0; a < N; a++)
            {
                key[a] = (int)password[a % n];
                sbox[a] = a;
            }

            int b = 0;
            for (int a = 0; a < N; a++)
            {
                b = (b + sbox[a] + key[a]) % N;
                int tempSwap = sbox[a];
                sbox[a] = sbox[b];
                sbox[b] = tempSwap;
            }
        }

The above code is a direct translation from the original VB Script. Note that the StringBuilder class is used here to improve the efficiency of string concatenation. The code snips for the StrToHexStr and HexStrToStr methods are as follows:

        public static string StrToHexStr(string str)
        {
            StringBuilder sb = new StringBuilder();
            for (int i = 0; i < str.Length; i++)
            {
                int v = Convert.ToInt32(str[i]);
                sb.Append(string.Format("{0:X2}", v));
            }
            return sb.ToString();
        }

        public static string HexStrToStr(string hexStr)
        {
            StringBuilder sb = new StringBuilder();
            for (int i = 0; i < hexStr.Length; i += 2)
            {
                int n = Convert.ToInt32(hexStr.Substring(i, 2), 16);
                sb.Append(Convert.ToChar(n));
            }
            return sb.ToString();        
        }

The StrToHexStr method converts each character in the input string to a 2-byte hex number without any prefix or suffix. The HexStrToStr method takes a hex string (generated by the StrToHexStr method) and converts it back to the original string.

Here is the code to show how to use the RC4 class in a simple ASP.Net project:

        protected void btnDoIt_Click(object sender, EventArgs e)
        {
            RC4 rc4 = new RC4(txtPassword.Text, txtText.Text);
            txtHexDump.Text = RC4.StrToHexStr(rc4.EnDeCrypt());
            rc4.Text = RC4.HexStrToStr(txtHexDump.Text);
            txtDecrypted.Text = rc4.EnDeCrypt();           
        }

In the "Do It!" button click event handler we first instantiate the RC4 class by passing the password and the text to be encrypted to the constructor. In the next line we call the EnDeCrypt method to encrypt the text, and then convert the encrypted string to a hex string by calling the StrToHexStr utility method. For decryption we simply do the opposite. Call the HexStrToStr method to convert the hex dump back to the original encrypted string and then call EnDeCrypt method again to decrypt it. The screenshot below shows what looks like after the "Do It!" button is clicked.

You can see a live demo here

You can download the RC4 class along with the sample ASP.Net project below.

TestRC4.zip (23.57 kb)

About

A seasoned computer professional. A tofu culture evangelist...
more >>

Tag Cloud

Calendar

<<  April 2017  >>
MoTuWeThFrSaSu
272829303112
3456789
10111213141516
17181920212223
24252627282930
1234567

View posts in large calendar
Copyright © 2008-2011 Gong Liu. All rights reserved. | credits | contact me
The content on this site represents my own personal opinions, and does not reflect those of my employer in any way.