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46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
"""
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}")