tlslite.utils.python_rc4

Package tlslite :: Package utils :: Module python_rc4 |
[hide private]
[frames] | no frames]

# Source Code for Module tlslite.utils.python_rc4

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