Download src/utils/encryption.py from Khushal-ag/tabular-generation-test: direct link, hf CLI and curl.
- Browser
- Download file 6.08 kB
-
https://huggingface.co/spaces/Khushal-ag/tabular-generation-test/resolve/main/src/utils/encryption.py
- Command line
-
hf download hf://spaces/Khushal-ag/tabular-generation-test/src/utils/encryption.py
-
curl -L -o encryption.py https://huggingface.co/spaces/Khushal-ag/tabular-generation-test/resolve/main/src/utils/encryption.py
6.08 kB
| """ | |
| API key encryption and decryption utilities | |
| Provides AES-256-CBC encryption for secure API key handling | |
| """ | |
| import os | |
| import base64 | |
| import secrets | |
| from typing import Optional | |
| from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes | |
| from cryptography.hazmat.backends import default_backend | |
| def encrypt_api_key(raw_key: Optional[str]) -> Optional[str]: | |
| """ | |
| Encrypt an API key using AES-256-CBC encryption | |
| Args: | |
| raw_key: The raw API key to encrypt | |
| Returns: | |
| Base64-encoded encrypted string or None if input is None/empty | |
| Raises: | |
| ValueError: If encryption configuration is missing or invalid | |
| Exception: If encryption fails | |
| """ | |
| # Get encryption configuration from environment | |
| aes_secret_key = os.getenv('AES_SECRET_KEY') | |
| aes_iv = os.getenv('AES_IV') | |
| # Check if raw key is valid | |
| if not raw_key or raw_key.strip() == '': | |
| return None | |
| # Validate encryption configuration | |
| if not aes_secret_key or not aes_iv: | |
| raise ValueError( | |
| 'Missing encryption configuration: AES_SECRET_KEY or AES_IV not found' | |
| ) | |
| try: | |
| # Convert hex strings to bytes | |
| key_bytes = bytes.fromhex(aes_secret_key) | |
| iv_bytes = bytes.fromhex(aes_iv) | |
| # Validate key and IV sizes | |
| if len(key_bytes) != 32: # 256 bits | |
| raise ValueError('AES_SECRET_KEY must be 64 hex characters (32 bytes)') | |
| if len(iv_bytes) != 16: # 128 bits | |
| raise ValueError('AES_IV must be 32 hex characters (16 bytes)') | |
| # Create cipher | |
| cipher = Cipher( | |
| algorithms.AES(key_bytes), | |
| modes.CBC(iv_bytes), | |
| backend=default_backend() | |
| ) | |
| encryptor = cipher.encryptor() | |
| # Convert string to bytes and pad to block size | |
| raw_bytes = raw_key.encode('utf-8') | |
| padded_data = _pad_data(raw_bytes) | |
| # Encrypt | |
| encrypted_bytes = encryptor.update(padded_data) + encryptor.finalize() | |
| # Return base64-encoded result | |
| return base64.b64encode(encrypted_bytes).decode('ascii') | |
| except ValueError as e: | |
| # Re-raise validation errors | |
| raise e | |
| except Exception as e: | |
| raise Exception( | |
| f'Failed to encrypt API key: Invalid key format or encryption error - {str(e)}' | |
| ) | |
| def decrypt_api_key(encrypted_key: Optional[str]) -> Optional[str]: | |
| """ | |
| Decrypt an API key using AES-256-CBC decryption | |
| Args: | |
| encrypted_key: Base64-encoded encrypted API key | |
| Returns: | |
| Decrypted API key string or None if input is None/empty | |
| Raises: | |
| ValueError: If encryption configuration is missing or invalid | |
| Exception: If decryption fails | |
| """ | |
| # Get encryption configuration from environment | |
| aes_secret_key = os.getenv('AES_SECRET_KEY') | |
| aes_iv = os.getenv('AES_IV') | |
| # Check if encrypted key is valid | |
| if not encrypted_key or encrypted_key.strip() == '': | |
| return None | |
| # Validate encryption configuration | |
| if not aes_secret_key or not aes_iv: | |
| raise ValueError( | |
| 'Missing encryption configuration: AES_SECRET_KEY or AES_IV not found' | |
| ) | |
| try: | |
| # Convert hex strings to bytes | |
| key_bytes = bytes.fromhex(aes_secret_key) | |
| iv_bytes = bytes.fromhex(aes_iv) | |
| # Validate key and IV sizes | |
| if len(key_bytes) != 32: # 256 bits | |
| raise ValueError('AES_SECRET_KEY must be 64 hex characters (32 bytes)') | |
| if len(iv_bytes) != 16: # 128 bits | |
| raise ValueError('AES_IV must be 32 hex characters (16 bytes)') | |
| # Decode base64 | |
| encrypted_bytes = base64.b64decode(encrypted_key.encode('ascii')) | |
| # Create cipher | |
| cipher = Cipher( | |
| algorithms.AES(key_bytes), | |
| modes.CBC(iv_bytes), | |
| backend=default_backend() | |
| ) | |
| decryptor = cipher.decryptor() | |
| # Decrypt | |
| decrypted_padded = decryptor.update(encrypted_bytes) + decryptor.finalize() | |
| # Remove padding and convert to string | |
| decrypted_bytes = _unpad_data(decrypted_padded) | |
| return decrypted_bytes.decode('utf-8') | |
| except ValueError as e: | |
| # Re-raise validation errors | |
| raise e | |
| except Exception as e: | |
| raise Exception( | |
| f'Failed to decrypt API key: Invalid key format or corrupted data - {str(e)}' | |
| ) | |
| def _pad_data(data: bytes) -> bytes: | |
| """ | |
| Pad data to AES block size using PKCS7 padding | |
| Args: | |
| data: Raw bytes to pad | |
| Returns: | |
| Padded bytes | |
| """ | |
| block_size = 16 # AES block size | |
| padding_length = block_size - (len(data) % block_size) | |
| padding = bytes([padding_length] * padding_length) | |
| return data + padding | |
| def _unpad_data(padded_data: bytes) -> bytes: | |
| """ | |
| Remove PKCS7 padding from data | |
| Args: | |
| padded_data: Padded bytes | |
| Returns: | |
| Unpadded bytes | |
| Raises: | |
| ValueError: If padding is invalid | |
| """ | |
| if len(padded_data) == 0: | |
| raise ValueError("Cannot unpad empty data") | |
| padding_length = padded_data[-1] | |
| if padding_length > 16 or padding_length == 0: | |
| raise ValueError("Invalid padding length") | |
| # Verify padding | |
| for i in range(padding_length): | |
| if padded_data[-(i + 1)] != padding_length: | |
| raise ValueError("Invalid padding") | |
| return padded_data[:-padding_length] | |
| def generate_encryption_keys() -> tuple[str, str]: | |
| """ | |
| Generate new AES secret key and IV for development/testing purposes | |
| Returns: | |
| Tuple of (secret_key_hex, iv_hex) | |
| """ | |
| # Generate 32 random bytes for AES-256 key | |
| secret_key = secrets.token_bytes(32) | |
| # Generate 16 random bytes for IV | |
| iv = secrets.token_bytes(16) | |
| return secret_key.hex(), iv.hex() | |