Download server.py from SemantIQ/pqc-safe: direct link, hf CLI and curl.
- Browser
- Download file 26.3 kB
-
https://huggingface.co/spaces/SemantIQ/pqc-safe/resolve/main/server.py
- Command line
-
hf download hf://spaces/SemantIQ/pqc-safe/server.py
-
curl -L -o server.py https://huggingface.co/spaces/SemantIQ/pqc-safe/resolve/main/server.py
26.3 kB
| """ | |
| Quantum Crypto-Breaking Simulation & PQC Testing Server | |
| Simulates Grover's search, Shor's factoring, and PQC algorithm comparisons. | |
| """ | |
| import math | |
| import time | |
| import random | |
| import hashlib | |
| import os | |
| from typing import Optional | |
| import numpy as np | |
| try: | |
| import sympy | |
| except ImportError: | |
| sympy = None | |
| from fastapi import FastAPI, HTTPException | |
| from fastapi.staticfiles import StaticFiles | |
| from fastapi.responses import FileResponse | |
| from pydantic import BaseModel, Field | |
| app = FastAPI(title="Quantum Crypto Simulation") | |
| # βββ Request / Response Models βββββββββββββββββββββββββββββββββββββββββββββββ | |
| class GroverRequest(BaseModel): | |
| search_space_bits: int = Field(..., ge=2, le=30, description="Number of bits in search space (2-30)") | |
| target_value: Optional[int] = None | |
| iterations: Optional[int] = None | |
| class ShorRequest(BaseModel): | |
| number: int = Field(..., ge=6, le=999999, description="Number to factor (6-999999)") | |
| class PQCCompareRequest(BaseModel): | |
| algorithms: list[str] = Field(default=["RSA-2048", "ECC-256", "AES-256", | |
| "ML-KEM-768", "ML-DSA-65", "SLH-DSA-128s"]) | |
| message_size_bytes: int = Field(default=256, ge=1, le=10000) | |
| class AVX512CompareRequest(BaseModel): | |
| algorithms: list[str] = Field(default=["ML-DSA-44", "ML-DSA-65", "ML-DSA-87", | |
| "ML-KEM-512", "ML-KEM-768", "ML-KEM-1024"]) | |
| operation: str = Field(default="all", description="Operation to compare: keygen, sign, verify, encrypt, decrypt, all") | |
| class BruteForceRequest(BaseModel): | |
| key_bits: int = Field(..., ge=4, le=128, description="Key size in bits") | |
| algorithm: str = Field(default="AES", description="Algorithm name") | |
| # βββ Grover's Algorithm Simulation ββββββββββββββββββββββββββββββββββββββββββ | |
| def simulate_grover(search_space_bits: int, target: int, max_iterations: Optional[int] = None): | |
| """ | |
| Simulate Grover's search algorithm. | |
| Classical search: O(N), Grover: O(βN) | |
| """ | |
| N = 2 ** search_space_bits | |
| if target < 0 or target >= N: | |
| target = random.randint(0, N - 1) | |
| optimal_iterations = max(1, int(math.pi / 4 * math.sqrt(N))) | |
| iterations = max_iterations if max_iterations else optimal_iterations | |
| # Simulate quantum state evolution | |
| # Initial amplitude for all states: 1/βN | |
| amplitude_target = 1.0 / math.sqrt(N) | |
| amplitude_other = 1.0 / math.sqrt(N) | |
| steps = [] | |
| for i in range(1, iterations + 1): | |
| # Oracle: flip target amplitude | |
| amplitude_target = -amplitude_target | |
| # Diffusion: inversion about mean | |
| mean = (amplitude_target + (N - 1) * amplitude_other) / N | |
| amplitude_target = 2 * mean - amplitude_target | |
| amplitude_other = 2 * mean - amplitude_other | |
| prob_target = amplitude_target ** 2 | |
| prob_other = amplitude_other ** 2 | |
| steps.append({ | |
| "iteration": i, | |
| "target_probability": round(min(prob_target, 1.0), 6), | |
| "other_probability": round(max(prob_other, 0.0), 8), | |
| "target_amplitude": round(amplitude_target, 6), | |
| }) | |
| # Classical comparison | |
| classical_avg_steps = N / 2 | |
| quantum_steps = optimal_iterations | |
| speedup = classical_avg_steps / quantum_steps if quantum_steps > 0 else 1 | |
| return { | |
| "search_space_bits": search_space_bits, | |
| "search_space_size": N, | |
| "target_value": target, | |
| "optimal_iterations": optimal_iterations, | |
| "iterations_run": iterations, | |
| "final_target_probability": steps[-1]["target_probability"] if steps else 0, | |
| "classical_avg_queries": int(classical_avg_steps), | |
| "quantum_queries": quantum_steps, | |
| "speedup_factor": round(speedup, 2), | |
| "steps": steps, | |
| } | |
| # βββ Shor's Algorithm Simulation ββββββββββββββββββββββββββββββββββββββββββββ | |
| def classical_gcd(a: int, b: int) -> int: | |
| while b: | |
| a, b = b, a % b | |
| return a | |
| def find_order(a: int, n: int) -> Optional[int]: | |
| """Find the multiplicative order of a mod n (period finding).""" | |
| if classical_gcd(a, n) != 1: | |
| return None | |
| r = 1 | |
| current = a % n | |
| while current != 1 and r < n: | |
| current = (current * a) % n | |
| r += 1 | |
| return r if current == 1 else None | |
| def simulate_shor(number: int): | |
| """ | |
| Simulate Shor's factoring algorithm step-by-step. | |
| """ | |
| N = number | |
| if N < 2: | |
| return {"error": "Number must be >= 2"} | |
| # Primality check (use sympy if available, else trial division) | |
| def is_prime(n): | |
| if sympy: | |
| return sympy.isprime(n) | |
| if n < 2: | |
| return False | |
| if n < 4: | |
| return True | |
| if n % 2 == 0 or n % 3 == 0: | |
| return False | |
| i = 5 | |
| while i * i <= n: | |
| if n % i == 0 or n % (i + 2) == 0: | |
| return False | |
| i += 6 | |
| return True | |
| if is_prime(N): | |
| return {"error": f"{N} is prime, cannot be factored"} | |
| if N % 2 == 0: | |
| return { | |
| "number": N, | |
| "factors": [2, N // 2], | |
| "method": "trivial_even", | |
| "steps": [{"step": "Even number detected", "detail": f"{N} = 2 Γ {N // 2}"}], | |
| "quantum_bits_needed": 0, | |
| "classical_difficulty": "trivial", | |
| } | |
| # Check perfect power | |
| for b in range(2, int(math.log2(N)) + 1): | |
| a = round(N ** (1.0 / b)) | |
| for candidate in [a - 1, a, a + 1]: | |
| if candidate > 1 and candidate ** b == N: | |
| return { | |
| "number": N, | |
| "factors": [candidate, N // candidate], | |
| "method": "perfect_power", | |
| "steps": [{"step": "Perfect power detected", "detail": f"{N} = {candidate}^{b}"}], | |
| "quantum_bits_needed": 0, | |
| "classical_difficulty": "trivial", | |
| } | |
| steps = [] | |
| attempts = [] | |
| factors = None | |
| qubits_needed = 2 * math.ceil(math.log2(N)) + 3 | |
| for attempt in range(1, 20): | |
| a = random.randint(2, N - 1) | |
| g = classical_gcd(a, N) | |
| step_info = {"attempt": attempt, "a": a, "gcd_a_N": g} | |
| if g > 1: | |
| step_info["result"] = f"Lucky: gcd({a}, {N}) = {g}" | |
| factors = sorted([g, N // g]) | |
| steps.append(step_info) | |
| break | |
| r = find_order(a, N) | |
| step_info["order_r"] = r | |
| if r is None or r % 2 != 0: | |
| step_info["result"] = f"Order r={r} is {'None' if r is None else 'odd'}, retry" | |
| steps.append(step_info) | |
| continue | |
| x = pow(a, r // 2, N) | |
| step_info["a^(r/2) mod N"] = x | |
| if x == N - 1: | |
| step_info["result"] = f"a^(r/2) β‘ -1 (mod N), retry" | |
| steps.append(step_info) | |
| continue | |
| f1 = classical_gcd(x - 1, N) | |
| f2 = classical_gcd(x + 1, N) | |
| step_info["gcd(x-1, N)"] = f1 | |
| step_info["gcd(x+1, N)"] = f2 | |
| if f1 > 1 and f1 < N: | |
| factors = sorted([f1, N // f1]) | |
| step_info["result"] = f"Success! {N} = {factors[0]} Γ {factors[1]}" | |
| steps.append(step_info) | |
| break | |
| elif f2 > 1 and f2 < N: | |
| factors = sorted([f2, N // f2]) | |
| step_info["result"] = f"Success! {N} = {factors[0]} Γ {factors[1]}" | |
| steps.append(step_info) | |
| break | |
| else: | |
| step_info["result"] = "No non-trivial factor found, retry" | |
| steps.append(step_info) | |
| bits = math.ceil(math.log2(N)) | |
| classical_trial_div = int(math.sqrt(N)) | |
| quantum_period_finding = int(bits ** 3) | |
| return { | |
| "number": N, | |
| "factors": factors, | |
| "method": "shor_simulation", | |
| "steps": steps, | |
| "quantum_bits_needed": qubits_needed, | |
| "number_bits": bits, | |
| "classical_trial_divisions": classical_trial_div, | |
| "quantum_operations_estimate": quantum_period_finding, | |
| "speedup": f"Exponential: O(nΒ³) quantum vs O(exp(n^(1/3))) classical (GNFS)", | |
| } | |
| # βββ PQC Comparison Engine ββββββββββββββββββββββββββββββββββββββββββββββββββ | |
| PQC_DATABASE = { | |
| "RSA-2048": { | |
| "type": "asymmetric", "family": "Integer Factorization", | |
| "classical_security_bits": 112, "quantum_security_bits": 0, | |
| "key_size_bytes": 256, "signature_bytes": 256, "encap_bytes": 256, | |
| "keygen_us": 50000, "sign_us": 1200, "verify_us": 50, | |
| "encrypt_us": 50, "decrypt_us": 1200, | |
| "nist_level": 0, "quantum_vulnerable": True, | |
| "standard": "FIPS 186-5", | |
| "attack": "Shor's algorithm breaks in polynomial time", | |
| }, | |
| "ECC-256": { | |
| "type": "asymmetric", "family": "Elliptic Curve DLP", | |
| "classical_security_bits": 128, "quantum_security_bits": 0, | |
| "key_size_bytes": 32, "signature_bytes": 64, "encap_bytes": 65, | |
| "keygen_us": 100, "sign_us": 150, "verify_us": 300, | |
| "encrypt_us": 300, "decrypt_us": 150, | |
| "nist_level": 0, "quantum_vulnerable": True, | |
| "standard": "FIPS 186-5", | |
| "attack": "Shor's algorithm (ECDLP variant) breaks in polynomial time", | |
| }, | |
| "AES-128": { | |
| "type": "symmetric", "family": "Block Cipher", | |
| "classical_security_bits": 128, "quantum_security_bits": 64, | |
| "key_size_bytes": 16, "signature_bytes": 0, "encap_bytes": 0, | |
| "keygen_us": 1, "sign_us": 0, "verify_us": 0, | |
| "encrypt_us": 0.5, "decrypt_us": 0.5, | |
| "nist_level": 1, "quantum_vulnerable": False, | |
| "standard": "FIPS 197", | |
| "attack": "Grover's reduces to 64-bit security β insufficient", | |
| }, | |
| "AES-256": { | |
| "type": "symmetric", "family": "Block Cipher", | |
| "classical_security_bits": 256, "quantum_security_bits": 128, | |
| "key_size_bytes": 32, "signature_bytes": 0, "encap_bytes": 0, | |
| "keygen_us": 1, "sign_us": 0, "verify_us": 0, | |
| "encrypt_us": 0.7, "decrypt_us": 0.7, | |
| "nist_level": 5, "quantum_vulnerable": False, | |
| "standard": "FIPS 197", | |
| "attack": "Grover's reduces to 128-bit security β still secure", | |
| }, | |
| "Kyber-512": { | |
| "type": "KEM", "family": "Lattice (MLWE)", | |
| "classical_security_bits": 128, "quantum_security_bits": 128, | |
| "key_size_bytes": 800, "signature_bytes": 0, "encap_bytes": 768, | |
| "keygen_us": 30, "sign_us": 0, "verify_us": 0, | |
| "encrypt_us": 40, "decrypt_us": 30, | |
| "nist_level": 1, "quantum_vulnerable": False, | |
| "attack": "No known polynomial quantum attack", | |
| }, | |
| "Kyber-768": { | |
| "type": "KEM", "family": "Lattice (MLWE)", | |
| "classical_security_bits": 192, "quantum_security_bits": 192, | |
| "key_size_bytes": 1184, "signature_bytes": 0, "encap_bytes": 1088, | |
| "keygen_us": 45, "sign_us": 0, "verify_us": 0, | |
| "encrypt_us": 55, "decrypt_us": 45, | |
| "nist_level": 3, "quantum_vulnerable": False, | |
| "attack": "No known polynomial quantum attack", | |
| }, | |
| "Kyber-1024": { | |
| "type": "KEM", "family": "Lattice (MLWE)", | |
| "classical_security_bits": 256, "quantum_security_bits": 256, | |
| "key_size_bytes": 1568, "signature_bytes": 0, "encap_bytes": 1568, | |
| "keygen_us": 65, "sign_us": 0, "verify_us": 0, | |
| "encrypt_us": 75, "decrypt_us": 60, | |
| "nist_level": 5, "quantum_vulnerable": False, | |
| "attack": "No known polynomial quantum attack", | |
| }, | |
| "Dilithium-2": { | |
| "type": "signature", "family": "Lattice (MLWE/MSIS)", | |
| "classical_security_bits": 128, "quantum_security_bits": 128, | |
| "key_size_bytes": 1312, "signature_bytes": 2420, "encap_bytes": 0, | |
| "keygen_us": 80, "sign_us": 200, "verify_us": 80, | |
| "encrypt_us": 0, "decrypt_us": 0, | |
| "nist_level": 2, "quantum_vulnerable": False, | |
| "attack": "No known polynomial quantum attack", | |
| }, | |
| "Dilithium-3": { | |
| "type": "signature", "family": "Lattice (MLWE/MSIS)", | |
| "classical_security_bits": 192, "quantum_security_bits": 192, | |
| "key_size_bytes": 1952, "signature_bytes": 3293, "encap_bytes": 0, | |
| "keygen_us": 120, "sign_us": 300, "verify_us": 110, | |
| "encrypt_us": 0, "decrypt_us": 0, | |
| "nist_level": 3, "quantum_vulnerable": False, | |
| "attack": "No known polynomial quantum attack", | |
| }, | |
| "Dilithium-5": { | |
| "type": "signature", "family": "Lattice (MLWE/MSIS)", | |
| "classical_security_bits": 256, "quantum_security_bits": 256, | |
| "key_size_bytes": 2592, "signature_bytes": 4595, "encap_bytes": 0, | |
| "keygen_us": 180, "sign_us": 450, "verify_us": 160, | |
| "encrypt_us": 0, "decrypt_us": 0, | |
| "nist_level": 5, "quantum_vulnerable": False, | |
| "attack": "No known polynomial quantum attack", | |
| }, | |
| "SPHINCS+-128s": { | |
| "type": "signature", "family": "Hash-based", | |
| "classical_security_bits": 128, "quantum_security_bits": 128, | |
| "key_size_bytes": 64, "signature_bytes": 7856, "encap_bytes": 0, | |
| "keygen_us": 3000, "sign_us": 70000, "verify_us": 3000, | |
| "encrypt_us": 0, "decrypt_us": 0, | |
| "nist_level": 1, "quantum_vulnerable": False, | |
| "attack": "No known polynomial quantum attack; hash-based security", | |
| }, | |
| "SPHINCS+-256": { | |
| "type": "signature", "family": "Hash-based", | |
| "classical_security_bits": 256, "quantum_security_bits": 256, | |
| "key_size_bytes": 128, "signature_bytes": 29792, "encap_bytes": 0, | |
| "keygen_us": 12000, "sign_us": 280000, "verify_us": 12000, | |
| "encrypt_us": 0, "decrypt_us": 0, | |
| "nist_level": 5, "quantum_vulnerable": False, | |
| "attack": "No known polynomial quantum attack; hash-based security", | |
| }, | |
| # βββ NIST FIPS 203: ML-KEM (formerly CRYSTALS-Kyber) βββββββββββββββββ | |
| "ML-KEM-512": { | |
| "type": "KEM", "family": "Lattice (Module-LWE)", | |
| "classical_security_bits": 128, "quantum_security_bits": 128, | |
| "key_size_bytes": 800, "signature_bytes": 0, "encap_bytes": 768, | |
| "keygen_us": 30, "sign_us": 0, "verify_us": 0, | |
| "encrypt_us": 40, "decrypt_us": 30, | |
| "keygen_us_avx2": 14, "encrypt_us_avx2": 18, "decrypt_us_avx2": 14, | |
| "keygen_us_avx512": 8, "encrypt_us_avx512": 10, "decrypt_us_avx512": 7, | |
| "nist_level": 1, "quantum_vulnerable": False, | |
| "standard": "FIPS 203", | |
| "attack": "No known polynomial quantum attack; NIST standardized (FIPS 203)", | |
| }, | |
| "ML-KEM-768": { | |
| "type": "KEM", "family": "Lattice (Module-LWE)", | |
| "classical_security_bits": 192, "quantum_security_bits": 192, | |
| "key_size_bytes": 1184, "signature_bytes": 0, "encap_bytes": 1088, | |
| "keygen_us": 45, "sign_us": 0, "verify_us": 0, | |
| "encrypt_us": 55, "decrypt_us": 45, | |
| "keygen_us_avx2": 22, "encrypt_us_avx2": 26, "decrypt_us_avx2": 21, | |
| "keygen_us_avx512": 12, "encrypt_us_avx512": 14, "decrypt_us_avx512": 11, | |
| "nist_level": 3, "quantum_vulnerable": False, | |
| "standard": "FIPS 203", | |
| "attack": "No known polynomial quantum attack; NIST standardized (FIPS 203)", | |
| }, | |
| "ML-KEM-1024": { | |
| "type": "KEM", "family": "Lattice (Module-LWE)", | |
| "classical_security_bits": 256, "quantum_security_bits": 256, | |
| "key_size_bytes": 1568, "signature_bytes": 0, "encap_bytes": 1568, | |
| "keygen_us": 65, "sign_us": 0, "verify_us": 0, | |
| "encrypt_us": 75, "decrypt_us": 60, | |
| "keygen_us_avx2": 32, "encrypt_us_avx2": 36, "decrypt_us_avx2": 28, | |
| "keygen_us_avx512": 17, "encrypt_us_avx512": 19, "decrypt_us_avx512": 15, | |
| "nist_level": 5, "quantum_vulnerable": False, | |
| "standard": "FIPS 203", | |
| "attack": "No known polynomial quantum attack; NIST standardized (FIPS 203)", | |
| }, | |
| # βββ NIST FIPS 204: ML-DSA (formerly CRYSTALS-Dilithium) βββββββββββββ | |
| "ML-DSA-44": { | |
| "type": "signature", "family": "Lattice (Module-LWE/SIS)", | |
| "classical_security_bits": 128, "quantum_security_bits": 128, | |
| "key_size_bytes": 1312, "signature_bytes": 2420, "encap_bytes": 0, | |
| "keygen_us": 80, "sign_us": 200, "verify_us": 80, | |
| "encrypt_us": 0, "decrypt_us": 0, | |
| "keygen_us_avx2": 38, "sign_us_avx2": 95, "verify_us_avx2": 37, | |
| "keygen_us_avx512": 22, "sign_us_avx512": 55, "verify_us_avx512": 20, | |
| "nist_level": 2, "quantum_vulnerable": False, | |
| "standard": "FIPS 204", | |
| "attack": "No known polynomial quantum attack; NIST standardized (FIPS 204)", | |
| }, | |
| "ML-DSA-65": { | |
| "type": "signature", "family": "Lattice (Module-LWE/SIS)", | |
| "classical_security_bits": 192, "quantum_security_bits": 192, | |
| "key_size_bytes": 1952, "signature_bytes": 3309, "encap_bytes": 0, | |
| "keygen_us": 120, "sign_us": 300, "verify_us": 110, | |
| "encrypt_us": 0, "decrypt_us": 0, | |
| "keygen_us_avx2": 58, "sign_us_avx2": 145, "verify_us_avx2": 52, | |
| "keygen_us_avx512": 32, "sign_us_avx512": 82, "verify_us_avx512": 28, | |
| "nist_level": 3, "quantum_vulnerable": False, | |
| "standard": "FIPS 204", | |
| "attack": "No known polynomial quantum attack; NIST standardized (FIPS 204)", | |
| }, | |
| "ML-DSA-87": { | |
| "type": "signature", "family": "Lattice (Module-LWE/SIS)", | |
| "classical_security_bits": 256, "quantum_security_bits": 256, | |
| "key_size_bytes": 2592, "signature_bytes": 4627, "encap_bytes": 0, | |
| "keygen_us": 180, "sign_us": 450, "verify_us": 160, | |
| "encrypt_us": 0, "decrypt_us": 0, | |
| "keygen_us_avx2": 88, "sign_us_avx2": 218, "verify_us_avx2": 78, | |
| "keygen_us_avx512": 48, "sign_us_avx512": 120, "verify_us_avx512": 42, | |
| "nist_level": 5, "quantum_vulnerable": False, | |
| "standard": "FIPS 204", | |
| "attack": "No known polynomial quantum attack; NIST standardized (FIPS 204)", | |
| }, | |
| # βββ NIST FIPS 205: SLH-DSA (formerly SPHINCS+) ββββββββββββββββββββββ | |
| "SLH-DSA-128s": { | |
| "type": "signature", "family": "Hash-based (Stateless)", | |
| "classical_security_bits": 128, "quantum_security_bits": 128, | |
| "key_size_bytes": 64, "signature_bytes": 7856, "encap_bytes": 0, | |
| "keygen_us": 3000, "sign_us": 70000, "verify_us": 3000, | |
| "encrypt_us": 0, "decrypt_us": 0, | |
| "nist_level": 1, "quantum_vulnerable": False, | |
| "standard": "FIPS 205", | |
| "attack": "No known polynomial quantum attack; NIST standardized (FIPS 205)", | |
| }, | |
| "SLH-DSA-256s": { | |
| "type": "signature", "family": "Hash-based (Stateless)", | |
| "classical_security_bits": 256, "quantum_security_bits": 256, | |
| "key_size_bytes": 128, "signature_bytes": 29792, "encap_bytes": 0, | |
| "keygen_us": 12000, "sign_us": 280000, "verify_us": 12000, | |
| "encrypt_us": 0, "decrypt_us": 0, | |
| "nist_level": 5, "quantum_vulnerable": False, | |
| "standard": "FIPS 205", | |
| "attack": "No known polynomial quantum attack; NIST standardized (FIPS 205)", | |
| }, | |
| } | |
| def compare_pqc(algorithms: list[str], message_size: int): | |
| results = [] | |
| for alg_name in algorithms: | |
| info = PQC_DATABASE.get(alg_name) | |
| if not info: | |
| continue | |
| results.append({"name": alg_name, **info}) | |
| return { | |
| "algorithms": results, | |
| "message_size_bytes": message_size, | |
| "available_algorithms": list(PQC_DATABASE.keys()), | |
| } | |
| # βββ Brute Force Time Estimator βββββββββββββββββββββββββββββββββββββββββββββ | |
| def estimate_brute_force(key_bits: int, algorithm: str): | |
| classical_ops = 2 ** key_bits | |
| grover_ops = 2 ** (key_bits // 2) # Grover quadratic speedup | |
| # Rough estimates: operations per second | |
| classical_rate = 1e12 # 1 THz classical | |
| quantum_rate_current = 1e6 # ~1 MHz current quantum | |
| quantum_rate_future = 1e9 # ~1 GHz projected | |
| classical_seconds = classical_ops / classical_rate | |
| quantum_current_seconds = grover_ops / quantum_rate_current | |
| quantum_future_seconds = grover_ops / quantum_rate_future | |
| def format_time(seconds): | |
| if seconds < 1e-6: | |
| return f"{seconds*1e9:.2f} nanoseconds" | |
| if seconds < 1e-3: | |
| return f"{seconds*1e6:.2f} microseconds" | |
| if seconds < 1: | |
| return f"{seconds*1e3:.2f} milliseconds" | |
| if seconds < 60: | |
| return f"{seconds:.2f} seconds" | |
| if seconds < 3600: | |
| return f"{seconds/60:.2f} minutes" | |
| if seconds < 86400: | |
| return f"{seconds/3600:.2f} hours" | |
| if seconds < 3.156e7: | |
| return f"{seconds/86400:.2f} days" | |
| if seconds < 3.156e10: | |
| return f"{seconds/3.156e7:.2f} years" | |
| if seconds < 3.156e13: | |
| return f"{seconds/3.156e7:.2e} years (thousands)" | |
| return f"{seconds/3.156e7:.2e} years" | |
| return { | |
| "algorithm": algorithm, | |
| "key_bits": key_bits, | |
| "classical_search_space": f"2^{key_bits}", | |
| "grover_search_space": f"2^{key_bits // 2}", | |
| "classical_time": format_time(classical_seconds), | |
| "quantum_current_time": format_time(quantum_current_seconds), | |
| "quantum_future_time": format_time(quantum_future_seconds), | |
| "classical_ops": classical_ops if key_bits <= 64 else f"2^{key_bits}", | |
| "grover_ops": grover_ops if key_bits <= 64 else f"2^{key_bits // 2}", | |
| "quantum_speedup": f"Quadratic: 2^{key_bits} β 2^{key_bits // 2}", | |
| "verdict": "SECURE" if key_bits >= 256 else ("WEAKENED" if key_bits >= 128 else "BROKEN"), | |
| } | |
| # βββ API Endpoints ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ | |
| async def api_grover(req: GroverRequest): | |
| target = req.target_value if req.target_value is not None else random.randint(0, 2**req.search_space_bits - 1) | |
| if target < 0 or target >= 2**req.search_space_bits: | |
| raise HTTPException(400, "target_value out of range") | |
| return simulate_grover(req.search_space_bits, target, req.iterations) | |
| async def api_shor(req: ShorRequest): | |
| if req.number < 6: | |
| raise HTTPException(400, "Number must be >= 6") | |
| return simulate_shor(req.number) | |
| async def api_pqc(req: PQCCompareRequest): | |
| return compare_pqc(req.algorithms, req.message_size_bytes) | |
| async def api_brute(req: BruteForceRequest): | |
| return estimate_brute_force(req.key_bits, req.algorithm) | |
| async def api_avx512(req: AVX512CompareRequest): | |
| """Compare baseline vs AVX2 vs AVX-512 performance for PQC algorithms.""" | |
| results = [] | |
| for alg_name in req.algorithms: | |
| info = PQC_DATABASE.get(alg_name) | |
| if not info: | |
| continue | |
| has_avx = any(k.endswith('_avx512') for k in info) | |
| if not has_avx: | |
| continue | |
| entry = {"name": alg_name, "type": info["type"], "family": info["family"], | |
| "standard": info.get("standard", ""), "nist_level": info.get("nist_level", 0)} | |
| ops = [] | |
| if info["type"] == "signature": | |
| ops = [("keygen", "keygen_us"), ("sign", "sign_us"), ("verify", "verify_us")] | |
| elif info["type"] == "KEM": | |
| ops = [("keygen", "keygen_us"), ("encaps", "encrypt_us"), ("decaps", "decrypt_us")] | |
| perf = [] | |
| for op_label, base_key in ops: | |
| if req.operation != "all" and req.operation != op_label: | |
| continue | |
| baseline = info.get(base_key, 0) | |
| avx2 = info.get(base_key.replace("_us", "_us_avx2"), baseline) | |
| avx512 = info.get(base_key.replace("_us", "_us_avx512"), baseline) | |
| speedup_avx2 = round(baseline / avx2, 2) if avx2 > 0 else 0 | |
| speedup_avx512 = round(baseline / avx512, 2) if avx512 > 0 else 0 | |
| perf.append({ | |
| "operation": op_label, | |
| "baseline_us": baseline, | |
| "avx2_us": avx2, | |
| "avx512_us": avx512, | |
| "speedup_avx2": speedup_avx2, | |
| "speedup_avx512": speedup_avx512, | |
| }) | |
| entry["performance"] = perf | |
| results.append(entry) | |
| avx512_algorithms = [name for name, info in PQC_DATABASE.items() | |
| if any(k.endswith('_avx512') for k in info)] | |
| return {"algorithms": results, "available_algorithms": avx512_algorithms} | |
| async def api_pqc_list(): | |
| return {"algorithms": [ | |
| {"name": name, "standard": info.get("standard", None)} | |
| for name, info in PQC_DATABASE.items() | |
| ]} | |
| # βββ Static Files βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ | |
| BASE_DIR = os.path.dirname(os.path.abspath(__file__)) | |
| STATIC_DIR = os.path.join(BASE_DIR, "static") | |
| app.mount("/static", StaticFiles(directory=STATIC_DIR), name="static") | |
| async def root(): | |
| return FileResponse(os.path.join(STATIC_DIR, "index.html")) | |
| if __name__ == "__main__": | |
| import uvicorn | |
| uvicorn.run(app, host="0.0.0.0", port=7860) | |