# Key Management in CQRIT

## Core Principle

**Keys are never stored. Keys are derived at runtime. Keys exist only in memory.**

This is the fundamental difference between CQRIT and traditional encryption systems.

## Key Properties

### 1. No Persistent Storage

**Traditional Systems:**
```
Generate Key → Save to File/Database → Encrypt/Decrypt → Keep File Secure Forever
```

**CQRIT:**
```
Generate Key → Use in Memory → Clear from Memory → Regenerate Next Time
```

**Implications:**
- No key files to protect
- No database to secure
- No backup/recovery of key files
- No key rotation needed

### 2. Deterministic Derivation

**Process:**
```
Same Memory Inputs → Same KDF Parameters → Same Private Key
```

**Properties:**
- Reproducible across devices
- No synchronization needed
- Multi-device support inherent

**Example:**
```
Device A: "What is your first pet's name?" → "fluffy" → Key ABC123
Device B: "What is your first pet's name?" → "fluffy" → Key ABC123
(Same key regenerated on different device)
```

### 3. Memory-Only Existence

**Lifecycle:**
1. User session begins
2. Memory inputs provided
3. Key derived in RAM
4. Key used for operations
5. Session ends
6. RAM cleared
7. Key gone forever (until regenerated)

**Security Benefit:**
- Cold boot attacks less effective
- No persistent key material
- Harder to exfiltrate

## Key Source: User Memory

### What Qualifies as "Memory Input"

**Good Inputs (High Entropy):**
- Personal facts only you know
- Specific details with many possibilities
- Combination of multiple inputs
- Non-obvious answers

**Examples:**
- "What street did you live on in 2010?"
- "What was your 3rd teacher's middle name?"
- "What color was your childhood bedroom wall?"

**Bad Inputs (Low Entropy):**
- Publicly available information
- Common passwords
- Dictionary words
- Predictable patterns

**Examples:**
- "What is your birthday?" (public)
- "password123" (weak)
- "qwerty" (predictable)

### Entropy Requirements

**Weak** (<40 bits):
- Single common word
- Public information
- Easily guessable

**Medium** (40-80 bits):
- Multiple words
- Personal but not unique
- Some complexity

**Strong** (>80 bits):
- Multiple unique personal facts
- High variability in answers
- Combination of different types

**Recommendation:**
Use multiple memory inputs combined for higher entropy.

## Key Types

### 1. Master Key

**Source:** Primary memory inputs

**Purpose:**
- Derive other keys
- Unlock key hierarchy
- Main authentication

**Properties:**
- Never stored
- Regenerated each session
- Highest importance

### 2. Item Keys

**Source:** Master key + item-specific data

**Purpose:**
- Encrypt individual items
- Isolated security

**Properties:**
- Derived from master
- Unique per item
- Not stored

### 3. Shared Keys (Group Encryption)

**Source:** Threshold cryptography reconstruction

**Purpose:**
- Multi-party access
- Family/team sharing
- Social recovery

**Properties:**
- No single party has full key
- Requires M-of-N participants
- Each participant has own memory-derived key

## Key Operations

### Generation

```javascript
// Pseudocode
function generateKey(memoryInputs, salt, iterations) {
  // 1. Combine inputs
  const combined = memoryInputs.join("")
  
  // 2. Apply KDF
  const key = KDF(combined, salt, iterations)
  
  // 3. Return (in memory only)
  return key // NEVER save this
}
```

**Steps:**
1. Collect memory inputs from user
2. Combine inputs deterministically
3. Apply KDF with user-specific salt
4. High iteration count (defense against brute force)
5. Return key to caller
6. **CRITICAL:** Never persist to disk/database

### Usage

```javascript
// Pseudocode
function encryptData(plaintext, memoryInputs) {
  // 1. Generate key
  const key = generateKey(memoryInputs, userSalt, iterations)
  
  // 2. Encrypt
  const ciphertext = encrypt(plaintext, key)
  
  // 3. Clear key from memory
  secureWipe(key)
  
  // 4. Return encrypted data
  return ciphertext
}
```

**Best Practices:**
- Generate key
- Use immediately
- Clear from memory ASAP
- Never pass key across network

### Destruction

```javascript
// Pseudocode
function secureWipe(key) {
  // Overwrite memory
  for (let i = 0; i < key.length; i++) {
    key[i] = 0
  }
  
  // Null reference
  key = null
  
  // Force garbage collection (if possible)
  gc()
}
```

**Importance:**
Prevents keys lingering in memory after use.

## Multi-Device Support

### How It Works Without Key Storage

**Problem:** User has Device A and Device B. How to use same key?

**Traditional Solution:**
1. Generate key on Device A
2. Save key to cloud/file
3. Sync to Device B
4. Load key on Device B

**CQRIT Solution:**
1. User provides memory inputs on Device A → Key generated
2. User provides **same** memory inputs on Device B → **Same key regenerated**
3. No synchronization needed
4. No key transmission

**Requirement:**
User must remember the same memory inputs.

### Cross-Device Consistency

**Same Inputs:**
```
Device A: "fluffy" → Key ABC123
Device B: "fluffy" → Key ABC123
✅ Same key, data decrypts
```

**Different Inputs:**
```
Device A: "fluffy" → Key ABC123
Device B: "Fluffy" → Key XYZ789
❌ Different key, data won't decrypt
```

**Note:** Inputs are case-sensitive by default.

## Security Implications

### Advantages of No Key Storage

✅ **No Database Leaks:**
- Server breach cannot expose keys
- Database dump reveals no keys

✅ **No Key Theft:**
- No files to steal
- No cloud sync to intercept

✅ **No Key Rotation:**
- No need to periodically change keys
- No old key management

✅ **Perfect Forward Secrecy:**
- Past sessions cannot be decrypted if current session compromised

### Challenges of Memory-Based Keys

⚠️ **User Forgetfulness:**
- If user forgets inputs, key lost forever
- Mitigation: Social recovery

⚠️ **Entropy Dependency:**
- Weak inputs = weak keys
- Mitigation: Entropy checking, user guidance

⚠️ **Coercion Risk:**
- User can be forced to reveal inputs
- Mitigation: Anti-kidnapping features

## Key Recovery

### What Happens if User Forgets

**Without Social Recovery:**
- Key cannot be regenerated
- Encrypted data lost forever
- No backdoor exists

**With Social Recovery:**
- Trusted parties help reconstruction
- Each has partial knowledge
- M-of-N threshold can restore access
- See [Social Recovery](recovery.md)

### Partial Forgetting

**Scenario:** User remembers some inputs but not all

**Options:**
1. **Try variations** (if close)
2. **Social recovery** (if configured)
3. **Brute force remaining** (if small search space)

**Example:**
- User remembers "fluff..." but not full word
- Try: "fluffy", "fluff", "fluffer", etc.
- If search space small enough, possible

## Comparison with Traditional Key Management

| Aspect | Traditional | CQRIT |
|--------|------------|-------|
| Storage | Files/Database | None |
| Backup | Required | Via memory/social recovery |
| Rotation | Periodic | Not needed |
| Multi-device | Sync files | Regenerate |
| Breach risk | High | Low (no keys to breach) |
| User burden | Protect files | Remember inputs |
| Quantum threat | Vulnerable (if RSA/ECC) | Resistant (CRYSTALS-Kyber) |

## Best Practices

### For Users

✅ **Choose strong memory inputs**
- High entropy
- Personal but not public
- Multiple inputs

✅ **Set up social recovery**
- For important data
- With trusted individuals

✅ **Practice recall**
- Ensure you can remember inputs
- Test on second device

✅ **Document inputs securely** (optional)
- Physical safe
- Split knowledge
- Not digital storage

### For Developers

✅ **Never log keys**
✅ **Clear memory after use**
✅ **Use constant-time comparisons**
✅ **Implement secure wipe functions**
✅ **Audit key lifecycle**

## Edge Cases

### Case 1: Memory Loss (Alzheimer's)
**Solution:** Social recovery with family members

### Case 2: Device Compromise
**Impact:** Current session at risk, but stored encrypted data safe (key not stored)

### Case 3: Parallel Sessions
**Behavior:** Same inputs generate same key on all sessions

### Case 4: Typo in Input
**Result:** Different key generated, decryption fails

## Future Enhancements

- Biometric inputs (fingerprint/face combined with memory)
- Hardware security module (HSM) integration
- Secure enclave use (if available)
- Fuzzy key extraction (tolerate small input variations)

---

**Next:** Read [Threat Model](threat-model.md) to understand what this protects against
