This is an implementation of the RC4 (also known as "ARCFOUR" for copyright reasons) stream cipher in C.
There are two steps to the cipher. First, the KSA function uses a user-supplied key to initialize the "state" matrix. Then, the PRGA function uses the state to generate pseudo-random output of any desired length, called the keystream. For encryption, this keystream is XOR'd by the plaintext to yield ciphertext. For decryption, the keystream is XOR'd by the ciphertext to yield plaintext.
void ksa(unsigned char state, unsigned char key, int len)
The KSA function takes a state and key and permutates the state with the key.
unsigned char state-- This is the state that will be initialized by the key. It must be 256 bytes in size.
unsigned char key-- This is the key to use for encryption/decryption.
int len-- This is the length of the key in bytes.
void prga(unsigned char state, unsigned char out, int len)
The PRGA function generates the keystream. The state is permutated to generate each byte of the keystream, and its original value is not saved. So generating 8 bytes of output in one function call followed by 8 more bytes of output in separate function call will yield the same keystream as generating all 16 bytes of output in one function call.
unsigned char state-- The state array initialized by ksa().
unsigned char out-- The array to store the output in. This is XOR'd by the plaintext/ciphertext. It must be the length of the "len" (below) value.
int len-- The number of bytes to generate.
- Create a state array of necessary size, generate a key, and determine it's size.
- Call the KSA() function.
- Call the PRGA() function.
- XOR the output from PRGA() against the plaintext/ciphertext to yield the desired ciphertext/plaintext.
In this implementation, the state is an 256-byte unsigned character array. Due to its minimal nature RC4 allows for little by way of optimization.
Cryptanalysis of RC4 has been shown that weaknesses in the algorithm allow the first 256 bytes of the keystream to be used to extrapolate the original key. When generating a keystream, it is recommended that you always discard the first 256 bytes of output, or the first 1K of bytes, just to be safe.