- add sources.
[platform/framework/web/crosswalk.git] / src / third_party / tlslite / tlslite / utils / Python_RC4.py
1 """Pure-Python RC4 implementation."""
2
3 from RC4 import RC4
4 from cryptomath import *
5
6 def new(key):
7     return Python_RC4(key)
8
9 class 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)