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