Implementation:869413421 Ai moive studio EncryptionService
| Knowledge Sources | |
|---|---|
| Domains | Security |
| Last Updated | 2026-10-23 12:00 GMT |
Overview
Singleton service that encrypts and decrypts API keys at rest using Fernet symmetric authenticated encryption.
Description
'EncryptionService wraps the cryptography.fernet.Fernet cipher with a singleton pattern. The master key is loaded from settings.API_KEY_ENCRYPTION_KEY at initialization. The service provides:
- encrypt(): Encrypts a plaintext string to a Base64-encoded Fernet token
- decrypt(): Decrypts a Fernet token back to plaintext
- Singleton access: Via the classmethod instance() for shared access
The service rejects empty string encryption and validates the master key at initialization.
Usage
Import when encrypting or decrypting API keys. Used by the APIKey model's set_api_key and get_api_key methods.
Code Reference
Source Location
- Repository: ai-moive-studio
- File: backend/src/utils/encryption.py:L64-93
Signature
class EncryptionService:
_instance = None
@classmethod
def instance(cls) -> "EncryptionService":
"""Get or create the singleton instance."""
def encrypt(self, plain_text: str) -> str:
"""Encrypt plaintext to Base64 Fernet token."""
def decrypt(self, encrypted_text: str) -> str:
"""Decrypt Fernet token to plaintext."""
Import
from src.utils.encryption import EncryptionService
I/O Contract
Inputs
| Name | Type | Required | Description |
|---|---|---|---|
| plain_text | str | Yes (encrypt) | Plaintext to encrypt |
| encrypted_text | str | Yes (decrypt) | Fernet token to decrypt |
Outputs
| Name | Type | Description |
|---|---|---|
| encrypt() | str | Base64-encoded Fernet token |
| decrypt() | str | Decrypted plaintext |
Usage Examples
Encrypting and Decrypting
from src.utils.encryption import EncryptionService
service = EncryptionService.instance()
encrypted = service.encrypt("sk-my-api-key")
# Store 'encrypted' in database
decrypted = service.decrypt(encrypted)
# Use 'decrypted' for API calls