Spaces:
Sleeping
Sleeping
Download utils/encryption.py from Divyaraj1617/testnexus-backend: direct link, hf CLI and curl.
- Browser
- Download file 2.81 kB
-
https://huggingface.co/spaces/Divyaraj1617/testnexus-backend/resolve/main/utils/encryption.py
- Command line
-
hf download hf://spaces/Divyaraj1617/testnexus-backend/utils/encryption.py
-
curl -L -o encryption.py https://huggingface.co/spaces/Divyaraj1617/testnexus-backend/resolve/main/utils/encryption.py
2.81 kB
| """ | |
| Encryption utility for securing sensitive data like API keys | |
| Uses Fernet symmetric encryption from the cryptography library | |
| """ | |
| import os | |
| import base64 | |
| import hashlib | |
| from cryptography.fernet import Fernet, InvalidToken | |
| def get_encryption_key() -> bytes: | |
| """ | |
| Get the encryption key from environment variable. | |
| Derives a proper 32-byte Fernet key from the provided ENCRYPTION_KEY or SECRET_KEY. | |
| This ensures the key is always valid regardless of the input format. | |
| """ | |
| # Try ENCRYPTION_KEY first, then SECRET_KEY as fallback | |
| key_source = os.getenv("ENCRYPTION_KEY") or os.getenv("SECRET_KEY", "default-secret-key-change-in-production") | |
| # Derive a proper 32-byte key using SHA256 | |
| # This ensures any input (even if not in Fernet format) works correctly | |
| derived_key = hashlib.sha256(key_source.encode()).digest() | |
| fernet_key = base64.urlsafe_b64encode(derived_key) | |
| return fernet_key | |
| def encrypt_api_key(api_key: str) -> str: | |
| """ | |
| Encrypt an API key for secure storage in the database. | |
| Args: | |
| api_key: The plaintext API key to encrypt | |
| Returns: | |
| The encrypted API key as a string (base64 encoded) | |
| """ | |
| if not api_key: | |
| return "" | |
| f = Fernet(get_encryption_key()) | |
| encrypted = f.encrypt(api_key.encode()) | |
| return encrypted.decode() | |
| def decrypt_api_key(encrypted_key: str) -> str: | |
| """ | |
| Decrypt an API key retrieved from the database. | |
| Args: | |
| encrypted_key: The encrypted API key string | |
| Returns: | |
| The decrypted plaintext API key | |
| Raises: | |
| InvalidToken: If decryption fails (wrong key or corrupted data) | |
| """ | |
| if not encrypted_key: | |
| return "" | |
| try: | |
| f = Fernet(get_encryption_key()) | |
| decrypted = f.decrypt(encrypted_key.encode()) | |
| return decrypted.decode() | |
| except InvalidToken: | |
| # Log warning but don't expose details | |
| print("Warning: Failed to decrypt API key - encryption key may have changed") | |
| raise | |
| def generate_encryption_key() -> str: | |
| """ | |
| Generate a new Fernet-compatible encryption key. | |
| Use this to generate a key for the ENCRYPTION_KEY environment variable. | |
| Returns: | |
| A new encryption key as a string | |
| """ | |
| return Fernet.generate_key().decode() | |
| def mask_api_key(api_key: str, visible_chars: int = 4) -> str: | |
| """ | |
| Mask an API key for safe display, showing only first and last few characters. | |
| Args: | |
| api_key: The API key to mask | |
| visible_chars: Number of characters to show at start and end | |
| Returns: | |
| Masked API key like "sk-ab...xyz" | |
| """ | |
| if not api_key: | |
| return "" | |
| if len(api_key) <= visible_chars * 2: | |
| return "*" * len(api_key) | |
| return f"{api_key[:visible_chars]}...{api_key[-visible_chars:]}" | |