| OLD | NEW |
| 1 # Author: Trevor Perrin |
| 2 # See the LICENSE file for legal information regarding use of this file. |
| 3 |
| 1 """Pure-Python RC4 implementation.""" | 4 """Pure-Python RC4 implementation.""" |
| 2 | 5 |
| 3 from rc4 import RC4 | 6 from .rc4 import RC4 |
| 4 from cryptomath import * | 7 from .cryptomath import * |
| 5 | 8 |
| 6 def new(key): | 9 def new(key): |
| 7 return Python_RC4(key) | 10 return Python_RC4(key) |
| 8 | 11 |
| 9 class Python_RC4(RC4): | 12 class Python_RC4(RC4): |
| 10 def __init__(self, key): | 13 def __init__(self, keyBytes): |
| 11 RC4.__init__(self, key, "python") | 14 RC4.__init__(self, keyBytes, "python") |
| 12 keyBytes = stringToBytes(key) | |
| 13 S = [i for i in range(256)] | 15 S = [i for i in range(256)] |
| 14 j = 0 | 16 j = 0 |
| 15 for i in range(256): | 17 for i in range(256): |
| 16 j = (j + S[i] + keyBytes[i % len(keyBytes)]) % 256 | 18 j = (j + S[i] + keyBytes[i % len(keyBytes)]) % 256 |
| 17 S[i], S[j] = S[j], S[i] | 19 S[i], S[j] = S[j], S[i] |
| 18 | 20 |
| 19 self.S = S | 21 self.S = S |
| 20 self.i = 0 | 22 self.i = 0 |
| 21 self.j = 0 | 23 self.j = 0 |
| 22 | 24 |
| 23 def encrypt(self, plaintext): | 25 def encrypt(self, plaintextBytes): |
| 24 plaintextBytes = stringToBytes(plaintext) | 26 ciphertextBytes = plaintextBytes[:] |
| 25 S = self.S | 27 S = self.S |
| 26 i = self.i | 28 i = self.i |
| 27 j = self.j | 29 j = self.j |
| 28 for x in range(len(plaintextBytes)): | 30 for x in range(len(ciphertextBytes)): |
| 29 i = (i + 1) % 256 | 31 i = (i + 1) % 256 |
| 30 j = (j + S[i]) % 256 | 32 j = (j + S[i]) % 256 |
| 31 S[i], S[j] = S[j], S[i] | 33 S[i], S[j] = S[j], S[i] |
| 32 t = (S[i] + S[j]) % 256 | 34 t = (S[i] + S[j]) % 256 |
| 33 plaintextBytes[x] ^= S[t] | 35 ciphertextBytes[x] ^= S[t] |
| 34 self.i = i | 36 self.i = i |
| 35 self.j = j | 37 self.j = j |
| 36 return bytesToString(plaintextBytes) | 38 return ciphertextBytes |
| 37 | 39 |
| 38 def decrypt(self, ciphertext): | 40 def decrypt(self, ciphertext): |
| 39 return self.encrypt(ciphertext) | 41 return self.encrypt(ciphertext) |
| OLD | NEW |