1
2
3
4 """OpenSSL/M2Crypto AES implementation."""
5
6 from .cryptomath import *
7 from .aes import *
8
9 if m2cryptoLoaded:
10
11 - def new(key, mode, IV):
12 return OpenSSL_AES(key, mode, IV)
13
15
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
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
41 AES.decrypt(self, ciphertext)
42 context = self._createContext(0)
43
44
45 plaintext = m2.cipher_update(context, ciphertext+('\0'*16))
46
47
48
49 plaintext = plaintext[:len(ciphertext)]
50 m2.cipher_ctx_free(context)
51 self.IV = ciphertext[-self.block_size:]
52 return bytearray(plaintext)
53