Skip to content

Instantly share code, notes, and snippets.

@e000
Created March 3, 2011 01:53
Show Gist options
  • Select an option

  • Save e000/852168 to your computer and use it in GitHub Desktop.

Select an option

Save e000/852168 to your computer and use it in GitHub Desktop.
nice rc4
class RC4:
def __init__(self, key):
self._key, x, box, kl = key, 0, range(256), len(key)
for i in xrange(256):
x = (x + box[i] + ord(key[i % kl])) & 0xff
box[i], box[x] = box[x], box[i]
self._box = box
def crypt(self, data):
box, x, y, out = self._box[:], 0, 0, []
a = out.append
for char in data:
x = (x + 1) & 0xff
r = box[x]
y = (y + r) & 0xff
r, j = box[x], box[y] = box[y], r
a(chr(ord(char) ^ box[(r + j) & 0xff]))
return ''.join(out)
__call__ = crypt
import unittest
class RC4UnitTest(unittest.TestCase):
def setUp(self):
self.crypto = RC4('thisIsMyKey')
def test_crypto(self):
self.assertEqual(self.crypto('foobar'), '\x07\x9ci\xd2\xc3i')
self.assertEqual(self.crypto('thhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhh'),
'\x15\x9bn\xd8\xcase\x0f7L\x8dFrjS\xb2:\x95o6\x8aN#\xed(\xa1\xe4\xcdQ.c\xad\x8b\x0e\xb6x>\xde\xc6\x14)W\x9f\xff\xe5S\xc4\xfapC\x9d\xa6\xed')
if __name__ == '__main__':
unittest.main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment