Learn › Part 3 · Cryptography and secure protocols

Stream ciphers: LFSR and RC4

How LFSRs work and why they fail alone, RC4's KSA and PRGA step by step, its biases, and the RC4 chat lab.

Linear feedback shift registers

An L-stage LFSR holds bits z0…zL−1. Each clock: output z0, shift every bit one place left, and insert a feedback bit = XOR of the tapped stages. A primitive feedback polynomial gives the maximum period 2L − 1 (the all-zero state is excluded).

Worked example

L = 4, seed (z0, z1, z2, z3) = (1, 0, 0, 1), feedback z0 ⊕ z1 (polynomial x4 + x + 1). Output: 1 0 0 1 1 0 1 0 … with period 15.

Why it fails alone: feedback is linear over GF(2), so about 2L consecutive output bits let an attacker solve for the taps and the state (Berlekamp–Massey). Multi-LFSR designs such as DVD CSS (17- and 25-bit registers), GSM A5/1 and Bluetooth E0 have all been broken.

RC4

A byte-oriented stream cipher with a 40–256-bit key, very fast in software. Ciphertext = plaintext ⊕ keystream; decryption is the same operation.

# 1. Initialisation
for i in 0..255:  S[i] = i;  T[i] = K[i mod keylen]

# 2. Key scheduling (KSA)
j = 0
for i in 0..255:
    j = (j + S[i] + T[i]) mod 256
    swap(S[i], S[j])

# 3. Keystream generation (PRGA)
i = j = 0
repeat:
    i = (i + 1) mod 256
    j = (j + S[i]) mod 256
    swap(S[i], S[j])
    t = (S[i] + S[j]) mod 256
    output k = S[t]          # C = P XOR k

Worked example: first KSA steps, key [3, 1, 4]

i = 0: j = 0 + 0 + 3 = 3, swap S[0] and S[3] → S starts 3, 1, 2, 0. i = 1: j = 3 + 1 + 1 = 5, swap S[1] and S[5]. With the key “Key”, the first keystream byte is 0xEB, so plaintext ‘P’ (0x50) encrypts to 0xBB.

Weaknesses

  • Second-byte bias: the second output byte is 0 with probability about 2/256, twice the random rate; with many encryptions of the same plaintext this reveals plaintext bytes.
  • Early output bytes correlate with key bytes; WEP prepended a public 24-bit IV to the key and used the keystream from byte one, so tools recovered keys from captured traffic.
  • Dropping the first bytes (RC4-drop[768]) removes the worst early bias but not long-term biases; RC4 is now prohibited in TLS.
  • Restarting RC4 with the same key repeats the keystream (pad reuse).

RC4 chat lab

A relay server on TCP 8080 forwards bytes between two clients. The clients agree a shared secret with Diffie–Hellman (g = 3, p = 19), seed RC4 with it and encrypt locally, so the relay sees only ciphertext… until it brute-forces the tiny discrete log (see the Diffie–Hellman page). Wireshark, nmap and traceroute are used alongside to observe traffic, open ports and paths.

Common pitfalls

  • KSA uses T; PRGA does not.
  • The output is S[t], not t.
  • Increment i, update j and swap before computing the output.