Minimized example of RC4

Your original lecture notes — 3-bit and 4-bit solutions

Note: Real RC4 uses 8-bit bytes (256-element S-box). This example uses a 3-bit minimized version for clarity.

Setup (3-bit)

S = [0,1,2,3,4,5,6,7]

Key for ciphering: K = [3, 5, 2]

Plaintext: p = [6, 1, 4]

Repeated key: k = [3, 5, 2, 3, 5, 2, 3, 5]

Phase 1 — KSA

for i = 0 to 7
  j = (j + S[i] + k[i mod 8]) mod 8
Inside the loop, k[i mod 8] repeats the key when K is shorter than S.

Worked steps

Step 1: S = [0,1,2,3,4,5,6,7], k = [3,5,2,3,5,2,3,5]

Step 2: i=0, j = 0+0+3 = 3 → swap S[0]↔S[3] → S = [3,1,2,0,4,5,6,7]

Step 3: i=1, j = 3+1+5 = 9 mod 8 = 1 → swap S[1]↔S[1] (no change)

Step 4: i=2, j = 1+2+2 = 5 → swap S[2]↔S[5] → S = [3,1,5,0,4,2,6,7]

Step 5: i=3, j = 5+0+3 = 8 mod 8 = 0 → swap S[3]↔S[0] → S = [0,1,5,3,4,2,6,7]

Step 6: i=4, j = 0+4+5 = 9 mod 8 = 1 → swap S[4]↔S[1] → S = [0,4,5,3,1,2,6,7]

Step 7: i=5, j = 1+2+2 = 5 → swap S[5]↔S[5] (no change)

Step 8: i=6, j = 5+6+3 = 14 mod 8 = 6 → no swap

Step 9: i=7, j = 6+7+5 = 18 mod 8 = 2 → swap S[2]↔S[7] → S = [0,4,7,3,1,2,6,5]

Phase 2 — PRGA

S after KSA: [0, 4, 7, 3, 1, 2, 6, 5] · P = [6, 1, 4]

Stepijtk=S[t]PC=P⊕k
1145264
2232312
3322743

Ciphertext C = [4, 2, 3] — matches RC4 Keystream calculator.

4-bit example (exam practice)

Plaintext: 5 characters · n = 16