.

RC4


Reading time: about 2 minutes

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

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()) # 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

The following pages link here

Citation

If you find this work useful, please cite it as:
@article{yaltirakli,
  title   = "RC4",
  author  = "Yaltirakli, Gokberk",
  journal = "gkbrk.com",
  year    = "2025",
  url     = "https://www.gkbrk.com/rc4"
}
Not using BibTeX? Click here for more citation styles.
IEEE Citation
Gokberk Yaltirakli, "RC4", February, 2025. [Online]. Available: https://www.gkbrk.com/rc4. [Accessed Feb. 04, 2025].
APA Style
Yaltirakli, G. (2025, February 04). RC4. https://www.gkbrk.com/rc4
Bluebook Style
Gokberk Yaltirakli, RC4, GKBRK.COM (Feb. 04, 2025), https://www.gkbrk.com/rc4

Comments

© 2025 Gokberk Yaltirakli