utils.py 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  1. from passlib.context import CryptContext
  2. from cryptography.fernet import Fernet, InvalidToken
  3. from pathlib import Path
  4. import os
  5. pwd_context = CryptContext(schemes=["bcrypt"], deprecated="auto")
  6. def hash_password(password: str) -> str:
  7. return pwd_context.hash(password)
  8. def verify_password(plain_password: str, hashed_password: str) -> bool:
  9. return pwd_context.verify(plain_password, hashed_password)
  10. KEY_FILE = Path(__file__).resolve().parent / "encryption.key"
  11. def load_key() -> bytes:
  12. env_key = os.getenv("ENCRYPTION_KEY")
  13. if env_key:
  14. return env_key.encode() if isinstance(env_key, str) else env_key
  15. if KEY_FILE.exists():
  16. return KEY_FILE.read_bytes().strip()
  17. key = Fernet.generate_key()
  18. KEY_FILE.write_bytes(key)
  19. return key
  20. try:
  21. key = load_key()
  22. cipher = Fernet(key)
  23. except Exception as exc:
  24. raise RuntimeError(
  25. "Invalid encryption key. Set ENCRYPTION_KEY or remove/replace encryption.key with a valid Fernet key."
  26. ) from exc
  27. def encrypt_data(data: str) -> str:
  28. return cipher.encrypt(data.encode()).decode()
  29. def decrypt_data(encrypted_data: str) -> str:
  30. try:
  31. return cipher.decrypt(encrypted_data.encode()).decode()
  32. except InvalidToken as exc:
  33. raise ValueError("Unable to decrypt data: invalid encryption token or mismatched key") from exc