@@ -15,24 +15,37 @@ class OpenSSL_TripleDES(TripleDES):
1515
1616 def __init__ (self , key , mode , IV ):
1717 TripleDES .__init__ (self , key , mode , IV , "openssl" )
18+ self ._IV , self ._key = IV , key
19+ self ._context = None
20+ self ._encrypt = None
21+
22+ def _init_context (self , encrypt = True ):
1823 cipherType = m2 .des_ede3_cbc ()
19- self .encrypt_context = m2 .cipher_ctx_new ()
20- self .decrypt_context = m2 .cipher_ctx_new ()
21- m2 .cipher_init (self .encrypt_context , cipherType , key , IV , 1 )
22- m2 .cipher_init (self .decrypt_context , cipherType , key , IV , 0 )
23- m2 .cipher_set_padding (self .encrypt_context , 0 )
24- m2 .cipher_set_padding (self .decrypt_context , 0 )
24+ self ._context = m2 .cipher_ctx_new ()
25+ m2 .cipher_init (self ._context , cipherType , self ._key , self ._IV ,
26+ int (encrypt ))
27+ m2 .cipher_set_padding (self ._context , 0 )
28+ self ._encrypt = encrypt
2529
2630 def encrypt (self , plaintext ):
31+ if self ._context is None :
32+ self ._init_context (encrypt = True )
33+ else :
34+ assert self ._encrypt , '.encrypt() not allowed after .decrypt()'
2735 TripleDES .encrypt (self , plaintext )
28- ciphertext = m2 .cipher_update (self .encrypt_context , plaintext )
36+ ciphertext = m2 .cipher_update (self ._context , plaintext )
2937 return bytearray (ciphertext )
3038
3139 def decrypt (self , ciphertext ):
40+ if self ._context is None :
41+ self ._init_context (encrypt = False )
42+ else :
43+ assert not self ._encrypt , \
44+ '.decrypt() not allowed after .encrypt()'
3245 TripleDES .decrypt (self , ciphertext )
33- plaintext = m2 .cipher_update (self .decrypt_context , ciphertext )
46+ plaintext = m2 .cipher_update (self ._context , ciphertext )
3447 return bytearray (plaintext )
3548
3649 def __del__ (self ):
37- m2 . cipher_ctx_free ( self .encrypt_context )
38- m2 .cipher_ctx_free (self .decrypt_context )
50+ if self ._context is not None :
51+ m2 .cipher_ctx_free (self ._context )
0 commit comments