Metadata-Version: 2.4
Name: sqrypt-cyber-sdk
Version: 3.0.2
Summary: Enterprise Post-Quantum Cybersecurity SDK and CBOM Auditing Suite
Author: Aryan Sujay
License: MIT
Classifier: Programming Language :: Python :: 3
Classifier: Topic :: Security :: Cryptography
Classifier: Environment :: Console
Requires-Python: >=3.8
Description-Content-Type: text/markdown
License-File: LICENSE
Requires-Dist: cryptography>=42.0.0
Requires-Dist: requests>=2.31.0
Requires-Dist: fpdf==1.7.2
Requires-Dist: tqdm>=4.66.0
Requires-Dist: rich>=13.0.0
Dynamic: license-file

<div align="center">

# SQrypt

**Post-Quantum Cryptographic Security Suite**

*Hybrid encryption SDK + Cryptographic Bill of Materials (CBOM) auditing engine, built for the "Harvest Now, Decrypt Later" threat era*

[![License: MIT](https://img.shields.io/badge/License-MIT-blue.svg)](LICENSE)
[![Python](https://img.shields.io/badge/python-3.8%2B-blue.svg)](pyproject.toml)
[![NIST FIPS 203](https://img.shields.io/badge/NIST-FIPS%20203%20%28ML--KEM%29-informational)](#cryptographic-design)
[![PyPI](https://img.shields.io/pypi/v/sqrypt-cyber-sdk.svg)](https://pypi.org/project/sqrypt-cyber-sdk/)
[![Status](https://img.shields.io/badge/status-beta-green.svg)](#project-status)

</div>

---

## Overview

SQrypt is a two-part cybersecurity suite helping organizations prepare for the post-quantum transition:

| Component | Purpose |
|---|---|
| **SQrypt SDK** | Client SDK + hosted Key Management Service (KMS) implementing hybrid classical/post-quantum encryption (X25519 + ML-KEM-768). All cryptographic key operations happen server-side — key material never leaves the KMS. |
| **SQrypt CLI Scanner** | Static-analysis engine that scans source code for legacy, quantum-vulnerable cryptography (RSA, ECC/ECDSA, Diffie-Hellman, weak hashes) and generates audit-ready CBOM, JSON, and PDF reports. |

Together, these let a team both **assess** their current cryptographic exposure and **remediate** it by integrating quantum-resistant encryption directly into their applications.

---

## Quickstart

### Hosted KMS (No server setup required)

```bash
pip install sqrypt-cyber-sdk
```

```python
from sqrypt.client import SQryptClient

client = SQryptClient(
    server_url="https://sqrypt-kms.onrender.com",
    api_key="YOUR_API_KEY"
)

payload  = client.encrypt("sensitive customer data")
original = client.decrypt(payload)
```

> Request API access: open an issue or contact the maintainer directly.

### CLI Scanner (Free, no API key required)

```bash
pip install "sqrypt-cyber-sdk[cli]"
sqrypt --target /path/to/your/codebase --pdf
```

---

## Why SQrypt

Cryptographically Relevant Quantum Computers (CRQCs) threaten to break RSA, ECC, and Diffie-Hellman via Shor's algorithm. Adversaries are already harvesting encrypted traffic today to decrypt once such hardware exists — the "Harvest Now, Decrypt Later" attack. NIST formalized post-quantum replacements in **FIPS 203 (ML-KEM)** and **FIPS 204 (ML-DSA)**. SQrypt operationalizes this transition by:

- Surfacing every line of code that still relies on Shor-vulnerable primitives, with file and line-level evidence.
- Scoring and reporting risk in a format suitable for security and compliance review (CBOM).
- Providing a drop-in hybrid encryption client so engineering teams can migrate without redesigning their key exchange from scratch.

---

## Architecture

```
┌─────────────────────────────┐        ┌──────────────────────────────────┐
│        SQrypt SDK            │        │       SQrypt CLI Scanner          │
│    (sqrypt/client.py)        │        │     (sqrypt/cli/scanner.py)       │
│                              │        │                                    │
│  SQryptClient                │        │  CodebaseQuantumScanner            │
│   - encrypt(plaintext)       │        │   - AST-based Python analysis      │
│   - decrypt(payload)         │        │   - Regex multi-language analysis  │
│   - auto_encrypt() decorator │        │     (JS/TS/Java/C/C++/C#/Go/PHP)  │
│   - protect_dict()           │        │   - Parallel scanning              │
└──────────┬───────────────────┘        │     (ProcessPoolExecutor)          │
           │ HTTPS + X-SQrypt-Key       │   - Risk scoring engine            │
           │ base64(plaintext)          │   - CBOM / JSON / PDF export       │
           ▼                            └──────────────────────────────────┘
┌──────────────────────────────┐
│      SQrypt KMS Server        │
│   (kms-server/server.py)     │
│   FastAPI + Gunicorn          │
│   Deployed: Render            │
│   Persistence: Redis + KEK    │
│                               │
│  POST /v2/encrypt             │  ← Receives plaintext, returns ciphertext
│  POST /v2/decrypt             │  ← Receives ciphertext, returns plaintext
│  GET  /v2/public-keys         │  ← Returns tenant PQC + X25519 public keys
│  GET  /healthz                │  ← Liveness probe
│                               │
│  Per-tenant ML-KEM-768 +      │
│  X25519 keypairs              │
│  Encrypted at rest (KEK)      │
│  Structured JSON audit log    │
│  Rate limited (60 req/min)    │
└──────────────────────────────┘
```

---

## Cryptographic Design

SQrypt uses a **server-side hybrid key encapsulation** scheme so that confidentiality is preserved even if either the classical or post-quantum primitive is later broken. Critically, **raw key material never leaves the KMS at any point** — neither during encryption nor decryption.

### Encryption flow

1. Client sends `base64(plaintext)` to `POST /v2/encrypt`.
2. KMS generates an ephemeral X25519 keypair for this operation.
3. KMS runs ML-KEM-768 encapsulation using the tenant's long-term PQC public key → produces `pqc_secret` + `pqc_capsule`.
4. KMS computes X25519 shared secret: `kms_ephemeral_private × tenant_x25519_public`.
5. KMS derives a 256-bit AES key via HKDF-SHA256 over `classical_secret || pqc_secret`.
6. KMS encrypts with AES-256-GCM, deletes the key, returns `{ciphertext, nonce, pqc_capsule, kms_x25519_ephemeral_pub}`.

### Decryption flow

1. Client sends the ciphertext envelope to `POST /v2/decrypt`.
2. KMS runs ML-KEM-768 decapsulation using the tenant's long-term PQC private key → recovers `pqc_secret`.
3. KMS computes X25519 shared secret: `tenant_x25519_private × kms_x25519_ephemeral_pub`.
4. KMS re-derives the AES key via HKDF-SHA256, decrypts, deletes the key, returns `base64(plaintext)`.

At no point is the AES key, or either shared secret, transmitted over the wire. The ciphertext envelope (`ciphertext`, `nonce`, `pqc_capsule`, `kms_x25519_pub`) contains no key material and is safe to store in a database.

> **Why hybrid?** If ML-KEM-768 were ever found to be weak, X25519 still provides a classical security floor. If X25519 is broken by a CRQC, ML-KEM-768 provides the post-quantum floor. Both must be broken simultaneously to compromise a payload.

---

## KMS Security Model

| Property | Implementation |
|---|---|
| Key material never exported | All AES-GCM operations are server-side |
| Keys encrypted at rest | AES-256-GCM under a Master KEK (env var) |
| Persistence across restarts | Redis with AOF persistence |
| Per-tenant isolation | Separate ML-KEM-768 + X25519 keypair per API key |
| Audit trail | Structured JSON log per operation (tenant, request ID, timestamp, status) |
| Rate limiting | 60 encrypt + 60 decrypt calls per tenant per minute |
| Input validation | Capsule length (1088B), nonce length (12B), X25519 key length (32B) enforced |
| Authentication | `X-SQrypt-Key` header, per-tenant registry in Redis |

---

## Installation

### SDK only (minimal dependencies)

```bash
pip install sqrypt-cyber-sdk
```

Dependencies: `cryptography>=42.0.0`, `requests>=2.31.0`

### SDK + CLI Scanner

```bash
pip install "sqrypt-cyber-sdk[cli]"
```

Additional dependencies: `fpdf==1.7.2`, `tqdm>=4.66.0`, `rich>=13.0.0`

### KMS Server (self-hosted)

```bash
# Requires Docker
docker compose up --build
```

Set the required environment variable before starting:
```bash
# Generate a 32-byte master KEK
python -c "import os, base64; print(base64.b64encode(os.urandom(32)).decode())"

# Set in your environment
SQRYPT_MASTER_KEK=<generated value>
SQRYPT_REDIS_URL=redis://localhost:6379/0
```

---

## Usage

### 1. CLI Scanner — Auditing a Codebase

```bash
# Basic scan with console summary
sqrypt --target /path/to/codebase

# Generate a branded PDF audit report
sqrypt --target /path/to/codebase --pdf

# Export a NIST-aligned Cryptographic Bill of Materials
sqrypt --target /path/to/codebase --cbom cbom_report.json

# Export raw findings as JSON
sqrypt --target /path/to/codebase --output-json findings.json
```

| Flag | Description |
|---|---|
| `-t`, `--target` | **(Required)** Path to the codebase to scan |
| `-p`, `--pdf` | Generate a formatted PDF audit report |
| `-c`, `--cbom` | Export a CBOM JSON file |
| `-j`, `--output-json` | Save raw findings to JSON |

**Detection coverage:**

| Category | Risk | Languages |
|---|---|---|
| RSA | Shor-vulnerable | Python (AST), JS/TS/Java/C/C++/C#/Go/PHP |
| ECC / ECDSA | Shor-vulnerable | Python (AST), JS/TS/Java/C/C++/C#/Go/PHP |
| Diffie-Hellman | Shor-vulnerable | Python (AST), JS/TS/Java/C/C++/C#/Go/PHP |
| Legacy Hashes (MD5, SHA-1, SHA-224) | Deprecated | Python (AST), JS/TS/Java/C/C++/C#/Go/PHP |
| Classical Hybrid (X25519, Ed25519) | Informational | All — not flagged as risk when paired with PQC |
| PQC Core (ML-KEM, ML-DSA, Kyber, SQrypt) | Quantum-resistant | All |

Python files use AST parsing for precise call-site tracking including import aliasing. All other languages use comment-aware regex matching. Scanning is parallelized via `ProcessPoolExecutor` with live `tqdm` progress.

### 2. SDK — Encrypting Application Data

```python
from sqrypt.client import SQryptClient

client = SQryptClient(
    server_url="https://sqrypt-kms.onrender.com",
    api_key="YOUR_API_KEY"
)

# Basic encrypt / decrypt
payload  = client.encrypt("sensitive customer data")
original = client.decrypt(payload)

# payload.to_dict() is JSON-serializable — safe to store in a database
import json
stored = json.dumps(payload.to_dict())
recovered = client.decrypt(json.loads(stored))
```

**Decorator-based encryption:**

```python
@client.auto_encrypt()
def get_card_number(user_id: str) -> str:
    return db.fetch_card(user_id)

payload = get_card_number("usr_001")   # returns SQryptPayload, not plaintext
```

**Selective field encryption in a dictionary:**

```python
record = {
    "account_id": "acc_001",
    "status":     "active",
    "tax_id":     "999-12-3456",      # sensitive
    "card_data":  "4111-1111-1111-1111"  # sensitive
}

protected = client.protect_dict(record, sensitive_keys=["tax_id", "card_data"])
# protected["account_id"] and protected["status"] are untouched
# protected["tax_id"] and protected["card_data"] are SQryptPayload dicts
```

### 3. KMS Server — Tenant Management

Add new tenants without redeploying:

```bash
python admin.py create-tenant "FinCorp Ltd"
# → API Key: SQ-abc123...

python admin.py list-tenants

python admin.py revoke-tenant SQ-abc123...
```

---

## Repository Structure

```
SQrypt_Cyber_SDK/
├── sqrypt/
│   ├── client.py              # SQryptClient — SDK
│   └── cli/
│       ├── main.py            # CLI entry point
│       ├── scanner.py         # AST + regex scanning engine
│       └── static/            # Branding assets for PDF reports
├── kms-server/
│   └── server.py              # FastAPI KMS: server-side encrypt/decrypt
├── admin.py                   # Tenant management CLI
├── Dockerfile                 # KMS container build
├── docker-compose.yml         # KMS + Redis orchestration
├── render.yaml                # Render Blueprint (KMS + Redis)
├── pyproject.toml             # Package metadata
├── requirements.txt           # KMS server dependencies
└── test_sdk.py                # Integration test suite
```

---

## Dependencies

**SDK** (base install): `cryptography>=42.0.0`, `requests>=2.31.0`

**CLI Scanner** (`[cli]` extra): `fpdf==1.7.2`, `tqdm>=4.66.0`, `rich>=13.0.0`

**KMS Server**: `fastapi`, `pydantic>=2.0`, `uvicorn`, `gunicorn`, `kyber-py`, `cryptography`, `redis`, `slowapi`

---

## Project Status

SQrypt is a **beta** project under active development. The current build (`v3.0.1`) is deployed and functional:

- ✅ Hosted KMS live at `https://sqrypt-kms.onrender.com`
- ✅ PyPI package: `pip install sqrypt-cyber-sdk`
- ✅ Redis-backed key persistence with KEK encryption at rest
- ✅ Per-tenant key isolation
- ✅ Structured audit logging and rate limiting
- ✅ Server-side encrypt/decrypt (key material never exported)

Before compliance-critical or high-volume production deployment, teams should:

- Conduct an independent security review of the hybrid KEM implementation
- Evaluate `liboqs-python` (C bindings) as a replacement for `kyber-py` (pure Python) for performance at scale
- Deploy a dedicated KMS instance rather than the shared hosted service

---

## Roadmap

- ML-DSA (FIPS 204) digital signature support alongside existing ML-KEM encryption
- `liboqs-python` backend swap for production-grade PQC performance
- Key rotation and revocation endpoints
- Expanded CLI scanner language coverage (Rust, Ruby, Kotlin, Swift, Scala)
- HSM / cloud KMS (AWS KMS, Azure Key Vault) integration for master KEK storage
- SDK packages for Node.js and Java

---

## Contributing

Issues and pull requests are welcome. Please open an issue describing the proposed change before submitting larger contributions, and include test coverage for any new detection signatures or SDK behavior.

---

## License

Released under the [MIT License](LICENSE).

Copyright (c) 2026 Aryan Sujay
