PageRenderTime 23ms CodeModel.GetById 18ms app.highlight 3ms RepoModel.GetById 1ms app.codeStats 0ms

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