import pickle from pathlib import Path from cryptography.fernet import Fernet from secrets_config import load_secrets # ===================================================== # SECRET KEY (only your program has this) # ===================================================== # The key is generated once and stored outside Git in instance/secrets.yaml. _SECRET_KEY = load_secrets(Path(__file__).parent / "instance")["fernet"]["key"].encode("ascii") fernet = Fernet(_SECRET_KEY) # ===================================================== # ENCRYPT # ===================================================== def encrypt_object(obj) -> bytes: """ Encrypt any Python object and return encrypted bytes. """ serialized = pickle.dumps(obj) encrypted = fernet.encrypt(serialized) return encrypted # ===================================================== # DECRYPT # ===================================================== def decrypt_object(encrypted_data: bytes): """ Decrypt bytes back into the original Python object. """ decrypted = fernet.decrypt(encrypted_data) obj = pickle.loads(decrypted) return obj # ===================================================== # EXAMPLE USAGE # ===================================================== if __name__ == "__main__": original_object = { "user": "alice", "permissions": ["read", "write"], "balance": 123.45 } encrypted = encrypt_object(original_object) print("Encrypted:", str(encrypted)) decrypted = decrypt_object(encrypted) print("Decrypted:", decrypted) bytes_data = b'I am a bytes string' string_data = bytes_data.decode('utf-8') print("Type Before :- ",type(bytes_data)) print(string_data) print("Type After :- ",type(string_data))