Files

63 lines
1.7 KiB
Python
Raw Permalink Normal View History

2026-01-18 08:22:41 +01:00
import pickle
2026-07-19 09:58:27 +02:00
from pathlib import Path
2026-01-18 08:22:41 +01:00
from cryptography.fernet import Fernet
2026-07-19 09:58:27 +02:00
from secrets_config import load_secrets
2026-01-18 08:22:41 +01:00
# =====================================================
# SECRET KEY (only your program has this)
# =====================================================
2026-07-19 09:58:27 +02:00
# 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")
2026-01-18 08:22:41 +01:00
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)
2026-07-19 09:58:27 +02:00
print("Type After :- ",type(string_data))