RC4 – C

• By Brad Conte, January 8, 2006
• Post Categories: My Code
The Algorithm
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.

Code Documentation
  • 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 This is the number of bytes to generate.
Code Usage
  1. Create a state array of necessary size, generate a key, and determine it’s size.
  2. Call the KSA() function.
  3. Call the PRGA() function.
  4. XOR the output from PRGA() against the plaintext/ciphertext to yield the desired ciphertext/plaintext.
Code
• Source Code
• Sample Driver Program

Notes
In this implementation, the state is an 256-byte unsigned character array. Due to its small and nimble nature, RC4 is a fast algorithm and requires little 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 generate 256 bytes more than necessary and discard the first 256. (Remember to do it for both your encryption and decryption code.) Or, preferably, discard the full first 1K of bytes, just to be safe.