File: arcfour.py

package info (click to toggle)
python-pattern 2.6%2Bgit20150109-3
  • links: PTS, VCS
  • area: main
  • in suites: buster
  • size: 78,672 kB
  • sloc: python: 53,865; xml: 11,965; ansic: 2,318; makefile: 94
file content (49 lines) | stat: -rw-r--r-- 1,136 bytes parent folder | download | duplicates (3)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
#!/usr/bin/env python2

""" Python implementation of Arcfour encryption algorithm.

This code is in the public domain.

"""

##  Arcfour
##
class Arcfour(object):

    """
    >>> Arcfour('Key').process('Plaintext').encode('hex')
    'bbf316e8d940af0ad3'
    >>> Arcfour('Wiki').process('pedia').encode('hex')
    '1021bf0420'
    >>> Arcfour('Secret').process('Attack at dawn').encode('hex')
    '45a01f645fc35b383552544b9bf5'
    """

    def __init__(self, key):
        s = range(256)
        j = 0
        klen = len(key)
        for i in xrange(256):
            j = (j + s[i] + ord(key[i % klen])) % 256
            (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
        r = ''
        for c in data:
            i = (i+1) % 256
            j = (j+s[i]) % 256
            (s[i], s[j]) = (s[j], s[i])
            k = s[(s[i]+s[j]) % 256]
            r += chr(ord(c) ^ k)
        (self.i, self.j) = (i, j)
        return r

# test
if __name__ == '__main__':
    import doctest
    doctest.testmod()