> For the complete documentation index, see [llms.txt](https://cryptic-documentation.gitbook.io/cryptic-pq/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://cryptic-documentation.gitbook.io/cryptic-pq/crytic-enterprise-whitepaper/3.-technical-implementation.md).

# 3. Technical Implementation

#### 3.1 Post-Quantum Algorithms

**Dilithium3 (Digital Signatures)**

**Specification**: NIST FIPS 204 (ML-DSA-65)

{% @mermaid/diagram content="sequenceDiagram
participant User
participant API
participant TEE as TEE (Cryptic)
participant PQC as Dilithium3 Engine
participant Storage

```
Note over User,Storage: Key Generation Flow
User->>API: POST /keys/dilithium3/generate
API->>TEE: Authenticate & authorize
TEE->>PQC: Generate key pair
PQC->>PQC: ML-DSA-65 KeyGen
PQC-->>TEE: Private key (4KB) + Public key (2KB)
TEE->>Storage: Store encrypted private key
TEE-->>API: Return public key + key_id
API-->>User: { key_id, public_key }

Note over User,Storage: Signing Flow
User->>API: POST /keys/{key_id}/sign<br/>{ message }
API->>TEE: Authenticate & authorize
TEE->>Storage: Retrieve encrypted private key
Storage-->>TEE: Encrypted private key
TEE->>TEE: Decrypt private key
TEE->>PQC: Sign(private_key, message)
PQC->>PQC: ML-DSA-65 Sign<br/>(~2.5ms)
PQC-->>TEE: Signature (3.3KB)
TEE->>TEE: Zero private key from memory
TEE-->>API: Return signature
API-->>User: { signature }

Note over User: User can verify signature<br/>with public key offline" %}
```

**Parameters:**

* Public key: 1,952 bytes
* Private key: 4,000 bytes
* Signature: 3,293 bytes
* Security level: NIST Level 3 (comparable to AES-192)

**Performance** (Apple M1, single-core):

* Key generation: \~1.2ms
* Signing: \~2.5ms
* Verification: \~1.0ms

**Use Cases:**

* Document signing
* Certificate authorities
* Code signing
* Blockchain transaction signing

**Kyber768 (Key Encapsulation)**

**Specification**: NIST FIPS 203 (ML-KEM-768)

**Parameters:**

* Public key: 1,184 bytes
* Private key: 2,400 bytes
* Ciphertext: 1,088 bytes
* Shared secret: 32 bytes
* Security level: NIST Level 3

**Performance** (Apple M1, single-core):

* Key generation: \~0.8ms
* Encapsulation: \~1.0ms
* Decapsulation: \~1.2ms

**Use Cases:**

* TLS 1.3 post-quantum handshakes
* Secure messaging
* Encrypted storage
* VPN key exchange

#### 3.2 API Design

**Authentication**

{% @mermaid/diagram content="sequenceDiagram
participant Client
participant Gateway as API Gateway
participant Auth as Auth Middleware
participant RateLimit as Rate Limiter
participant Crypto as Crypto Core

```
alt JWT Authentication
    Client->>Gateway: Request + JWT Token
    Gateway->>Auth: Validate JWT
    Auth->>Auth: Check signature & expiration
    Auth-->>Gateway: ✅ Valid (owner extracted)
end

alt Chain Signature Authentication
    Client->>Gateway: Request + Chain Signature
    Gateway->>Auth: Verify signature
    Auth->>Auth: Recover address from signature
    Auth-->>Gateway: ✅ Valid (address = owner)
end

alt Development Mode (Testing Only)
    Client->>Gateway: Request + Owner Header
    Gateway->>Auth: Check dev mode enabled
    Auth-->>Gateway: ⚠️ Valid (dev only!)
end

Gateway->>RateLimit: Check rate limit for owner
RateLimit-->>Gateway: ✅ Within limits
Gateway->>Crypto: Execute crypto operation
Crypto-->>Gateway: Result
Gateway-->>Client: Response + Audit Log

Note over Auth,RateLimit: All auth modes enforce<br/>same rate limits & audit" %}
```

**Multi-modal authentication** supports diverse use cases:

1. **JWT (OAuth 2.0 / OIDC)**
   * Enterprise integration
   * Web applications
   * Mobile apps
2. **Chain Signature (Web3)**
   * Ethereum (ECDSA)
   * Cosmos (Secp256k1)
   * Solana (Ed25519)
3. **Development Mode**
   * Owner header for testing
   * Disabled in production

**Endpoints**

**Key Generation:**

```http
POST /api/v1/keys/{algorithm}/generate
Authorization: Bearer <jwt> or Signature <chain-sig>
Content-Type: application/json

{
  "purpose": "document-signing",
  "mode": "session",      // session, derived, time-limited, cloudhsm
  "ttl": "3600"           // seconds (for time-limited mode)
}

Response:
{
  "key_id": "key_a7b8c9d0...",
  "public_key": "base64-encoded-public-key",
  "algorithm": "dilithium3",
  "mode": "session",
  "created_at": "2026-01-07T12:00:00Z",
  "expires_at": "2026-01-07T13:00:00Z"
}
```

**Digital Signing:**

```http
POST /api/v1/keys/{key_id}/sign
Authorization: Bearer <jwt>
Content-Type: application/json

{
  "message": "base64-encoded-message"
}

Response:
{
  "signature": "base64-encoded-signature",
  "algorithm": "dilithium3",
  "key_id": "key_a7b8c9d0...",
  "timestamp": "2026-01-07T12:01:00Z"
}
```

**Key Encapsulation:**

```http
POST /api/v1/keys/{key_id}/encapsulate
Authorization: Bearer <jwt>

Response:
{
  "ciphertext": "base64-encoded-ciphertext",
  "shared_secret": "base64-encoded-32-byte-secret"
}
```

**Full API docs coming - This is a high-level whitepaper.**&#x20;

#### 3.3 Key Management Modes

{% @mermaid/diagram content="graph TD
Request\[User Request]

```
Request --> Choice{Choose Mode}

Choice -->|Default| Session[Session Mode]
Choice -->|Stateless| Derived[Derived Mode]
Choice -->|Certificates| TimeLimited[Time-Limited Mode]
Choice -->|Compliance| HSM[CloudHSM Mode<br/>Phase 2]

Session --> S1[Generate in RAM]
S1 --> S2[Use for 1 hour]
S2 --> S3[Auto-expire]
S3 --> S4[Zero memory]
S4 --> S5[❌ Never touches disk]

Derived --> D1[Derive from master seed]
D1 --> D2[Use for operation]
D2 --> D3[Discard]
D3 --> D4[Re-derive if needed]
D4 --> D5[❌ Never stored]

TimeLimited --> T1[Generate & encrypt]
T1 --> T2[Store with TTL]
T2 --> T3[Use within TTL]
T3 --> T4[Auto-delete after 30d]
T4 --> T5[⚠️ Temporarily stored]

HSM --> H1[Generate in HSM hardware]
H1 --> H2[Key never leaves HSM]
H2 --> H3[Sign/Encrypt in hardware]
H3 --> H4[FIPS 140-2 L3 certified]
H4 --> H5[✅ Maximum security]

style Session fill:#c8e6c9,stroke:#2e7d32
style Derived fill:#fff9c4,stroke:#f57f17
style TimeLimited fill:#ffccbc,stroke:#d84315
style HSM fill:#e1bee7,stroke:#6a1b9a,stroke-dasharray: 5 5" %}
```

**Mode 1: Session Keys (Default)**

**Design Philosophy**: Keys that never touch persistent storage

```go
// Keys stored in memory only
type SessionKey struct {
    PrivateKey []byte
    PublicKey  []byte
    CreatedAt  time.Time
    ExpiresAt  time.Time // Auto-expire after 1 hour
}

// Automatic cleanup on expiration
func CleanupExpiredKeys() {
    for _, key := range sessions {
        if time.Now().After(key.ExpiresAt) {
            // Zero memory before deletion
            for i := range key.PrivateKey {
                key.PrivateKey[i] = 0
            }
            delete(sessions, key.ID)
        }
    }
}
```

**Benefits:**

* ✅ Zero persistence risk
* ✅ Automatic expiration
* ✅ Memory zeroed on cleanup
* ✅ Perfect for short-lived operations

**Use Cases:**

* Real-time signing
* API authentication
* Temporary credentials
* Development/testing

**Mode 2: Derived Keys**

**Design Philosophy**: Deterministic key generation from master seed

```go
// Never store keys - derive on demand
func DeriveKey(masterSeed, keyID, userID []byte) []byte {
    // HKDF: Deterministic key derivation
    ikm := append(masterSeed, keyID...)
    ikm = append(ikm, userID...)
    
    // Same inputs = same key (reproducible)
    return hkdf.Expand(ikm, 32, "dilithium3-private-key")
}
```

**Benefits:**

* ✅ Stateless (no storage needed)
* ✅ Reproducible keys
* ✅ Master seed rotation possible
* ✅ Scales infinitely

**Use Cases:**

* Deterministic wallets
* Backup-less key recovery
* Multi-device sync

**Mode 3: Time-Limited Keys**

**Design Philosophy**: Persistent keys with automatic expiration

```go
type TimeLimitedKey struct {
    KeyID      string
    PrivateKey []byte
    ExpiresAt  time.Time
    TTL        time.Duration // e.g., 30 days
}

// Auto-delete after TTL
time.AfterFunc(key.TTL, func() {
    SecureDelete(key.KeyID)
})
```

**Benefits:**

* ✅ Survives restarts
* ✅ Automatic cleanup
* ✅ Configurable lifetime
* ✅ Best-effort secure deletion

**Use Cases:**

* Certificates
* Temporary access tokens
* Audit-required operations

**Mode 4: CloudHSM Keys (Phase 2)**

**Design Philosophy**: Hardware-isolated key storage with FIPS certification

```
Client Request
    ↓
Cryptic Service (TEE)
    ↓ PKCS#11 API
AWS CloudHSM Cluster
    ↓
Private key INSIDE HSM hardware
(Never exported to software)
```

**Benefits:**

* ✅ FIPS 140-2 Level 3 certified
* ✅ Physical tamper resistance
* ✅ Keys never in software
* ✅ Compliance requirements met
* ✅ True key deletion

**Limitations:**

* ⚠️ Cost: $1,152+/month for HA setup
* ⚠️ Latency: \~5-10ms per operation
* ⚠️ No PQC support yet (awaiting NIST FIPS modules)

**Use Cases:**

* Financial institutions
* Certificate authorities
* Government/defense
* Regulatory compliance (PCI-DSS, HIPAA)
