Skip to content

Instantly share code, notes, and snippets.

/rc4.py Secret

Created July 29, 2017 17:57
Show Gist options
  • Save anonymous/bf4931559758f9ada33077fe773eb6e6 to your computer and use it in GitHub Desktop.
Save anonymous/bf4931559758f9ada33077fe773eb6e6 to your computer and use it in GitHub Desktop.
from binascii import hexlify, unhexlify
from hexdump import hexdump
def rotate(l, n):
return l[-n:] + l[:-n]
def convert_key(s):
return [ord(c) for c in s]
def KSA(key, rot):
keylength = len(key)
S = rotate(range(256), rot)
j = 0
for i in range(256):
j = (j + S[i] + key[i % keylength]) % 256
S[i], S[j] = S[j], S[i] # swap
return S
def PRGA(S):
i = 0
j = 0
while True:
i = (i + 1) % 256
j = (j + S[i]) % 256
S[i], S[j] = S[j], S[i] # swap
K = S[(S[i] + S[j]) % 256]
yield K
def RC4(key, rot):
S = KSA(key, rot)
return PRGA(S)
if __name__ == '__main__':
# test vectors are from http://en.wikipedia.org/wiki/RC4
# ciphertext should be BBF316E8D940AF0AD3
#key = 'Key'
#plaintext = 'Plaintext'
key = '4b6579'.decode('hex')
plaintext = '506c61696e74657874'.decode('hex')
print key, plaintext
# encrypt
key = convert_key(key)
keystream = RC4(key, 0)
output = ''
for c in plaintext:
char = ord(c) ^ keystream.next()
output += "%02X" % char
print 'verifying encryption. output should be BBF316E8D940AF0AD3'
hexdump(unhexlify(output))
print
# decrypt
keystream = RC4(key, 0)
ciphertext = 'BBF316E8D940AF0AD3'.decode('hex')
output = ''
for c in ciphertext:
char = ord(c) ^ keystream.next()
output += "%02X" % char
print 'verifying decryption. output should be Plaintext'
hexdump(unhexlify(output))
print
key = 'C28222B7B746D25A8F180FFCFADCFF11'.decode('hex')
msg = '6cd022c2da6dc500105a9274cab92177177527d683fad205fb002071d7931f67170a90080f92'.decode('hex')
key = convert_key(key)
for i in range(256):
keystream = RC4(key, i)
output = ''
for c in msg:
char = ord(c) ^ keystream.next()
output += "%02X" % char
print 'offset: %d' % i
hexdump(unhexlify(output))
print
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment