<s> from __future__ import unicode_literals <EOL> import binascii <EOL> from django . conf import settings <EOL> from django . db import models <EOL> from django . utils . encoding import force_bytes , force_text <EOL> try : <EOL> import Crypto . Cipher . AES <EOL> except ImportError : <EOL> raise ImportError ( '<STR_LIT>' ) <EOL> class EncryptedField ( models . TextField ) : <EOL> """<STR_LIT>""" <EOL> cipher_class = Crypto . Cipher . AES <EOL> prefix = b'<STR_LIT>' <EOL> def __init__ ( self , * args , ** kwargs ) : <EOL> self . cipher = self . cipher_class . new ( force_bytes ( settings . SECRET_KEY ) [ : <NUM_LIT:32> ] ) <EOL> super ( EncryptedField , self ) . __init__ ( * args , ** kwargs ) <EOL> def _is_encrypted ( self , value ) : <EOL> return value . startswith ( self . prefix ) <EOL> def _get_padding ( self , value ) : <EOL> mod = ( len ( value ) + <NUM_LIT:2> ) % self . cipher . block_size <EOL> return self . cipher . block_size - mod + <NUM_LIT:2> <EOL> def from_db_value ( self , value , expression , connection , context ) : <EOL> if value is None : <EOL> return value <EOL> value = force_bytes ( value ) <EOL> if self . _is_encrypted ( value ) : <EOL> hexdigest = value [ len ( self . prefix ) : ] <EOL> encrypted = binascii . a2b_hex ( hexdigest ) <EOL> decrypted = self . cipher . decrypt ( encrypted ) . split ( b'<STR_LIT:\x00>' ) [ <NUM_LIT:0> ] <EOL> return force_text ( decrypted ) <EOL> return force_text ( value ) <EOL> def get_db_prep_value ( self , value , connection = None , prepared = False ) : <EOL> if self . null : <EOL> value = value or None <EOL> if value is None : <EOL> return None <EOL> value = force_bytes ( value ) <EOL> if not self . _is_encrypted ( value ) : <EOL> padding = self . _get_padding ( value ) <EOL> if padding > <NUM_LIT:0> : <EOL> value = value + b'<STR_LIT:\x00>' + b'<STR_LIT:*>' * ( padding - <NUM_LIT:1> ) <EOL> value = self . prefix + binascii . b2a_hex ( self . cipher . encrypt ( value ) ) <EOL> return force_text ( value ) </s>
