tlslite.utils.openssl_tripledes

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

# Source Code for Module tlslite.utils.openssl_tripledes

     1  # Author: Trevor Perrin
     2  # See the LICENSE file for legal information regarding use of this file.
     3
     4  """OpenSSL/M2Crypto 3DES implementation."""
     5
     6  from .cryptomath import *
     7  from .tripledes import *
     8
     9  if m2cryptoLoaded:
    10
    11 -    def new(key, mode, IV):
    12          return OpenSSL_TripleDES(key, mode, IV)
    13
    14 -    class OpenSSL_TripleDES(TripleDES):
    15
    16 -        def __init__(self, key, mode, IV):
    17              TripleDES.__init__(self, key, mode, IV, "openssl")
    18              self.key = key
    19              self.IV = IV
    20
    21 -        def _createContext(self, encrypt):
    22              context = m2.cipher_ctx_new()
    23              cipherType = m2.des_ede3_cbc()
    24              m2.cipher_init(context, cipherType, self.key, self.IV, encrypt)
    25              return context
    26
    27 -        def encrypt(self, plaintext):
    28              TripleDES.encrypt(self, plaintext)
    29              context = self._createContext(1)
    30              ciphertext = m2.cipher_update(context, plaintext)
    31              m2.cipher_ctx_free(context)
    32              self.IV = ciphertext[-self.block_size:]
    33              return bytearray(ciphertext)
    34
    35 -        def decrypt(self, ciphertext):
    36              TripleDES.decrypt(self, ciphertext)
    37              context = self._createContext(0)
    38              #I think M2Crypto has a bug - it fails to decrypt and return the last block passed in.
    39              #To work around this, we append sixteen zeros to the string, below:
    40              plaintext = m2.cipher_update(context, ciphertext+('\0'*16))
    41
    42              #If this bug is ever fixed, then plaintext will end up having a garbage
    43              #plaintext block on the end.  That's okay - the below code will ignore it.
    44              plaintext = plaintext[:len(ciphertext)]
    45              m2.cipher_ctx_free(context)
    46              self.IV = ciphertext[-self.block_size:]
    47              return bytearray(plaintext)
    48