# Quantum-Sign 🔐

**The Digital Notary Stamp That Even Quantum Computers Can't Forge**

[![Crates.io](https://img.shields.io/crates/v/quantum-sign)](https://crates.io/crates/quantum-sign)
[![Documentation](https://docs.rs/quantum-sign/badge.svg)](https://docs.rs/quantum-sign)
[![License](https://img.shields.io/crates/l/quantum-sign)](LICENSE)
[![MSRV](https://img.shields.io/badge/MSRV-1.77-blue)](https://rust-lang.org)
[![Security Audit](https://img.shields.io/badge/security-audited-green)](docs/security-requirements.md)

**Simple Answer:** Quantum-Sign is a command-line tool that digitally signs software using quantum-resistant cryptography to prove the software is authentic and hasn't been tampered with.

**Technical Details:** A production-ready, pure-Rust implementation of post-quantum code signing with NIST-approved algorithms. Quantum-Sign provides quantum-resistant digital signatures using ML-DSA-87 (Module-Lattice Digital Signature Algorithm) with support for multi-party quorum signing, offline verification, and comprehensive policy enforcement.

## 🌟 Key Features

- **🛡️ Quantum-Resistant**: Built on FIPS 204 ML-DSA-87, secure against both classical and quantum computers
- **🔒 Pure Rust**: Zero unsafe code, memory-safe implementation with `#![forbid(unsafe_code)]`
- **📦 Supply Chain Security**: Strictly crates.io-only dependencies, no FFI or C libraries
- **✅ Standards Compliant**: Full compliance with NIST FIPS 204/205, SP 800-90A/B/C, SP 800-53
- **👥 Quorum Signing**: M-of-N threshold signatures for critical operations
- **🔍 Offline Verification**: Complete verification without network access
- **📋 Policy Engine**: Comprehensive policy enforcement with FIPS-only defaults
- **🔐 Defense in Depth**: Multiple security layers including domain separation, canonical encoding, and zeroization

## 📚 Table of Contents

- [Installation](#installation)
- [Quick Start](#quick-start)
- [Architecture](#architecture)
- [Usage Guide](#usage-guide)
  - [Basic Signing](#basic-signing)
  - [Quorum Signing](#quorum-signing)
- [Verification](#verification)
- [Trust Management](#trust-management)
- [One‑Shot Packaging](#one-shot-packaging)
- [CLI Reference](docs/CLI.md)
- [Security](#security)
- [Documentation](#documentation)
- [License](#license)

## 🚀 Installation

### As a CLI Tool

```bash
cargo install quantum-sign
```

### As a Library

Add to your `Cargo.toml`:

```toml
[dependencies]
quantum-sign = "0.1.0"
qs-crypto = "0.1.0"
qs-format = "0.1.0"
qs-policy = "0.1.0"
```

### Build from Source

```bash
# Clone from crates.io source
cargo install quantum-sign --git
# Or download source archive from crates.io
cargo build --release
```

## ⚡ Quick Start

### Generate a Signing Key Pair

```bash
quantum-sign keygen \
  --profile mldsa-87 \
  --secret key.sk \
  --public key.pub
```

### Sign a File

```bash
quantum-sign sign \
  --inp document.pdf \
  --sig document.qsig \
  --policy policy.json
```

### Verify a Signature

```bash
quantum-sign verify \
  --inp document.pdf \
  --sig document.qsig \
  --trustdb ./trust
```

## 🏗️ Architecture

Quantum-Sign is structured as a workspace with specialized crates:

| Crate | Purpose | Dependencies |
|-------|---------|--------------|
| `qs-crypto` | Core cryptographic operations | `ml-dsa`, `sha2`, `sha3`, `zeroize` |
| `qs-drbg` | Deterministic random bit generator | `hmac`, `sha2`, `zeroize` |
| `qs-format` | `.qsig` CBOR format handling | `ciborium`, `serde` |
| `qs-policy` | Policy engine and validation | `serde`, `sha2` |
| `qs-cli` | Command-line interface | All above crates |
| `qs-verify` | Standalone verification | `qs-crypto`, `qs-format` |
| `qs-tsp` | RFC 3161 timestamping | Future implementation |
| `qs-transparency` | Transparency log support | Future implementation |

### Cryptographic Flow

```
    File → SHA-512/256 Digest → Policy Binding → ML-DSA-87 Sign → CBOR Encode → .qsig File
```

## 📖 Usage Guide

### Basic Signing

Create a policy file `policy.json`:

```json
{
  "default_alg": "mldsa-87",
  "allow_algs": ["mldsa-87"],
  "require_fips_only": true,
  "require_level5": true,
  "digest_alg": "sha512",
  "offline_ok": true
}
```

Sign with policy enforcement:

```bash
# Generate keys
quantum-sign keygen --secret alice.sk --public alice.pub

# Import public key to trust store
quantum-sign trust import --public alice.pub --trustdb ./trust

# Sign artifact
quantum-sign sign \
  --inp artifact.bin \
  --sig artifact.qsig \
  --policy policy.json
```

### Quorum Signing (M-of-N)

For critical operations requiring multiple approvals:

```json
{
  "default_alg": "mldsa-87",
  "allow_algs": ["mldsa-87"],
  "required_signatures": {"m": 2, "n": 3},
  "digest_alg": "sha512"
}
```

```bash
# Initialize quorum signing
quantum-sign quorum init \
  --artifact critical.bin \
  --policy quorum-policy.json \
  --allowed-kid $KID1 --allowed-kid $KID2 --allowed-kid $KID3

# Each signer creates a fragment
quantum-sign quorum cosign \
  --intent critical.qsi \
  --secret alice.sk --public alice.pub \
  --fragment alice.csf \
  --append critical.qsig.part

quantum-sign quorum cosign \
  --intent critical.qsi \
  --secret bob.sk --public bob.pub \
  --fragment bob.csf \
  --append critical.qsig.part

# Seal into final signature (requires 2 valid signatures)
quantum-sign quorum seal \
  --part critical.qsig.part \
  --out critical.qsig \
  --trust-dir ./trust
```

### Verification

Standard verification:

```bash
quantum-sign verify \
  --inp document.pdf \
  --sig document.qsig \
  --trustdb ./trust
```

JSON output for automation:

```bash
quantum-sign verify \
  --inp document.pdf \
  --sig document.qsig \
  --trustdb ./trust \
  --json
```

Output format:
```json
{
  "status": "ok",
  "alg": "mldsa-87",
  "digest_alg": "sha512",
  "domain": "quantum-sign-v1",
  "canonical": true,
  "m": 2,
  "n": 3,
  "kids_verified": 2,
  "verified_kids": ["abc123...", "def456..."],
  "policy_hash_hex": "...",
  "file_digest_hex": "..."
}
```

### Trust Management

Import and list trusted public keys:

```bash
# Import a public key (PEM or DER format)
quantum-sign trust import --public alice.pub --trustdb ./trust
# Output: imported abc123def456... -> ./trust/abc123def456.spki

# List all trusted keys
quantum-sign trust list --trustdb ./trust

## 🎁 One‑Shot Packaging

Produce a minimal, production‑ready release in a single command. The output contains exactly:

- `<artifact>` (your original file)
- `<artifact>.qsig` (final signature)
- `policy.json` (canonical JSON)
- `trust/<KID>.spki` (SPKI DER of the verifying key)

Nothing else is emitted in the release: no secret keys, `.qsi`, `.qsig.part`, `.csf`, or platform cruft.

```bash
quantum-sign quorum package \
  --artifact ./AnubisQuantumCipher.png \
  --policy ./policy.json \
  --digest sha512 \
  --secret ./keys/sicarii.sk \   # optional; if omitted, an in-memory keypair is used
  --public ./keys/sicarii.vk \   # optional; required if you pass --secret
  --out-dir ./release \          # defaults to ./release
  --zip true                      # creates a zip next to out_dir if 'zip' is available
```

Verify for recipients (one command):

```bash
quantum-sign verify --json \
  --inp ./release/AnubisQuantumCipher.png \
  --sig ./release/AnubisQuantumCipher.qsig \
  --trustdb ./release/trust
```

Expected JSON fields:

- `status: "ok"`, `alg: "mldsa-87"`, `digest_alg: "sha512"`
- `kids_verified: 1`, `m=1`, `n=1`
- `canonical: true`
- `policy_hash_hex` matches your `policy.json`
- `file_digest_hex` matches your artifact

Tip: Embed human owner info in `policy.json` (e.g., `comments: "Owner: <name>"`); the policy’s canonical hash is cryptographically bound into the signature claims.
# Output:
# abc123def456 ./trust/abc123def456.spki
# 789abcdef012 ./trust/789abcdef012.spki
```

## 🔒 Security

### Threat Model

Quantum-Sign defends against:
- **Quantum computer attacks** on signatures
- **Supply chain attacks** via dependency control
- **Downgrade attacks** via policy enforcement
- **Key compromise** via quorum signing
- **Tampering** via canonical encoding
- **Memory disclosure** via zeroization

### Security Features

1. **Cryptographic Security**
   - ML-DSA-87 (NIST Level 5 security)
   - HMAC-DRBG with continuous health tests
   - Constant-time operations
   - Automatic key material zeroization

2. **Implementation Security**
   - Pure Rust, zero unsafe code
   - Memory-safe by construction
   - No FFI or external dependencies
   - Strict input validation

3. **Operational Security**
   - Offline-first verification
   - Policy-bound signatures
   - Audit logging support
   - Reproducible builds

### Compliance

- **FIPS 204**: ML-DSA specification
- **FIPS 205**: SLH-DSA specification
- **SP 800-90A/B/C**: DRBG requirements
- **SP 800-53 Rev.5**: Security controls
- **SP 800-131A**: Algorithm transitions

## 📚 Documentation

### Core Documentation
- Security Requirements - Comprehensive security analysis
- QSig Format Specification - Detached signature format
- [API Documentation](https://docs.rs/quantum-sign) - Rust API reference

### Examples

Example usage patterns:

**Basic Signing**
```rust
use qs_crypto::{keypair_mldsa87, sign_mldsa87, HmacSha512Drbg};
use qs_policy::Policy;

let mut drbg = HmacSha512Drbg::from_os(Some(b"app-context"))?;
let keypair = keypair_mldsa87(&mut drbg)?;
// Sign with policy binding...
```

**Custom Policy**
```rust
use qs_policy::{Policy, RequiredSignatures};

let policy = Policy {
    default_alg: "mldsa-87".into(),
    allow_algs: vec!["mldsa-87".into()],
    required_signatures: Some(RequiredSignatures { m: 2, n: 3 }),
    require_fips_only: true,
    require_level5: true,
    digest_alg: "sha512".into(),
    ..Default::default()
};
```

### Performance

On Apple M1/M2:
- Key generation: ~2ms
- Signing (SHA-512): ~3ms
- Verification: ~2ms
- Quorum seal (3 signatures): ~7ms

## 🤝 Development

```bash
# Run tests
cargo test --workspace --all-features

# Format code
cargo fmt --all

# Lint
cargo clippy --all-targets --all-features -- -D warnings

# Security audit
cargo audit
cargo deny check

# Build documentation
cargo doc --no-deps --open
```

## 📜 License

Licensed under either of:

- Apache License, Version 2.0 (LICENSE-APACHE)
- MIT License (LICENSE-MIT)

at your option.

## 🙏 Acknowledgments

- NIST PQC team for ML-DSA specification
- Rust Crypto community for foundational libraries
- Security researchers and contributors

## ⚠️ Security Warning

This is cryptographic software. While we've taken extensive precautions:
- Always use the latest version
- Review security advisories on crates.io
- Test thoroughly in your environment
- Consider professional security audit for critical uses

## 📞 Contact

- **Author**: Sicarii
- **Email**: sic.tau@pm.me
- **Crates.io**: [quantum-sign](https://crates.io/crates/quantum-sign)

For security issues, please email sic.tau@pm.me with subject line "[SECURITY] Quantum-Sign".

---

*Building quantum-resistant security for the classical world* 🔐
