/gdata/tlslite/utils/OpenSSL_AES.py

http://radioappz.googlecode.com/ · Python · 49 lines · 35 code · 9 blank · 5 comment · 4 complexity · 5aad68d3439f0f4d417099b0bc48e1a0 MD5 · raw file

  1. """OpenSSL/M2Crypto AES implementation."""
  2. from cryptomath import *
  3. from AES import *
  4. if m2cryptoLoaded:
  5. def new(key, mode, IV):
  6. return OpenSSL_AES(key, mode, IV)
  7. class OpenSSL_AES(AES):
  8. def __init__(self, key, mode, IV):
  9. AES.__init__(self, key, mode, IV, "openssl")
  10. self.key = key
  11. self.IV = IV
  12. def _createContext(self, encrypt):
  13. context = m2.cipher_ctx_new()
  14. if len(self.key)==16:
  15. cipherType = m2.aes_128_cbc()
  16. if len(self.key)==24:
  17. cipherType = m2.aes_192_cbc()
  18. if len(self.key)==32:
  19. cipherType = m2.aes_256_cbc()
  20. m2.cipher_init(context, cipherType, self.key, self.IV, encrypt)
  21. return context
  22. def encrypt(self, plaintext):
  23. AES.encrypt(self, plaintext)
  24. context = self._createContext(1)
  25. ciphertext = m2.cipher_update(context, plaintext)
  26. m2.cipher_ctx_free(context)
  27. self.IV = ciphertext[-self.block_size:]
  28. return ciphertext
  29. def decrypt(self, ciphertext):
  30. AES.decrypt(self, ciphertext)
  31. context = self._createContext(0)
  32. #I think M2Crypto has a bug - it fails to decrypt and return the last block passed in.
  33. #To work around this, we append sixteen zeros to the string, below:
  34. plaintext = m2.cipher_update(context, ciphertext+('\0'*16))
  35. #If this bug is ever fixed, then plaintext will end up having a garbage
  36. #plaintext block on the end. That's okay - the below code will discard it.
  37. plaintext = plaintext[:len(ciphertext)]
  38. m2.cipher_ctx_free(context)
  39. self.IV = ciphertext[-self.block_size:]
  40. return plaintext