/gdata/tlslite/utils/Python_RC4.py

http://radioappz.googlecode.com/ · Python · 39 lines · 32 code · 6 blank · 1 comment · 3 complexity · 6131ab9c69edb2989f80cd67b95847ca MD5 · raw file

  1. """Pure-Python RC4 implementation."""
  2. from RC4 import RC4
  3. from cryptomath import *
  4. def new(key):
  5. return Python_RC4(key)
  6. class Python_RC4(RC4):
  7. def __init__(self, key):
  8. RC4.__init__(self, key, "python")
  9. keyBytes = stringToBytes(key)
  10. S = [i for i in range(256)]
  11. j = 0
  12. for i in range(256):
  13. j = (j + S[i] + keyBytes[i % len(keyBytes)]) % 256
  14. S[i], S[j] = S[j], S[i]
  15. self.S = S
  16. self.i = 0
  17. self.j = 0
  18. def encrypt(self, plaintext):
  19. plaintextBytes = stringToBytes(plaintext)
  20. S = self.S
  21. i = self.i
  22. j = self.j
  23. for x in range(len(plaintextBytes)):
  24. i = (i + 1) % 256
  25. j = (j + S[i]) % 256
  26. S[i], S[j] = S[j], S[i]
  27. t = (S[i] + S[j]) % 256
  28. plaintextBytes[x] ^= S[t]
  29. self.i = i
  30. self.j = j
  31. return bytesToString(plaintextBytes)
  32. def decrypt(self, ciphertext):
  33. return self.encrypt(ciphertext)