C# - RC4 Encryption

By , 8/26/2007
(1 ratings)
RC4 is a stream cipher designed by Ron Rivest for RSA Security. Here is a RC4-encryption function for C#

Sample call:

Byte[] Key = { 25, 64, 1, 45, 54, 45 };
Byte[] Content = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };

// encrypt
RC4(ref Content, Key);

// decrypt
RC4(ref Content, Key);
Translate to VB
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];
    }
}

Tagged with RC4, Encryption, Security.

Comments

 

Log in, to comment!