6. Stream Ciphers

Generating an endless river of pseudorandom keystream

Block ciphers like AES operate on fixed 16-byte chunks. That's fine for many things, but sometimes you want to encrypt a continuous stream of data — a live video feed, a VPN tunnel, a WebSocket connection — byte by byte, as it arrives. That's what stream ciphers are for.

A stream cipher generates a long pseudorandom keystream from a short key and XORs it directly with the plaintext. If you've read the XOR and One-Time Pad article, this is exactly the stream cipher concept introduced there — a short key expanded into a message-length keystream to approximate the perfect secrecy of a true OTP.

How Stream Ciphers Work

The fundamental operation is simple:

Stream cipher encryption and decryption

Key + Nonce
    │
    ▼
┌─────────────────────┐
│  Keystream Generator │──→ k₀ k₁ k₂ k₃ k₄ k₅ k₆ k₇ ...
└─────────────────────┘
                              ⊕  ⊕  ⊕  ⊕  ⊕  ⊕  ⊕  ⊕
Plaintext:                    p₀ p₁ p₂ p₃ p₄ p₅ p₆ p₇ ...
                              │  │  │  │  │  │  │  │
Ciphertext:                   c₀ c₁ c₂ c₃ c₄ c₅ c₆ c₇ ...

Decryption: regenerate the same keystream, XOR again. Identical operation.

The nonce (number used once) is a public value that ensures two messages encrypted with the same key produce completely different keystreams. Think of the key as the long-term secret and the nonce as the per-message randomness.

XOR Is Self-Inverse

Because XOR is its own inverse, encryption and decryption are the same operation. Generate the keystream, XOR with the data. To decrypt, generate the exact same keystream and XOR again. There is no separate decryption algorithm.

RC4 — A Cautionary Tale

RC4 (1987, Ron Rivest) was the dominant stream cipher for two decades. It was used in WEP Wi-Fi encryption, early SSL/TLS, and countless other protocols. Its design is elegantly simple: maintain a 256-byte permutation array, and step through it to generate keystream bytes.

RC4 key scheduling (simplified)

// Initialize permutation
S = [0, 1, 2, ..., 255]

// Scramble with key j = 0 for i in 0..255: j = (j + S[i] + key[i mod key_length]) mod 256 swap(S[i], S[j])

// Generate keystream i = 0, j = 0 loop: i = (i + 1) mod 256 j = (j + S[i]) mod 256 swap(S[i], S[j]) yield S[(S[i] + S[j]) mod 256]

It's compact — RC4 was famously implementable in about a dozen lines of C. But the simplicity masked serious flaws:

  • The first few hundred bytes of the keystream are statistically biased — the key scheduling algorithm doesn't mix the state well enough at the start
  • Related-key attacks: using RC4 with keys that differ only slightly (like WEP's IV construction) lets an attacker recover the key. This was the attack that broke WEP entirely
  • The Fluhrer–Mantin–Shamir attack (2001) extracted WEP keys from about one million packets
  • Further analysis revealed biases throughout the keystream, not just at the start

RC4 was banned from TLS in 2015 (RFC 7465) and should not be used for any new system. It lives on as a lesson in how statistical biases in a keystream can be catastrophically exploited.

ChaCha20 — The Modern Standard

ChaCha20 was designed by Daniel J. Bernstein in 2008 as a faster, more secure alternative to RC4 and earlier stream ciphers. It's now one of the two dominant stream ciphers in production (alongside AES in CTR mode), and for environments without AES hardware acceleration it's often the better choice.

The State Matrix

ChaCha20 operates on a 4×4 matrix of 32-bit words — 16 words, 512 bits total. Each block of keystream starts from this state:

ChaCha20 initial state (4×4 matrix of 32-bit words)

┌──────────┬──────────┬──────────┬──────────┐
│ constant │ constant │ constant │ constant │  ← "expa nd 32" as 4 little-endian words
│ key[0]   │ key[1]   │ key[2]   │ key[3]   │  ← 256-bit key, words 0–3
│ key[4]   │ key[5]   │ key[6]   │ key[7]   │  ← 256-bit key, words 4–7
│ counter  │ nonce[0] │ nonce[1] │ nonce[2] │  ← 32-bit counter + 96-bit nonce
└──────────┴──────────┴──────────┴──────────┘

Total state: 16 × 32-bit words = 512 bits = 64 bytes per block

The four constant words spell out "expa nd 3 2-by te k" — a "nothing up my sleeve" magic value showing the constants weren't chosen adversarially. The 256-bit key fills the next eight words. The counter starts at zero and increments for each 64-byte block, giving you a maximum keystream of 256 GB per nonce.

The Quarter-Round

Every bit of security in ChaCha20 comes from one primitive: the quarter-round. It takes four 32-bit words and mixes them with adds, XORs, and rotates — operations that are fast on any processor and have no secret-dependent memory accesses.

The quarter-round: QR(a, b, c, d)

a += b;  d ^= a;  d <<<= 16;
c += d;  b ^= c;  b <<<= 12;
a += b;  d ^= a;  d <<<= 8;
c += d;  b ^= c;  b <<<= 7;

All operations are mod 2³². The <<< symbol means rotate left (not shift).

Each full ChaCha20 round applies eight quarter-rounds — four to the columns, then four to the diagonals of the 4×4 state. This is one double round:

Column rounds then diagonal rounds

Column rounds:
  QR(state[0], state[4], state[ 8], state[12])   // column 0
  QR(state[1], state[5], state[ 9], state[13])   // column 1
  QR(state[2], state[6], state[10], state[14])   // column 2
  QR(state[3], state[7], state[11], state[15])   // column 3

Diagonal rounds: QR(state[0], state[5], state[10], state[15]) // main diagonal QR(state[1], state[6], state[11], state[12]) // diagonal QR(state[2], state[7], state[ 8], state[13]) // diagonal QR(state[3], state[4], state[ 9], state[14]) // diagonal

ChaCha20 runs 20 rounds = 10 double rounds.

After 20 rounds, the scrambled state is added back to the original state word-by-word. That final addition is what makes ChaCha20 a pseudorandom function rather than just a permutation — you can't reverse it to recover the key from a keystream block.

  1. Initialize the 4×4 state

    Fill in the four constants, the 256-bit key, the 32-bit block counter, and the 96-bit nonce.

  2. Run 20 rounds of quarter-rounds

    Alternate between column rounds and diagonal rounds, 10 times each. Every word influences every other word multiple times.

  3. Add the original state

    Add the pre-round state back to the post-round state, word by word. Serialize the 16 words as 64 bytes of keystream.

  4. Increment the counter and repeat

    Increment the counter by 1, generate the next 64-byte block. Repeat until you have enough keystream to cover the entire message.

  5. XOR with plaintext

    XOR the keystream bytes with the plaintext bytes. Truncate the last keystream block to match the message length.

Why ChaCha20 Won

ChaCha20 has largely displaced RC4 and competes with AES-CTR on equal footing. Three reasons explain the adoption:

Constant-time by design. ChaCha20 uses only adds, XORs, and rotations. No table lookups, no conditional branches on secret data. This eliminates the entire class of timing side-channel attacks that have plagued AES implementations without hardware support (AES cache-timing attacks).

Fast in software. Without AES-NI hardware instructions, software AES is slow — eight table lookups per round, with cache pressure. ChaCha20 is pure arithmetic. On most CPUs without AES-NI (older phones, embedded systems, ARM microcontrollers) ChaCha20 is significantly faster.

Wide adoption. Google chose ChaCha20-Poly1305 for QUIC and Chrome's HTTPS connections to Android devices. WireGuard uses it for all data encryption. It's a mandatory cipher suite in TLS 1.3. If you're building a protocol today, it's a first-class choice.

AES-GCM preferred when...

AES-NI hardware instructions are available (most modern x86 CPUs). Hardware-accelerated AES is faster than ChaCha20 and has comparable security.

ChaCha20-Poly1305 preferred when...

No AES hardware support (mobile, embedded). Constant-time is required by policy. Side-channel resistance must be guaranteed even in hostile environments.

The Nonce Reuse Catastrophe

Stream ciphers have one absolute rule: never reuse a (key, nonce) pair. The consequences are severe enough that the attack has a name — two-time pad — echoing the broken one-time pad.

What happens when you reuse a nonce

Alice encrypts with (key K, nonce N):
  C₁ = P₁ ⊕ keystream(K, N)
  C₂ = P₂ ⊕ keystream(K, N)   ← same key, same nonce!

An attacker observes both ciphertexts and XORs them: C₁ ⊕ C₂ = (P₁ ⊕ keystream) ⊕ (P₂ ⊕ keystream) = P₁ ⊕ P₂

The keystream cancels out completely. The attacker now has the XOR of two plaintexts — and if one is known (or guessable), the other is immediately recovered.

Nonce Reuse Is Fatal

This is the same vulnerability that broke WEP (RC4 with predictable IVs) and the same reason OTP reuse is catastrophic. With enough messages and known plaintext, XOR-of-plaintexts can be deciphered using frequency analysis and crib-dragging — the same techniques that broke the Vigenere cipher centuries ago.

Recovery attack in practice

If P₁ contains "the " at offset 0 (common English), the attacker guesses:
  P₁ ⊕ P₂ ⊕ "the " → candidate for P₂ at offset 0

Confirmed if the candidate reads as valid English/data. The attacker "drags" known cribs across C₁ ⊕ C₂ to recover both messages.

This works even with zero knowledge of the key.

How do you avoid nonce reuse? Several strategies:

Strategy How it works
Random nonce 96 bits of random data — collision probability is negligible for up to ~2³² messages
Counter nonce Increment a per-connection counter — guaranteed unique, requires stateful tracking
XSalsa20/XChaCha20 Extended nonce variants (192-bit nonce) — large enough that random nonces are safe even at huge scale

Stream vs Block: When to Use Which

Property Stream cipher (ChaCha20) Block cipher + mode (AES-GCM)
Granularity Byte-by-byte 16-byte blocks
Padding needed No Only CBC; CTR/GCM: no
Parallelizable Yes (arbitrary seek) Yes (CTR/GCM)
Random access Yes — seek to any position Yes (CTR/GCM)
HW acceleration No (software is fast anyway) Yes (AES-NI)
Side-channel risk Low — no table lookups Requires care without AES-NI
Authentication Needs Poly1305 (ChaCha20-Poly1305) Needs GHASH (AES-GCM)

Real-World Deployments

System Algorithm Role
WireGuard ChaCha20-Poly1305 All data encryption
TLS 1.3 ChaCha20-Poly1305 or AES-GCM Mandatory cipher suites
OpenSSH ChaCha20-Poly1305 Default cipher on modern clients
QUIC (HTTP/3) ChaCha20-Poly1305 or AES-GCM Packet encryption
Noise Protocol ChaCha20-Poly1305 Used by WhatsApp, WireGuard handshake
Android HTTPS ChaCha20-Poly1305 Preferred on devices without AES-NI

Notice a pattern: ChaCha20 never appears alone. It's always paired with Poly1305, a message authentication code. Stream ciphers provide confidentiality — they don't protect against tampering. That's why the real-world cipher suite is always ChaCha20-Poly1305. We'll look at exactly how that works in the next article on authenticated encryption.

ChaCha20 Keystream Explorer

Enter a key and nonce below to initialize the ChaCha20 state matrix. Step through the quarter-rounds and watch how every word in the state changes. The final keystream bytes are shown after all 20 rounds complete.

State Matrix

Keystream Output

Nonce Reuse Attack

This demo shows what happens when you reuse a (key, nonce) pair. Encrypt two messages with the same key and nonce, then XOR the ciphertexts together. The keystream cancels out, leaving the XOR of the two plaintexts — and from there, with even partial knowledge of one message, you can recover the other.

Key Takeaways

  • Stream ciphers expand a short key into a long pseudorandom keystream, then XOR with the plaintext
  • RC4 was the dominant stream cipher for 20 years but is now broken — biased keystream bytes enabled practical attacks on WEP and TLS
  • ChaCha20 uses a 4×4 state matrix, a 256-bit key, a 96-bit nonce, and 20 rounds of the quarter-round operation (adds, XORs, rotates)
  • ChaCha20 is constant-time by design — no table lookups means no timing side channels, making it safer than AES in software on hardware without AES-NI
  • Nonce reuse is catastrophic — XORing two ciphertexts produced from the same (key, nonce) eliminates the keystream and exposes the XOR of the plaintexts
  • ChaCha20 alone provides confidentiality but not integrity — real protocols always pair it with Poly1305 to form ChaCha20-Poly1305
  • ChaCha20-Poly1305 is a mandatory cipher suite in TLS 1.3 and the default in WireGuard, OpenSSH, and the Noise Protocol

ChaCha20 solves confidentiality beautifully — but confidentiality alone isn't enough. An attacker who can't read your data can still flip bits in your ciphertext and predictably corrupt the plaintext, all without knowing the key. Encryption without authentication is a vulnerability waiting to be exploited. The solution is authenticated encryption with associated data (AEAD) — and ChaCha20-Poly1305 is one of the two canonical AEAD constructions used everywhere from TLS 1.3 to WireGuard.