29 lines
840 B
Python
29 lines
840 B
Python
from pathlib import Path
|
|
|
|
from cryptography.fernet import Fernet
|
|
|
|
|
|
class CryptoManager:
|
|
def __init__(self, key_path: Path) -> None:
|
|
self.key_path = key_path
|
|
|
|
def _load_or_create_key(self) -> bytes:
|
|
if self.key_path.exists():
|
|
return self.key_path.read_bytes().strip()
|
|
|
|
self.key_path.parent.mkdir(parents=True, exist_ok=True)
|
|
key = Fernet.generate_key()
|
|
self.key_path.write_bytes(key)
|
|
return key
|
|
|
|
def _fernet(self) -> Fernet:
|
|
return Fernet(self._load_or_create_key())
|
|
|
|
def encrypt_text(self, value: str) -> str:
|
|
token = self._fernet().encrypt(value.encode("utf-8"))
|
|
return token.decode("utf-8")
|
|
|
|
def decrypt_text(self, token: str) -> str:
|
|
value = self._fernet().decrypt(token.encode("utf-8"))
|
|
return value.decode("utf-8")
|