Generating RC4 Keystream

Joined
May 30, 2011
Messages
443
Reaction score
95
The .NET Framework does not support RC4 natively, and very literally every implementation I've seen is nonfunctional. I've attempted to write an implementation of my own, but like the other libraries I've used, it fails to generate a keystream consistent with the IETF test vectors. My source is identical to the specification on the RC4 Wikipedia page so far as I can tell.

PHP:
            var key = new byte[] { 1, 2, 3, 4, 5 };

            var sbox = Enumerable.Range(0, 256).Select(i => (byte)i).ToArray();

            for (int i = 0, j = 0; i < sbox.Length; i++) {
                j = (j + key[i % key.Length] + sbox[i]) % 256;
                sbox.Swap(i, j);
            }
 
Where are you seeing this?

In the RFC and in the Wiki. The RFC says pretty clearly the output is the key stream for 4096 (+16) bytes but it's not S box data, and it's shown at different offsets (important!).

Here, I threw this together:

http://jmerlin.net/rc4.html

Has correct output of the key stream generator. Just XOR to win. I'd throw away the first 1KB or so in any real use case.
 
Last edited:
I was looking in the wrong part of my code. I had used some reference code to generate the keystream, which was doing this:

PHP:
plaintext[i] ^ sbox[i + j]
 
Back