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
|
|
|
|
2019-12-29 20:20:20 +00:00
|
|
|
|
2020-01-04 15:47:07 +00:00
|
|
|
class Arcfour:
|
2008-04-26 06:47:56 +00:00
|
|
|
|
2009-10-24 04:41:59 +00:00
|
|
|
def __init__(self, key):
|
2019-12-29 20:20:20 +00:00
|
|
|
# because Py3 range is not indexable
|
|
|
|
s = [i for i in range(256)]
|
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):
|
2020-01-04 15:47:07 +00:00
|
|
|
j = (j + s[i] + 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''
|
2020-01-04 15:47:07 +00:00
|
|
|
for c in iter(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]
|
2020-01-04 15:47:07 +00:00
|
|
|
r += bytes((c ^ k,))
|
2009-10-24 04:41:59 +00:00
|
|
|
(self.i, self.j) = (i, j)
|
|
|
|
return r
|
2019-12-29 20:20:20 +00:00
|
|
|
|
2014-05-19 14:27:43 +00:00
|
|
|
encrypt = decrypt = process
|
|
|
|
|
2019-12-29 20:20:20 +00:00
|
|
|
|
2014-09-07 16:38:22 +00:00
|
|
|
new = Arcfour
|