~/ learn/ comp-400/ cards/ Stream ciphers: RC4, ChaCha20, and the rule you must never break
1 of 8

Implement RC4 (key scheduling plus generation), print the first eight keystream bytes for a fixed key, and confirm that encrypting twice returns the plaintext.

Implement RC4 (key scheduling plus generation), print the first eight keystream bytes for a fixed key, and confirm that encrypting twice returns the plaintext.

Answer

def ksa(key): S = list(range(256)) j = 0 for i in range(256): j = (j + S[i] + key[i % len(key)]) % 256 S[i], S[j] = S[j], S[i] return S def prga(S, n): S = S[:] i = j = 0 out = [] for _ in range(n): i = (i + 1) % 256 j = (j + S[i]) % 256 S[i], S[j] = S[j], S[i] out.append(S[(S[i] + S[j]) % 256]) return bytes(out) def rc4(key, data): return bytes(a ^ b for a, b in zip(data, prga(ksa(key), len(data)))) KEY = b'COMP400' MSG = b'keystream' print('first 8 keystream bytes:', prga(ksa(KEY), 8).hex()) CT = rc4(KEY, MSG) print('ciphertext:', CT.hex()) print('round trip:', rc4(KEY, CT).decode()) print('matches:', rc4(KEY, CT) == MSG)

SB5e ch2 §2.1; ch20 §20.4; RFC 8439 (ChaCha20-Poly1305); RFC 7465 (prohibiting RC4 in TLS)

space flip · ← → navigate · esc to exit
NORMAL ~/memra/library/31a8ab80-f928-42df-b3a6-a0143a594089/flashcard utf-8 LF