/gdata/tlslite/utils/Python_AES.py

http://radioappz.googlecode.com/ · Python · 68 lines · 39 code · 19 blank · 10 comment · 5 complexity · 2c7c0593f758339061ed74645de5eaee MD5 · raw file

  1. """Pure-Python AES implementation."""
  2. from cryptomath import *
  3. from AES import *
  4. from rijndael import rijndael
  5. def new(key, mode, IV):
  6. return Python_AES(key, mode, IV)
  7. class Python_AES(AES):
  8. def __init__(self, key, mode, IV):
  9. AES.__init__(self, key, mode, IV, "python")
  10. self.rijndael = rijndael(key, 16)
  11. self.IV = IV
  12. def encrypt(self, plaintext):
  13. AES.encrypt(self, plaintext)
  14. plaintextBytes = stringToBytes(plaintext)
  15. chainBytes = stringToBytes(self.IV)
  16. #CBC Mode: For each block...
  17. for x in range(len(plaintextBytes)/16):
  18. #XOR with the chaining block
  19. blockBytes = plaintextBytes[x*16 : (x*16)+16]
  20. for y in range(16):
  21. blockBytes[y] ^= chainBytes[y]
  22. blockString = bytesToString(blockBytes)
  23. #Encrypt it
  24. encryptedBytes = stringToBytes(self.rijndael.encrypt(blockString))
  25. #Overwrite the input with the output
  26. for y in range(16):
  27. plaintextBytes[(x*16)+y] = encryptedBytes[y]
  28. #Set the next chaining block
  29. chainBytes = encryptedBytes
  30. self.IV = bytesToString(chainBytes)
  31. return bytesToString(plaintextBytes)
  32. def decrypt(self, ciphertext):
  33. AES.decrypt(self, ciphertext)
  34. ciphertextBytes = stringToBytes(ciphertext)
  35. chainBytes = stringToBytes(self.IV)
  36. #CBC Mode: For each block...
  37. for x in range(len(ciphertextBytes)/16):
  38. #Decrypt it
  39. blockBytes = ciphertextBytes[x*16 : (x*16)+16]
  40. blockString = bytesToString(blockBytes)
  41. decryptedBytes = stringToBytes(self.rijndael.decrypt(blockString))
  42. #XOR with the chaining block and overwrite the input with output
  43. for y in range(16):
  44. decryptedBytes[y] ^= chainBytes[y]
  45. ciphertextBytes[(x*16)+y] = decryptedBytes[y]
  46. #Set the next chaining block
  47. chainBytes = blockBytes
  48. self.IV = bytesToString(chainBytes)
  49. return bytesToString(ciphertextBytes)