Skip to content

Instantly share code, notes, and snippets.

@dsandler
Created January 25, 2019 04:48
Show Gist options
  • Save dsandler/4979f79964fcb7423da91ade686d70b6 to your computer and use it in GitHub Desktop.
Save dsandler/4979f79964fcb7423da91ade686d70b6 to your computer and use it in GitHub Desktop.
# https://en.wikipedia.org/wiki/RC4
# dsandler 2019
class cipher(object):
S = None
def __init__(this, key):
this.key = key
this.reset()
def reset(this):
key = [ord(x) for x in this.key]
keylen = len(key)
this.S = range(256)
S = this.S
j = 0
for i in range(256):
j = (j + S[i] + key[i % keylen]) % 256
S[i], S[j] = S[j], S[i]
this.keystream = this.start_keystream()
def start_keystream(this):
S = this.S
i = 0
j = 0
while True:
i = (i + 1) % 256
j = (j + S[i]) % 256
S[i], S[j] = S[j], S[i]
yield S[(S[i] + S[j]) % 256]
def code(this, plain):
return (chr(ord(b) ^ this.keystream.next()) for b in plain)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment