PageRenderTime 5ms CodeModel.GetById 1ms app.highlight 3ms RepoModel.GetById 1ms app.codeStats 0ms

/gdata/tlslite/utils/Python_RC4.py

http://radioappz.googlecode.com/
Python | 39 lines | 32 code | 6 blank | 1 comment | 6 complexity | 6131ab9c69edb2989f80cd67b95847ca MD5 | raw file
 1"""Pure-Python RC4 implementation."""
 2
 3from RC4 import RC4
 4from cryptomath import *
 5
 6def new(key):
 7    return Python_RC4(key)
 8
 9class Python_RC4(RC4):
10    def __init__(self, key):
11        RC4.__init__(self, key, "python")
12        keyBytes = stringToBytes(key)
13        S = [i for i in range(256)]
14        j = 0
15        for i in range(256):
16            j = (j + S[i] + keyBytes[i % len(keyBytes)]) % 256
17            S[i], S[j] = S[j], S[i]
18
19        self.S = S
20        self.i = 0
21        self.j = 0
22
23    def encrypt(self, plaintext):
24        plaintextBytes = stringToBytes(plaintext)
25        S = self.S
26        i = self.i
27        j = self.j
28        for x in range(len(plaintextBytes)):
29            i = (i + 1) % 256
30            j = (j + S[i]) % 256
31            S[i], S[j] = S[j], S[i]
32            t = (S[i] + S[j]) % 256
33            plaintextBytes[x] ^= S[t]
34        self.i = i
35        self.j = j
36        return bytesToString(plaintextBytes)
37
38    def decrypt(self, ciphertext):
39        return self.encrypt(ciphertext)