11import json
22from binascii import unhexlify , hexlify
3- from json import JSONDecodeError
43
54from Crypto import Random
65from Crypto .Cipher import AES
76
7+ from securenative .logger import Logger
88from securenative .models .client_token import ClientToken
99
1010
@@ -14,25 +14,30 @@ class EncryptionUtils(object):
1414
1515 @classmethod
1616 def encrypt (cls , text , cipher_key ):
17- key = cipher_key [:cls .KEY_SIZE ]
18- iv = Random .new ().read (AES .block_size )
19- cipher = AES .new (key , AES .MODE_CBC , iv )
20- raw = str (cls ._pad (text ))
21- return hexlify (iv + cipher .encrypt (raw ))
17+ try :
18+ key = cipher_key [:cls .KEY_SIZE ]
19+ iv = Random .new ().read (AES .block_size )
20+ cipher = AES .new (key , AES .MODE_CBC , iv )
21+ raw = str (cls ._pad (text ))
22+ return hexlify (iv + cipher .encrypt (raw ))
23+ except Exception as e :
24+ Logger .error ("Could not encrypt text {}; {}" .format (text , e ))
25+ return None
2226
2327 @classmethod
2428 def decrypt (cls , encrypted , cipher_key ):
25- key = cipher_key [:cls .KEY_SIZE ]
26- content = unhexlify (encrypted )
27- iv = content [:cls .BLOCK_SIZE ]
28- cipher_text = content [cls .BLOCK_SIZE :]
29- aes = AES .new (key , AES .MODE_CBC , iv )
30- rv = aes .decrypt (cipher_text ).decode ("utf-8" ).strip ()
3129 try :
30+ key = cipher_key [:cls .KEY_SIZE ]
31+ content = unhexlify (encrypted )
32+ iv = content [:cls .BLOCK_SIZE ]
33+ cipher_text = content [cls .BLOCK_SIZE :]
34+ aes = AES .new (key , AES .MODE_CBC , iv )
35+ rv = aes .decrypt (cipher_text ).decode ("utf-8" ).strip ()
3236 secret = json .loads (rv )
3337 return ClientToken (secret .get ("cid" ), secret .get ("vid" ), secret .get ("fp" ))
34- except JSONDecodeError :
35- return rv
38+ except Exception as e :
39+ Logger .error ("Could not decrypt str {}; {}" .format (encrypted , e ))
40+ return None
3641
3742 @classmethod
3843 def _pad (cls , s ):
0 commit comments