def get_admin_key(keylen=ADMIN_KEY_LEN): """ reads admin key from file (and sets admin in config module) """ logging.info('reading admin key from %s', TOKEN_SERVICE_ADMIN_KEY) with open(TOKEN_SERVICE_ADMIN_KEY, 'r') as f: d = f.readline().strip() raw_len = keylen * 2 if len(d) != raw_len: logging.warn('admin key file %s must contain a %s byte hexidecimal string', TOKEN_SERVICE_ADMIN_KEY, raw_len) admin_key = d # this remains as hex tsc.admin_key = admin_key logging_sensitive("read admin_key: %s", admin_key) return admin_key
def get_db_key(keylen=DB_KEY_LEN): """ reads db key from file, create crypt instance """ logging.info('reading DB key from %s', TOKEN_SERVICE_DB_KEY) with open(TOKEN_SERVICE_DB_KEY, 'r') as f: d = f.readline().strip() raw_len = keylen * 2 if len(d) != raw_len: logging.warn('db key file %s must contain a %s byte hexidecimal string', TOKEN_SERVICE_DB_KEY, raw_len) db_key = binascii.unhexlify(d.encode('utf-8')) crypt.instance = crypt.Crypt(db_key) logging_sensitive("read db_key and created crypt instance: %s", db_key) return db_key
def decrypt(self, ciphertext): logging_sensitive('crypt.decrypt ciphertext: %s', ciphertext) if len(ciphertext) % 4 != 0: ciphertext += '=' * (4 - (len(ciphertext) % 4)) de_enco = base64.b64decode(ciphertext) iv = de_enco[:AES.block_size] aes = AES.new(self.key, AES.MODE_CFB, iv) de_encr = aes.decrypt(de_enco[AES.block_size:]) logging_sensitive('crypt.decrypt de_encr: %s', de_encr) # unpad pad_n = de_encr[-1] if not isinstance(pad_n, int): # py3 returns bytes as decrypted value # py2 original string; so it needs the inverse of the chr pad_n = ord(pad_n) de_encr = de_encr[:-pad_n] de_encr = de_encr.decode('utf-8') logging_sensitive('crypt.decrypt de_encr unpad: %s', de_encr) return de_encr
def encrypt(self, plaintext): # pad PKSC#7 (https://www.ietf.org/rfc/rfc2315.txt) if plaintext: pad_n = (AES.block_size - (len(plaintext) % AES.block_size)) else: plaintext = '' pad_n = AES.block_size plaintext += pad_n * chr(pad_n) logging_sensitive('crypt.encrypt plaintext: %s', plaintext) iv = self.random(AES.block_size) logging_sensitive('crypt.encrypt iv: %s', iv) aes = AES.new(self.key, AES.MODE_CFB, iv) encr = aes.encrypt(plaintext.encode('utf-8')) enco = base64.b64encode(iv + encr) enco = enco.decode('utf-8') logging_sensitive("encrypted [%s] to [%s]", plaintext, enco) return enco
def get_prep_value(self, value): logging_sensitive('EncryptedTextField.get_prep_value value: %s', value) enc = self.crypt.encrypt(value) logging_sensitive('EncryptedTextField.get_prep_value(%s) -> %s', value, enc) return enc
def from_db_value(self, value, expression, connection, context): logging_sensitive('EncryptedTextField.from_db_value value: %s', value) dec = self.crypt.decrypt(value) logging_sensitive('EncryptedTextField.from_db_value(%s) -> %s', value, dec) return dec