encryption.py 1.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  1. """
  2. Encryption utilities for sensitive data (WiFi passwords, etc).
  3. Uses Fernet (symmetric encryption) from cryptography library.
  4. """
  5. from cryptography.fernet import Fernet
  6. from app.config import settings
  7. def get_cipher() -> Fernet:
  8. """Get Fernet cipher instance."""
  9. # Convert settings key to bytes if needed
  10. key = settings.ENCRYPTION_KEY
  11. if isinstance(key, str):
  12. key = key.encode()
  13. return Fernet(key)
  14. def encrypt_password(plain_password: str) -> str:
  15. """
  16. Encrypt a password using Fernet.
  17. Args:
  18. plain_password: Plain text password
  19. Returns:
  20. Encrypted password as string (base64 encoded)
  21. """
  22. cipher = get_cipher()
  23. encrypted_bytes = cipher.encrypt(plain_password.encode())
  24. return encrypted_bytes.decode()
  25. def decrypt_password(encrypted_password: str) -> str:
  26. """
  27. Decrypt a password using Fernet.
  28. Args:
  29. encrypted_password: Encrypted password (base64 encoded string)
  30. Returns:
  31. Decrypted plain text password
  32. """
  33. cipher = get_cipher()
  34. decrypted_bytes = cipher.decrypt(encrypted_password.encode())
  35. return decrypted_bytes.decode()