Metadata-Version: 2.4
Name: sqrypt-cyber-sdk
Version: 3.0.3
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
Provides-Extra: cli
Requires-Dist: fpdf==1.7.2; extra == "cli"
Requires-Dist: tqdm>=4.66.0; extra == "cli"
Requires-Dist: rich>=13.0.0; extra == "cli"
Provides-Extra: all
Requires-Dist: sqrypt-cyber-sdk[cli]; extra == "all"
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 + 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.

### Deployment options

The same KMS runs in two modes. The SDK is identical in both; only `server_url` changes.

| | Hosted (cloud) | Self-hosted (Docker) |
|---|---|---|
| Who runs the KMS | SQrypt | You, on your own servers |
| Setup | Request an API key | `docker compose up` |
| Key custody | SQrypt-operated KMS (trusted third party, not zero-knowledge) | Entirely inside your infrastructure |
| Tenant management | Managed by SQrypt | You, via `admin.py` |
| Best for | Pilots, evaluation, fast start | Data-residency and compliance-sensitive workloads |

---

## Quickstart

### Hosted KMS (no server setup)

```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:** [sqrypt.io](https://sqrypt.io) or aryansujay@sqrypt.io. Keys are issued manually during the beta.

### Self-hosted KMS (Docker)

```bash
cp .env.example .env
# edit .env and set SQRYPT_MASTER_KEK and SQRYPT_ADMIN_KEY (see Self-Hosting below)
docker compose up -d --build
python admin.py create-tenant "My Org"     # prints your API key
```

Then point the SDK at `http://localhost:8500` (or wherever you deploy it).

### 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          │
│   Hosted (Render) or Docker   │
│   Persistence: Redis + KEK    │
│                               │
│  Tenant endpoints             │
│  POST /v2/encrypt             │  ← plaintext in, ciphertext envelope out
│  POST /v2/decrypt             │  ← ciphertext envelope in, plaintext out
│  GET  /v2/public-keys         │  ← tenant PQC + X25519 public keys
│  GET  /healthz                │  ← liveness probe
│                               │
│  Admin endpoints              │
│  POST /admin/create-tenant    │  ← X-SQrypt-Admin header required
│  GET  /admin/tenants          │
│  POST /admin/revoke-tenant    │
│  GET  /admin/tenant-usage/{id}│
│                               │
│  Per-tenant ML-KEM-768 +      │
│  X25519 keypairs              │
│  Encrypted at rest (KEK)      │
│  Structured JSON audit log    │
│  Rate limited per API key     │
└──────────────────────────────┘
```

---

## 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. **Raw key material never leaves the KMS** — 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.

> **Trust model:** the KMS is a custodial, trusted third party. The server sees plaintext during encrypt and decrypt, so SQrypt is not zero-knowledge. Self-hosting keeps that trust boundary inside your own infrastructure.

---

## 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 (self-hosted compose); use a persistent Redis plan when hosting elsewhere |
| 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 minute, **keyed per API key** so tenants behind a shared proxy do not share a quota |
| Input validation | Capsule length (1088B), nonce length (12B), X25519 key length (32B) enforced; 10 MB request cap enforced at the HTTP layer |
| Tenant authentication | `X-SQrypt-Key` header, per-tenant registry in Redis |
| Admin authentication | Separate `X-SQrypt-Admin` header, constant-time comparison, minimum 32 characters enforced at boot |
| Secrets in transit | Tenant API keys are sent in request bodies for admin operations, never in query strings |
| Attack surface | Swagger / ReDoc UIs disabled; server refuses to boot without `SQRYPT_MASTER_KEK` and `SQRYPT_ADMIN_KEY` |

---

## 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`

---

## Self-Hosting the KMS

### Requirements

- Docker with Docker Compose
- Python 3.11+ only if you run `admin.py` outside Docker

### 1. Configure

```bash
cp .env.example .env
```

Generate and fill in the two required secrets:

```bash
# Master KEK: encrypts all tenant private keys at rest
python -c "import os, base64; print(base64.b64encode(os.urandom(32)).decode())"

# Admin key: protects /admin/* endpoints (minimum 32 characters)
python -c "import secrets; print('SQADMIN-' + secrets.token_urlsafe(32))"
```

| Variable | Required | Purpose |
|---|---|---|
| `SQRYPT_MASTER_KEK` | Yes | Base64-encoded 32-byte key. **If lost, every tenant keypair becomes unrecoverable. Back it up in a secret manager.** |
| `SQRYPT_ADMIN_KEY` | Yes | Admin API key, 32+ characters. Rotate independently of the KEK. |
| `SQRYPT_REDIS_URL` | No | Defaults to the bundled Redis container. Override to use an external Redis. |

Never commit `.env`. It is listed in `.gitignore`.

### 2. Start

```bash
docker compose up -d --build
curl http://localhost:8500/healthz
```

The KMS listens on port `8500`. Redis data persists in the `redis_data` Docker volume. Redis is bound to `127.0.0.1` only and is not reachable from outside the host.

> Put the KMS behind a TLS-terminating reverse proxy (nginx, Caddy, a cloud load balancer) before exposing it beyond localhost.

### 3. Create a tenant

```bash
python admin.py create-tenant "Acme Corp"
# → Tenant ID: tenant_...
# → API Key:   SQ-...      (shown once; store it securely)
```

### 4. Use it

```python
client = SQryptClient(server_url="http://localhost:8500", api_key="SQ-...")
```

### 5. Verify

```bash
export SQRYPT_TEST_API_KEY=SQ-...
python test_sdk.py
```

The suite runs encrypt/decrypt round-trips, the decorator and dictionary helpers, and a tamper-detection check against your KMS.

---

## 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",   # or your self-hosted URL
    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. Tenant Management

`admin.py` picks its mode automatically.

**Self-hosted (direct Redis).** Used when `SQRYPT_KMS_URL` is not set:

```bash
export SQRYPT_REDIS_URL=redis://localhost:6380/0   # host port mapped by docker-compose
python admin.py create-tenant "FinCorp Ltd"
python admin.py list-tenants
python admin.py revoke-tenant SQ-abc123...
python admin.py tenant-usage tenant_abc123...
```

**Remote (HTTP).** Used when `SQRYPT_KMS_URL` is set. Talks to the admin endpoints, so Redis never needs to be reachable:

```bash
export SQRYPT_KMS_URL=https://your-kms.example.com
export SQRYPT_ADMIN_KEY=SQADMIN-...
python admin.py create-tenant "FinCorp Ltd"
python admin.py list-tenants
```

Every command prints which mode and target it is using on its first line. Check it before running anything that writes.

Revocation takes effect immediately; no restart is needed.

### 4. Admin API

All admin endpoints require the `X-SQrypt-Admin: <SQRYPT_ADMIN_KEY>` header.

| Method | Path | Body | Description |
|---|---|---|---|
| `POST` | `/admin/create-tenant` | `{"name": "Acme"}` | Create a tenant; returns the API key once |
| `GET` | `/admin/tenants` | — | List tenants (API keys are never returned) |
| `POST` | `/admin/revoke-tenant` | `{"api_key": "SQ-..."}` | Revoke an API key |
| `GET` | `/admin/tenant-usage/{tenant_id}` | — | Encrypt/decrypt counters and last-used time |

```bash
curl -X POST https://your-kms.example.com/admin/create-tenant \
  -H "X-SQrypt-Admin: $SQRYPT_ADMIN_KEY" \
  -H "Content-Type: application/json" \
  -d '{"name": "Acme Corp"}'
```

---

## 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: encrypt/decrypt + admin API
├── admin.py                   # Tenant management CLI (Redis or HTTP mode)
├── Dockerfile                 # KMS container build
├── docker-compose.yml         # KMS + Redis stack for self-hosting
├── .env.example               # Configuration template
├── render.yaml                # Render Blueprint (hosted deployment)
├── 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`, `python-dotenv`

The SDK supports Python 3.8+. The KMS server and `admin.py` require Python 3.11+ (the Docker image uses 3.11).

---

## Project Status

SQrypt is a **beta** project under active development. Server `v3.1.0` and SDK `v3.0.1` are deployed and functional:

- ✅ Hosted KMS at `https://sqrypt-kms.onrender.com`
- ✅ Self-hosted deployment via Docker Compose
- ✅ PyPI package: `pip install sqrypt-cyber-sdk`
- ✅ Redis-backed key persistence with KEK encryption at rest
- ✅ Per-tenant key isolation and per-tenant rate limiting
- ✅ Admin API for tenant provisioning, revocation and usage
- ✅ Structured audit logging
- ✅ Server-side encrypt/decrypt (key material never exported)

**The hosted service is for evaluation and sandbox pilots on non-production data.** It runs on shared, small-tier infrastructure with no durability or uptime guarantee. Before compliance-critical or high-volume production use, teams should:

- Self-host, or use a dedicated KMS instance, with a persistent, backed-up Redis
- Back up `SQRYPT_MASTER_KEK` in a secret manager; losing it makes stored keys unrecoverable
- 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

---

## Roadmap

- ML-DSA (FIPS 204) digital signature support alongside existing ML-KEM encryption
- `liboqs-python` backend swap for production-grade PQC performance
- Master KEK rotation and per-tenant key rotation
- Expanded CLI scanner language coverage (Rust, Ruby, Kotlin, Swift, Scala)
- HSM / cloud KMS (AWS KMS, Azure Key Vault) integration for master KEK storage
- Terms of Service and Data Processing Agreement for hosted customers
- 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.

---

## Contact

[sqrypt.io](https://sqrypt.io) · aryansujay@sqrypt.io

---

## License

Released under the [MIT License](LICENSE).

Copyright (c) 2026 Aryan Sujay
