### Table of Contents

# RC4

RC4 is a stream cipher designed by Ron Rivest in 1987. It works by generating a string of pseudorandom bits based on a key that can be combined with plaintext through the use of exclusive-or (XOR) to produce the ciphertext. Decryption is the same process, as XOR is the inverts itself. This is possible because given the same key, RC4 will always produce the same keystream. There are two main parts to RC4, the Key Scheduling Algorithm (KSA) and the Pseudo-Random Generation Algorithm (PRGA).

## Key Scheduling Algorithm (KSA)

The KSA initializes the internal state array “S”, first by setting it to the identity permutation, then by mixing in the key. This is demonstrated in the below C code, where K is an array holding the key, and klen is an integer holding the length of the key (not including any NULL terminator).

unsigned char S[256]; int i = 0, x = 0; for(i = 0; i < 256; i++) S[i] = i; for(i = 0; i < 256; i++) { x = (x + S[i] + K[i % klen]) % 256; swap(&S[i], &S[x]); }

Note that this implementation relies on an external function that wasn't shown, swap(). A possible implementation follows.

void swap(unsigned char *a, unsigned char *b) { unsigned char t = *a; *a = *b; *b = t; return; }

## Pseudo-Random Generation Algorithm (PRGA)

The PRGA produces the output of the RC4 algorithm, the keystream, which can then be combined with the message to produce the ciphertext or plaintext. This loop may run as many times as necessary to generate enough of the keystream to encrypt or decrypt the data; the value used below (256) is arbitrary. Each iteration outputs one byte of keystream, stored in the array “Ks” in the example below. Note that this example continues from the KSA example, the KSA must be completed before the PRGA is run.

int count = 256, k = 0; i = x = 0; while(count--) { i = (i + 1) % 256; x = (x + S[i]) % 256; swap(&S[i], &S[x]); Ks[k++] = S[(S[i] + S[x]) % 256]; }