Understand and use stream ciphers correctly
Stream ciphers encrypt byte-by-byte using a keystream, offering speed and no padding. Learn correct nonce handling and the fatal mistake of nonce reuse.
- 1
A stream cipher generates a pseudorandom keystream and XORs it with the plaintext. The ciphertext is exactly the same length as the plaintext — no padding needed. The critical rule: never reuse a (key, nonce) pair, or the XOR of two ciphertexts reveals the XOR of two plaintexts.
- 2 RC4 Encryptor →
Encrypt a short message to see the stream cipher property: ciphertext length equals plaintext length. Observe how the output changes completely with a different key.
- 3 RC4 Encryptor →
Encrypt a second message with the SAME key to demonstrate the nonce-reuse catastrophe. XOR the two ciphertexts — the keystream cancels and you get the XOR of the two plaintexts, leaking structural information.
- 4
Modern stream ciphers (ChaCha20, AES-CTR, AES-GCM) use an explicit nonce to vary the keystream per message. Generate a fresh nonce for every encryption — never hardcode it, never reuse it. Use authenticated encryption (AEAD) to detect tampering.
Frequently asked questions
- Why is nonce reuse catastrophic?
- If two messages are encrypted with the same key and nonce, C1 XOR C2 = P1 XOR P2. The keystream cancels out. An attacker who guesses one plaintext recovers the other. This broke WPA2 (KRACK attack).
- Stream cipher vs block cipher — which to use?
- Use AES-GCM (a block cipher in AEAD mode) in most cases. Use ChaCha20-Poly1305 on devices without AES hardware. Never use a raw stream cipher without authentication.
Workflows that solve this
Learn more
Want to understand why?