leo.blog();

RC4

RC4, also known as ARC4 or ARCFOUR, is a stream cipher.

State

RC4 keeps the following state when executing.

Python implementation

def rc4(key):
    key_len = len(key)
    s = list(range(256))
    
    j = 0
    for i in range(256):
        i &= 0xFF
        j = (j + s[i] + key[i % key_len]) & 0xFF
        
        # Swap s[i] and s[j]
        tmp = s[i]
        s[i] = s[j]
        s[j] = tmp

    i = 0
    j = 0
    while True:
        i = (i + 1) & 0xFF
        j = (j + s[i]) & 0xFF
        
        # Swap s[i] and s[j]
        tmp = s[i]
        s[i] = s[j]
        s[j] = tmp
        
        yield s[(s[i] + s[j]) & 0xFF]

import itertools

keystream = rc4(b"Secret")
buf = bytes(itertools.islice(keystream, 16))

print(buf.hex())
# Prints 04d46b053ca87b594172302aec9bb992

Leave a Comment