/gdata/tlslite/utils/OpenSSL_TripleDES.py

http://radioappz.googlecode.com/ · Python · 44 lines · 30 code · 9 blank · 5 comment · 1 complexity · 0ad5778e742f9a39ff29ff4e72624da1 MD5 · raw file

  1. """OpenSSL/M2Crypto 3DES implementation."""
  2. from cryptomath import *
  3. from TripleDES import *
  4. if m2cryptoLoaded:
  5. def new(key, mode, IV):
  6. return OpenSSL_TripleDES(key, mode, IV)
  7. class OpenSSL_TripleDES(TripleDES):
  8. def __init__(self, key, mode, IV):
  9. TripleDES.__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. cipherType = m2.des_ede3_cbc()
  15. m2.cipher_init(context, cipherType, self.key, self.IV, encrypt)
  16. return context
  17. def encrypt(self, plaintext):
  18. TripleDES.encrypt(self, plaintext)
  19. context = self._createContext(1)
  20. ciphertext = m2.cipher_update(context, plaintext)
  21. m2.cipher_ctx_free(context)
  22. self.IV = ciphertext[-self.block_size:]
  23. return ciphertext
  24. def decrypt(self, ciphertext):
  25. TripleDES.decrypt(self, ciphertext)
  26. context = self._createContext(0)
  27. #I think M2Crypto has a bug - it fails to decrypt and return the last block passed in.
  28. #To work around this, we append sixteen zeros to the string, below:
  29. plaintext = m2.cipher_update(context, ciphertext+('\0'*16))
  30. #If this bug is ever fixed, then plaintext will end up having a garbage
  31. #plaintext block on the end. That's okay - the below code will ignore it.
  32. plaintext = plaintext[:len(ciphertext)]
  33. m2.cipher_ctx_free(context)
  34. self.IV = ciphertext[-self.block_size:]
  35. return plaintext