2013-10-17 14:05:27 +00:00
|
|
|
#!/usr/bin/env python
|
2008-04-26 06:47:56 +00:00
|
|
|
|
2009-11-04 10:35:16 +00:00
|
|
|
""" Python implementation of Arcfour encryption algorithm.
|
2014-09-04 07:36:19 +00:00
|
|
|
See https://en.wikipedia.org/wiki/RC4
|
2009-11-04 10:35:16 +00:00
|
|
|
This code is in the public domain.
|
|
|
|
|
|
|
|
"""
|
2008-08-30 07:40:52 +00:00
|
|
|
|
2014-09-04 07:36:19 +00:00
|
|
|
import six # Python 2+3 compatibility
|
2008-08-30 07:40:52 +00:00
|
|
|
## Arcfour
|
|
|
|
##
|
2008-07-09 15:15:32 +00:00
|
|
|
class Arcfour(object):
|
2008-04-26 06:47:56 +00:00
|
|
|
|
2009-10-24 04:41:59 +00:00
|
|
|
def __init__(self, key):
|
2014-09-04 07:36:19 +00:00
|
|
|
s = [i for i in range(256)] #because Py3 range is not indexable
|
2009-10-24 04:41:59 +00:00
|
|
|
j = 0
|
|
|
|
klen = len(key)
|
2014-09-04 07:36:19 +00:00
|
|
|
for i in range(256):
|
|
|
|
j = (j + s[i] + six.indexbytes(key,i % klen)) % 256
|
2009-10-24 04:41:59 +00:00
|
|
|
(s[i], s[j]) = (s[j], s[i])
|
|
|
|
self.s = s
|
|
|
|
(self.i, self.j) = (0, 0)
|
|
|
|
return
|
|
|
|
|
|
|
|
def process(self, data):
|
|
|
|
(i, j) = (self.i, self.j)
|
|
|
|
s = self.s
|
2014-06-30 10:05:56 +00:00
|
|
|
r = b''
|
2014-09-04 07:36:19 +00:00
|
|
|
for c in six.iterbytes(data):
|
2009-10-24 04:41:59 +00:00
|
|
|
i = (i+1) % 256
|
|
|
|
j = (j+s[i]) % 256
|
|
|
|
(s[i], s[j]) = (s[j], s[i])
|
|
|
|
k = s[(s[i]+s[j]) % 256]
|
2014-09-04 07:36:19 +00:00
|
|
|
r += six.int2byte(c ^ k)
|
2009-10-24 04:41:59 +00:00
|
|
|
(self.i, self.j) = (i, j)
|
|
|
|
return r
|
2014-05-19 14:27:43 +00:00
|
|
|
|
|
|
|
encrypt = decrypt = process
|
|
|
|
|