""" QCrypt RNG Python Client SDK Enterprise-ready client for integrating with QCrypt RNG API """ import requests import json from typing import Dict, Any, Optional, Union from enum import Enum class Algorithm(str, Enum): """Supported cryptographic algorithms""" AES = "AES" RSA = "RSA" ECDSA = "ECDSA" DILITHIUM2 = "DILITHIUM2" DILITHIUM3 = "DILITHIUM3" DILITHIUM5 = "DILITHIUM5" KYBER512 = "KYBER512" KYBER768 = "KYBER768" KYBER1024 = "KYBER1024" FALCON512 = "FALCON512" FALCON1024 = "FALCON1024" class OutputFormat(str, Enum): """Supported output formats""" HEX = "hex" BASE64 = "base64" ARRAY = "array" RAW = "raw" class QCryptClient: """ Python client for QCrypt RNG API Provides easy access to quantum random number generation, post-quantum cryptography, and blockchain security features. """ def __init__(self, base_url: str = "http://localhost:8000", api_key: Optional[str] = None): """ Initialize the QCrypt client Args: base_url: Base URL of the QCrypt API server api_key: API key for authentication (optional if not required) """ self.base_url = base_url.rstrip('/') self.api_key = api_key self.session = requests.Session() # Set up headers self.session.headers.update({ 'Content-Type': 'application/json', 'User-Agent': 'QCrypt-Python-SDK/1.0' }) if api_key: self.session.headers.update({'X-API-Key': api_key}) def _make_request(self, method: str, endpoint: str, data: Optional[Dict] = None) -> Dict[str, Any]: """ Make an HTTP request to the API Args: method: HTTP method (GET, POST, etc.) endpoint: API endpoint (e.g., '/api/v2/generate/bytes') data: Request payload (for POST requests) Returns: JSON response from the API """ url = f"{self.base_url}{endpoint}" try: if method.upper() == 'GET': response = self.session.get(url) elif method.upper() == 'POST': response = self.session.post(url, json=data) else: raise ValueError(f"Unsupported HTTP method: {method}") response.raise_for_status() return response.json() except requests.exceptions.RequestException as e: raise QCryptAPIError(f"API request failed: {str(e)}") except json.JSONDecodeError: raise QCryptAPIError("Invalid JSON response from API") def generate_bytes( self, length: int, quantum_bits: int = 8, output_format: OutputFormat = OutputFormat.HEX ) -> Dict[str, Any]: """ Generate quantum random bytes Args: length: Number of bytes to generate (1-10240) quantum_bits: Number of qubits to use (1-16) output_format: Output format (hex, base64, array, raw) Returns: Dictionary containing the generated bytes and metadata """ payload = { "length": length, "quantum_bits": quantum_bits, "format": output_format.value } return self._make_request('POST', '/api/v2/generate/bytes', payload) def generate_key( self, algorithm: Algorithm, key_size: int, output_format: OutputFormat = OutputFormat.HEX ) -> Dict[str, Any]: """ Generate cryptographic key Args: algorithm: Cryptographic algorithm (AES, RSA, ECDSA, etc.) key_size: Key size in bits output_format: Output format (hex, base64, etc.) Returns: Dictionary containing the generated key and metadata """ payload = { "algorithm": algorithm.value, "key_size": key_size, "format": output_format.value } return self._make_request('POST', '/api/v2/generate/key', payload) def generate_token( self, length: int = 32, url_safe: bool = True, expires_in: Optional[int] = 3600 ) -> Dict[str, Any]: """ Generate secure session token Args: length: Token length in bytes url_safe: Whether to use URL-safe encoding expires_in: Expiration time in seconds (None for no expiration) Returns: Dictionary containing the generated token and metadata """ payload = { "length": length, "url_safe": url_safe, "expires_in": expires_in } return self._make_request('POST', '/api/v2/generate/token', payload) def generate_uuid( self, version: int = 4, count: int = 1, output_format: str = "standard" ) -> Dict[str, Any]: """ Generate quantum UUID Args: version: UUID version (currently only v4 supported) count: Number of UUIDs to generate output_format: Format (standard, raw, urn) Returns: Dictionary containing the generated UUID(s) and metadata """ payload = { "version": version, "count": count, "format": output_format } return self._make_request('POST', '/api/v2/generate/uuid', payload) def generate_password( self, length: int = 16, include_uppercase: bool = True, include_lowercase: bool = True, include_numbers: bool = True, include_symbols: bool = True, exclude_ambiguous: bool = False, min_uppercase: int = 1, min_lowercase: int = 1, min_numbers: int = 1, min_symbols: int = 1 ) -> Dict[str, Any]: """ Generate secure password Args: length: Password length include_uppercase: Include uppercase letters include_lowercase: Include lowercase letters include_numbers: Include numbers include_symbols: Include symbols exclude_ambiguous: Exclude ambiguous characters (0,O,1,l,I) min_uppercase: Minimum number of uppercase letters min_lowercase: Minimum number of lowercase letters min_numbers: Minimum number of numbers min_symbols: Minimum number of symbols Returns: Dictionary containing the generated password and metadata """ payload = { "length": length, "include_uppercase": include_uppercase, "include_lowercase": include_lowercase, "include_numbers": include_numbers, "include_symbols": include_symbols, "exclude_ambiguous": exclude_ambiguous, "min_uppercase": min_uppercase, "min_lowercase": min_lowercase, "min_numbers": min_numbers, "min_symbols": min_symbols } return self._make_request('POST', '/api/v2/generate/password', payload) def generate_pqc_keypair( self, algorithm: Union[Algorithm, str], encoding: str = "base64" ) -> Dict[str, Any]: """ Generate post-quantum cryptography key pair Args: algorithm: PQC algorithm (DILITHIUM2/3/5, KYBER512/768/1024, etc.) encoding: Output encoding (base64 or hex) Returns: Dictionary containing the key pair and metadata """ if isinstance(algorithm, Algorithm): algorithm = algorithm.value payload = { "algorithm": algorithm, "encoding": encoding } return self._make_request('POST', '/api/v2/pqc/generate', payload) def sign_with_pqc( self, message: str, private_key: str, algorithm: Union[Algorithm, str] = Algorithm.DILITHIUM3, encoding: str = "base64" ) -> Dict[str, Any]: """ Sign a message with post-quantum signature Args: message: Message to sign private_key: Private key (base64 or hex encoded) algorithm: Signing algorithm encoding: Key encoding format Returns: Dictionary containing the signature and metadata """ if isinstance(algorithm, Algorithm): algorithm = algorithm.value payload = { "message": message, "private_key": private_key, "algorithm": algorithm, "encoding": encoding } return self._make_request('POST', '/api/v2/pqc/sign', payload) def verify_pqc_signature( self, message: str, signature: str, public_key: str, algorithm: Union[Algorithm, str] = Algorithm.DILITHIUM3, encoding: str = "base64" ) -> Dict[str, Any]: """ Verify a post-quantum signature Args: message: Original message signature: Signature to verify public_key: Public key algorithm: Signing algorithm encoding: Key encoding format Returns: Dictionary containing verification result and metadata """ if isinstance(algorithm, Algorithm): algorithm = algorithm.value payload = { "message": message, "signature": signature, "public_key": public_key, "algorithm": algorithm, "encoding": encoding } return self._make_request('POST', '/api/v2/pqc/verify', payload) def assess_quantum_threat( self, algorithm: str ) -> Dict[str, Any]: """ Assess quantum threat level for a cryptographic algorithm Args: algorithm: Algorithm to assess (e.g., RSA-2048, ECDSA-256) Returns: Dictionary containing threat assessment """ payload = { "algorithm": algorithm } return self._make_request('POST', '/api/v2/pqc/assess-threat', payload) def create_blockchain_wallet( self, wallet_type: str = "both" ) -> Dict[str, Any]: """ Create blockchain wallet with both vulnerable and quantum-safe keys Args: wallet_type: 'vulnerable', 'quantum-safe', or 'both' Returns: Dictionary containing wallet information """ payload = { "wallet_type": wallet_type } return self._make_request('POST', '/api/v2/blockchain/create-wallet', payload) def sign_blockchain_transaction( self, from_address: str, to_address: str, amount: float, signature_type: str = "both" ) -> Dict[str, Any]: """ Sign a blockchain transaction Args: from_address: Sender address to_address: Recipient address amount: Amount to transfer signature_type: 'vulnerable', 'quantum-safe', or 'both' Returns: Dictionary containing transaction and signatures """ payload = { "from_address": from_address, "to_address": to_address, "amount": amount, "signature_type": signature_type } return self._make_request('POST', '/api/v2/blockchain/sign-transaction', payload) def simulate_quantum_attack( self, target: str = "RSA-2048", show_timeline: bool = True ) -> Dict[str, Any]: """ Simulate Shor's algorithm quantum attack Args: target: Algorithm to attack (e.g., RSA-2048, ECDSA-256) show_timeline: Whether to include quantum computing timeline Returns: Dictionary containing attack simulation results """ payload = { "target": target, "show_timeline": show_timeline } return self._make_request('POST', '/api/v2/blockchain/simulate-attack', payload) def get_system_info(self) -> Dict[str, Any]: """ Get system information and statistics Returns: Dictionary containing system information """ return self._make_request('GET', '/') def get_health(self) -> Dict[str, Any]: """ Get system health status Returns: Dictionary containing health status """ return self._make_request('GET', '/health') class QCryptAPIError(Exception): """Custom exception for API errors""" pass # Example usage if __name__ == "__main__": # Initialize client client = QCryptClient(base_url="http://localhost:8000", api_key="your-api-key") # Generate quantum random bytes try: result = client.generate_bytes(length=32, quantum_bits=8, output_format=OutputFormat.HEX) print(f"Generated bytes: {result['data']['bytes']}") except QCryptAPIError as e: print(f"Error: {e}") # Generate a quantum-safe key pair try: result = client.generate_pqc_keypair(Algorithm.DILITHIUM3) print(f"DILITHIUM3 key generated, NIST Level: {result['data']['nist_level']}") except QCryptAPIError as e: print(f"Error: {e}")