I have written 2 functions in python, one for encrypting data and other for decrypting data which are as follows.
from app.settings import DATA_KEY
import logging
from cryptography.hazmat.primitives.ciphers.aead import AESSIV
import base64
cipher_suite = AESSIV(DATA_KEY)
error_logger = logging.getLogger("error_logger")
def encrypt_field(input_text):
try:
if isinstance(input_text, str):
input_text = input_text.encode()
enc_text = cipher_suite.encrypt(input_text, associated_data = None)
print(f"enc_text is {enc_text}")
enc_text_base_64 = base64.b64encode(enc_text)
print(f"encrypted_text is {enc_text_base_64}")
return enc_text_base_64
except Exception as e:
error_logger.error(f"exception in encrypt field {str(e)} on field {input_text}")
return input_text
def decrypt_field(input_text):
try:
print(f"input in decrypt field is {input_text} its type is {type(input_text)}")
enc_text = base64.b64decode(input_text)
print(f"enc text is {enc_text}")
decrypted_field = cipher_suite.decrypt(enc_text, associated_data = None)
print(f"decrypted_field is {decrypted_field}")
return decrypted_field.decode('utf-8')
except Exception as e:
print(e)
error_logger.error(f"exception in decrypt_field {e} on field {input_text}")
return input_text
I am able to encrypt and store the data in db, however upon reading the data from db and trying to decrypt it, I am getting a utf-8 bytestring instead of original plaintext string back. What am I doing wrong here?
My Django version is 5.0, Python version is 3.10.11 and Database is PostgreSQ
I have tried storing the data in BinaryField as well TextField of Django models, but to no avail the result is same. I have tried storing data as encoded byte data without base64encde as well but it cannot be decoded later and results in undefined character error.