# Cryptographic Architecture & Password Recovery

## Current Encryption Architecture

### Key Types and Usage

The app uses a **HYBRID cryptographic approach**:

```
┌──────────────────────────────────────────────────────────────┐
│                   CRYPTOGRAPHIC HIERARCHY                      │
├──────────────────────────────────────────────────────────────┤
│                                                                │
│  1. USER PASSWORD (User Input)                                │
│       ↓                                                        │
│  2. PBKDF2 Key Derivation (100,000 iterations)               │
│       ↓                                                        │
│  3. AES-256 SYMMETRIC KEY (Derived from password)            │
│       ├── Encrypts: Health data                               │
│       └── Stored: Locally in secure storage                   │
│                                                                │
│  4. RSA-2048 ASYMMETRIC KEYS (Optional, for future use)      │
│       ├── Public Key: Could encrypt symmetric keys            │
│       └── Private Key: Could be password-protected            │
│                                                                │
└──────────────────────────────────────────────────────────────┘
```

### Actual Implementation Analysis

#### 1. **PRIMARY ENCRYPTION: Symmetric (AES-256)**
```dart
// From encryption_service.dart lines 28-50
Future<void> initialize({
  required String password,  // User's password
  String? salt,
  bool forceRegenerate = false,
}) async {
  // Derive AES key from password using PBKDF2
  encryptionKey = await _keyManagement.deriveSymmetricKey(
    password: password,
    salt: keySalt,
    iterations: 100000,  // Strong key derivation
    keyLength: 32,       // 256-bit key
  );
}
```

**Key Points:**
- **SYMMETRIC encryption (AES-256-GCM)** is the primary method
- Key is **derived from user password** using PBKDF2
- **NOT using asymmetric (RSA) keys** for data encryption currently
- RSA keys are generated but not actively used for health data

#### 2. **RSA Keys (Currently Unused for Data)**
```dart
// From key_management_service.dart
// RSA keys are generated and stored but NOT used for health data encryption
Future<KeyGenerationResult> generateKeyPair({
  int keySize = 2048,  // RSA-2048
  String? keyId,
}) async {
  // These keys are generated but not used for health data
  // They could be used for future features like:
  // - Key escrow
  // - Multi-device sync
  // - Password recovery
}
```

### Password Protection & Recovery

#### Current Situation: **NO RECOVERY OPTIONS** ⚠️

```
USER PASSWORD → PBKDF2 → AES KEY → ENCRYPTED DATA
     ↑                                    ↓
     └──── IF LOST, NO RECOVERY ────────┘
```

**Critical Points:**
1. **Password is NEVER stored** (only used to derive keys)
2. **No backup codes** currently implemented
3. **No key escrow** system
4. **Lost password = Lost data** (by design for privacy)

### Why No Recovery? Privacy vs Convenience Trade-off

```yaml
Current Design Philosophy:
  Priority: Maximum Privacy
  Trade-off: No Password Recovery
  
  Pros:
    - Zero-knowledge architecture
    - No backdoors for hackers
    - Complete user control
    - No trust required in service provider
    
  Cons:
    - Lost password = permanent data loss
    - No account recovery options
    - User bears full responsibility
```

## Potential Recovery Solutions

### Option 1: Recovery Phrase (Recommended for Privacy)

```dart
class RecoveryPhraseService {
  // Generate 12-24 word recovery phrase
  Future<List<String>> generateRecoveryPhrase() async {
    // Use BIP39 wordlist
    final entropy = SecurityUtils.generateRandomBytes(16); // 128 bits
    final mnemonic = bip39.entropyToMnemonic(entropy);
    
    // Derive encryption key from mnemonic
    final seed = bip39.mnemonicToSeed(mnemonic);
    final encryptionKey = deriveKeyFromSeed(seed);
    
    return mnemonic.split(' ');
  }
  
  // User stores these 12-24 words offline
  // Can recover account with phrase instead of password
}
```

**Implementation:**
```
PASSWORD → AES KEY → ENCRYPT DATA
    OR
RECOVERY PHRASE → AES KEY → ENCRYPT DATA
```

### Option 2: Key Escrow with RSA (Less Private)

```dart
class KeyEscrowService {
  Future<void> setupKeyEscrow(String password) async {
    // 1. Generate RSA key pair for escrow
    final escrowKeyPair = await generateRSAKeyPair();
    
    // 2. Encrypt AES key with RSA public key
    final aesKey = deriveKeyFromPassword(password);
    final encryptedAesKey = rsaEncrypt(aesKey, escrowKeyPair.publicKey);
    
    // 3. Store encrypted key in cloud (still encrypted)
    await cloudStorage.store('escrow_key', encryptedAesKey);
    
    // 4. RSA private key protected by security questions
    final protectedPrivateKey = encryptWithSecurityAnswers(
      escrowKeyPair.privateKey,
      securityAnswers
    );
  }
}
```

**Recovery Flow:**
```
SECURITY QUESTIONS → DECRYPT RSA PRIVATE KEY → DECRYPT AES KEY → ACCESS DATA
```

### Option 3: Shamir's Secret Sharing (Advanced)

```dart
class SecretSharingRecovery {
  // Split encryption key into N shares, require M to recover
  Future<List<String>> createRecoveryShares({
    required Uint8List encryptionKey,
    int totalShares = 5,
    int requiredShares = 3,
  }) async {
    // Use Shamir's Secret Sharing
    final shares = shamirSplit(encryptionKey, totalShares, requiredShares);
    
    // Distribute shares:
    // - Give 2 to user
    // - Store 1 in cloud (encrypted)
    // - Email 1 to trusted contact
    // - Store 1 with recovery service
    
    return shares;
  }
}
```

### Option 4: Biometric-Protected Backup (Mobile Only)

```dart
class BiometricBackup {
  Future<void> createBiometricBackup(String password) async {
    // Derive encryption key
    final aesKey = deriveKeyFromPassword(password);
    
    // Store in biometric-protected storage
    await FlutterSecureStorage(
      aOptions: AndroidOptions(
        encryptedSharedPreferences: true,
        requireAuthenticationForDecrypt: true, // Biometric required
      ),
    ).write(key: 'backup_key', value: base64Encode(aesKey));
  }
  
  // Recovery: Biometric auth → Retrieve key → Decrypt data
}
```

## Recommended Implementation Plan

### Phase 1: Add Recovery Phrase (Maintains Privacy)
```dart
class EnhancedEncryptionService {
  Future<RecoveryData> initializeWithRecovery({
    required String password,
  }) async {
    // Generate recovery phrase
    final recoveryPhrase = await generateRecoveryPhrase();
    
    // Derive key from BOTH password and phrase
    final passwordKey = deriveFromPassword(password);
    final phraseKey = deriveFromPhrase(recoveryPhrase);
    
    // Use XOR or KDF to combine (allows either to decrypt)
    final masterKey = combineKeys(passwordKey, phraseKey);
    
    return RecoveryData(
      recoveryPhrase: recoveryPhrase,
      displayWarning: 'WRITE DOWN AND STORE SAFELY! Cannot recover without this.',
    );
  }
}
```

### Phase 2: Optional Cloud Backup of Encrypted Keys
```dart
class OptionalCloudRecovery {
  // User chooses privacy level
  enum RecoveryMode {
    none,           // Current: No recovery
    localOnly,      // Recovery phrase only
    cloudBackup,    // Encrypted key in cloud
    fullRecovery,   // Multiple recovery options
  }
  
  Future<void> setupRecovery(RecoveryMode mode) async {
    switch (mode) {
      case RecoveryMode.none:
        // Current implementation
        break;
      case RecoveryMode.localOnly:
        // Generate recovery phrase only
        break;
      case RecoveryMode.cloudBackup:
        // Encrypt and backup key to cloud
        break;
      case RecoveryMode.fullRecovery:
        // All recovery methods
        break;
    }
  }
}
```

## Security Analysis

### Current Risks
1. **Single Point of Failure**: Password loss = data loss
2. **No Account Recovery**: Cannot help users who forget password
3. **User Burden**: High responsibility on user

### With Recovery Options
| Method | Privacy | Convenience | Security | Recommendation |
|--------|---------|-------------|----------|----------------|
| **No Recovery** (Current) | ⭐⭐⭐⭐⭐ | ⭐ | ⭐⭐⭐⭐ | Privacy-focused users |
| **Recovery Phrase** | ⭐⭐⭐⭐ | ⭐⭐⭐ | ⭐⭐⭐⭐ | **Best balance** |
| **Key Escrow** | ⭐⭐ | ⭐⭐⭐⭐ | ⭐⭐⭐ | Convenience-focused |
| **Secret Sharing** | ⭐⭐⭐ | ⭐⭐ | ⭐⭐⭐⭐⭐ | Advanced users |
| **Biometric Backup** | ⭐⭐⭐ | ⭐⭐⭐⭐⭐ | ⭐⭐⭐ | Mobile-only users |

## Implementation Priority

### Immediate (High Priority)
1. **Add Recovery Phrase Generation**
   - Use BIP39 standard
   - 12-24 word mnemonic
   - Display once, user must write down

### Short-term (Medium Priority)
2. **Security Questions** (optional)
   - Encrypt recovery phrase with answers
   - Store encrypted phrase locally

3. **Biometric Backup** (mobile)
   - Store encrypted key in biometric storage
   - Requires device support

### Long-term (Low Priority)
4. **Cloud Key Escrow** (optional, privacy trade-off)
   - User explicitly opts in
   - Multiple encryption layers
   - Clear privacy warnings

## User Experience Recommendations

### During Setup
```
┌─────────────────────────────────────────┐
│         SECURE YOUR ACCOUNT             │
├─────────────────────────────────────────┤
│                                          │
│ Choose your security level:             │
│                                          │
│ 🔒 Maximum Privacy (Recommended)        │
│    • No cloud recovery                  │
│    • 12-word recovery phrase            │
│    • You control everything             │
│                                          │
│ 🔄 Balanced                             │
│    • Recovery phrase                    │
│    • Optional biometric backup          │
│                                          │
│ ☁️ Convenience                          │
│    • Cloud backup (encrypted)           │
│    • Security questions                 │
│    • Easier recovery                    │
│                                          │
└─────────────────────────────────────────┘
```

### Recovery Phrase Display
```
┌─────────────────────────────────────────┐
│     YOUR RECOVERY PHRASE (CRITICAL!)    │
├─────────────────────────────────────────┤
│                                          │
│ Write these words down in order:        │
│                                          │
│ 1. canvas    7. electric                │
│ 2. dizzy     8. sad                     │
│ 3. buyer     9. story                   │
│ 4. gossip    10. treat                  │
│ 5. rhythm    11. race                   │
│ 6. north     12. alone                  │
│                                          │
│ ⚠️ NEVER share or photograph these     │
│ ⚠️ Store in a SAFE place                │
│ ⚠️ This is your ONLY recovery method   │
│                                          │
│ [✓] I have written down these words     │
│                                          │
└─────────────────────────────────────────┘
```

## Summary

### Current State
- **Encryption**: AES-256 symmetric (NOT asymmetric RSA for data)
- **Key Derivation**: PBKDF2 from password (100,000 iterations)
- **Password Protected**: YES (it's the only way to derive keys)
- **Recovery Options**: NONE ⚠️
- **Backup Codes**: NOT IMPLEMENTED ⚠️

### Critical Points
1. **No asymmetric encryption for health data** (RSA keys exist but unused)
2. **Password loss = permanent data loss** (by design)
3. **Zero-knowledge architecture** (maximum privacy)
4. **No backdoors or recovery** (currently)

### Recommended Action
Implement **BIP39 recovery phrase** as the primary recovery method:
- Maintains privacy
- Industry standard
- User-friendly
- No cloud dependency
- Compatible with current architecture
