# Received Key Processor Application - System Administrator Guide

## Version 1.0.107
**Document Date:** 2026-05-18
**Application Version:** .NET 8.0 WPF Desktop Application

---

## 1. Introduction

### 1.1 System Overview

The Received Key Processor Application (RKPA) is a C# WPF desktop application designed for receiving, processing, and managing cryptographic keys and mission data through serial port communication and SQLite database storage. The application supports multiple cryptographic tag formats including DS-100-1 TrKEK, MIDS JTRS, and various binary tag formats.

### 1.2 Key Capabilities

- **Serial Port Communication**: Receive key data via COM port
- **XML Processing**: Parse and validate Tier3 XML payloads
- **Database Storage**: SQLite database for persistent storage
- **Mission Planning**: Create and manage mission plans
- **Key Management**: Organize and process cryptographic keys
- **Duplicate Prevention**: Hash-based duplicate detection
- **Binary Tag Processing**: Support for JMPS, TR, MIDS JTRS, IFF, and composite formats
- **8727 Binary File Processing**: Complete EKMS2.exe integration

### 1.3 Target Audience

This guide is intended for IT system administrators responsible for deploying, configuring, monitoring, and maintaining the RKPA application in production environments.

---

## 2. System Architecture

### 2.1 5-Layer Architecture

The application follows a clean 5-layer architecture pattern:

```
├── ReceivedKeyProcessorApp/          # Presentation Layer (WPF UI)
│   ├── Views/                        # XAML user interfaces
│   ├── ViewModels/                   # MVVM view models
│   ├── Contracts/                    # UI contracts
│   └── Resources/                    # UI resources
│
├── Application/                      # Business Logic Layer
│   ├── Services/                     # Application services
│   ├── Contracts/                    # Service contracts
│   └── DTOs/                         # Data transfer objects
│
├── Domain/                           # Domain Models Layer
│   ├── Models/                       # Business entities
│   ├── Contracts/                    # Domain contracts
│   └── Enums/                        # Enumerations
│
├── Infrastructure/                   # Data Access Layer
│   ├── Data/                         # EF Core context
│   ├── Services/                     # Data services
│   └── Repositories/                 # Repository implementations
│
└── CrossCutting/                     # Shared Utilities
    ├── Common/                       # Common utilities
    ├── Security/                     # Security helpers
    └── Extensions/                   # Extension methods
```

### 2.2 Component Interactions

```
User Interface (WPF)
    ↓
View Models (MVVM)
    ↓
Business Services
    ↓
Repository/EF Core
    ↓
SQLite Database
```

### 2.3 External Integration Points

- **EKMS2.exe**: External tool for 8727 binary file conversion
- **Serial Port**: COM port communication for key data reception
- **Radio Interface Library**: Separate solution for radio/serial communications

---

## 3. Installation and Deployment

### 3.1 System Requirements

#### Hardware Requirements
- **Processor**: x64 architecture, 2.0 GHz or faster
- **RAM**: 4 GB minimum, 8 GB recommended
- **Disk Space**: 500 MB for application, additional space for database and logs
- **Serial Port**: At least one COM port for key data reception

#### Software Requirements
- **Operating System**: Windows 10/11 Pro or Enterprise
- **.NET Runtime**: .NET 8.0 Windows Desktop Runtime
- **Development Tools** (for source builds):
  - Visual Studio 2022
  - .NET 8.0 SDK
  - .NET Framework 4.8

### 3.2 Installation Procedure

#### Method 1: Compiled Executable Deployment

1. **Extract Application Files**
   ```bash
   # Copy to deployment directory
   C:\Program Files\ReceivedKeyProcessorApp\
   ```

2. **Verify Dependencies**
   - Ensure .NET 8.0 Windows Desktop Runtime is installed
   - Verify EKMS2.exe is in application directory

3. **Create Shortcut**
   - Create desktop shortcut to `ReceivedKeyProcessorApp.exe`

4. **Test Installation**
   - Launch application and verify database creation
   - Test serial port connectivity (if hardware available)

#### Method 2: Source Code Build

```bash
# Navigate to solution directory
cd C:\development\receivekeyprocessorapp

# Build solution
dotnet build /mnt/c/development/receivekeyprocessorapp/ReceivedKeyProcessorApp.sln

# Run tests
dotnet test

# Publish release build
dotnet publish -c Release -r win-x64 --self-contained false
```

### 3.3 File Structure

```
ReceivedKeyProcessorApp/
├── ReceivedKeyProcessorApp.exe        # Main executable
├── EKMS2.exe                          # External binary converter (REQUIRED)
├── appsettings.json                   # Application configuration
├── Configurations/                    # Configuration files
├── Resources/                         # UI resources and assets
│   └── EquipmentIds.json             # Equipment ID lookup table
└── RadioInterfaceLibrary/             # Radio interface library (if deployed)
```

### 3.4 Post-Installation Configuration

1. **Set Serial Port Permissions**
   - Ensure user has read/write access to COM ports
   - Configure Windows Device Manager port settings

2. **Configure Database Location** (optional)
   - Default: `%LOCALAPPDATA%\ReceivedKeyProcessorApp\keys.db`
   - Custom path can be set via `KeyContext.CustomDatabasePath`

3. **Verify External Dependencies**
   - Confirm EKMS2.exe is accessible
   - Test EKMS2.exe command-line execution

---

## 4. Database Configuration and Management

### 4.1 Database Overview

**Database Engine**: SQLite (embedded, no server required)
**Default Location**: `%LOCALAPPDATA%\ReceivedKeyProcessorApp\keys.db`
**ORM**: Entity Framework Core 8.0
**Context**: `Infrastructure/Data/KeyContext.cs`

### 4.2 Database Schema

#### Primary Entities

| Table | Description | Primary Key |
|-------|-------------|-------------|
| Keys | Root key entities | KeyId |
| ShortTitle | Key short titles | ShortTitleId |
| Edition | Key editions | EditionId |
| Segment | Cryptographic key segments | SegmentId |
| MissionPlan | Mission planning data | MissionPlanId |
| Tier3Payloads | XML payload storage | Tier3PayloadId |

#### Lookup Tables

| Table | Purpose |
|-------|---------|
| MaterialType | Material type classifications |
| KeyType | Key type classifications |
| Classification | Security classifications |
| KeyUse | Key usage categories |
| KeyStatus | Key status values |
| Ownership | NATO ownership codes |
| AccountingLegendCode | ALC values |
| Caveat | Caveat codes |
| WII | Waveform Instance IDs |

#### Entity Relationships

```
Key (1) ----< (many) ShortTitle (1) ----< (many) Edition (1) ----< (many) Segment
                 |                    |- Classification (FK)
                 |                    |- KeyUse (FK)
                 |
                 |- MaterialType (FK)
```

### 4.3 Database Initialization

#### Automatic Initialization

The database is automatically initialized on first application launch:

```csharp
// Location: App.xaml.cs:CheckForDatabase()
using (var db = new InfraData.KeyContext())
{
    var created = db.Database.EnsureCreated();
    // Returns false if database already exists
}
```

#### Manual Database Creation

```bash
# Using EF Core migrations
dotnet ef migrations add InitialCreate --project ReceivedKeyProcessorApp/ReceivedKeyProcessorApp.csproj --startup-project ReceivedKeyProcessorApp/ReceivedKeyProcessorApp.csproj

# Apply migrations
dotnet ef database update
```

### 4.4 Database Seeding

#### Lookup Data Seeding

Lookup tables are automatically seeded with predefined values in `KeyContext.OnModelCreating()`:

- MaterialTypes (e.g., Key, KMID)
- KeyTypes (e.g., OTAR, KGV, KEK)
- Classifications (e.g., UNCLASSIFIED, SECRET, TOP SECRET)
- KeyUses (e.g., OTAR, KGV, KEK)
- KeyStatuses (e.g., Active, Expired, Revoked)
- Ownerships (e.g., US ONLY, ALLIED, NATO)
- AccountingLegendCodes
- Caveats

#### Test Data Seeding

For testing environments, use `DatabaseManagementService`:

```csharp
var config = new DatabaseManagementService.DatabaseConfig
{
    Environment = DatabaseManagementService.EnvironmentMode.Testing,
    Volume = DatabaseManagementService.DataVolume.Small,
    IncludeTestData = true
};

var dbService = new DatabaseManagementService(config);
var report = await dbService.InitializeDatabaseAsync();
```

### 4.5 Database Operations

#### Custom Database Path

To use a custom database location:

```csharp
// Set before any database operations
Infrastructure.Data.KeyContext.CustomDatabasePath = @"C:\CustomPath\keys.db";
```

#### Database Connection String

The connection string is configured in `KeyContext.OnConfiguring()`:

```csharp
optionsBuilder.UseSqlite($"Data Source={GetDatabasePath()}", options =>
    options.MigrationsAssembly("ReceivedKeyProcessorApp.Infrastructure"));
```

#### Database Maintenance

**Vacuum Database** (reclaim space):
```bash
sqlite3 %LOCALAPPDATA%\ReceivedKeyProcessorApp\keys.db "VACUUM;"
```

**Backup Database**:
```bash
copy %LOCALAPPDATA%\ReceivedKeyProcessorApp\keys.db C:\Backups\keys_backup_%DATE%.db
```

**Check Database Integrity**:
```bash
sqlite3 %LOCALAPPDATA%\ReceivedKeyProcessorApp\keys.db "PRAGMA integrity_check;"
```

### 4.6 Important Constraints

#### NOT NULL Constraints in SQLite

EF Core treats non-nullable reference types as NOT NULL in SQLite. When seeding test data:

- Use empty strings (`""`) instead of `null` for string fields
- Example: `SegmentEffectiveDate = ""`, `SegmentData = ""`

#### UI-Only Properties

The `Edition.IsExpanded` property is marked as `[NotMapped]` - it is a WPF UI property only and is not persisted to the database.

---

## 5. External Dependencies

### 5.1 EKMS2.exe

#### Purpose

External tool for converting 8727 binary format files to XML format for database import.

#### Location

Must be in the application directory:
```
C:\Program Files\ReceivedKeyProcessorApp\EKMS2.exe
```

#### Command Line Format

```bash
EKMS2.exe -protocol ds101 -tasks readfdusfromfile -files.8727inputfile "inputfile" -files.outputpath "outputdir" -files.outputtier3xml "outputfile"
```

#### Parameters

| Parameter | Description |
|-----------|-------------|
| `-protocol ds101` | Uses DS101 protocol |
| `-tasks readfdusfromfile` | Task to read FDUs from file |
| `-files.8727inputfile` | Path to input binary file |
| `-files.outputpath` | Directory for output files |
| `-files.outputtier3xml` | Path for XML output file |

#### Supported File Formats

| Extension | Description | Processing |
|-----------|-------------|------------|
| .8727 | Standard 8727 binary format | EKMS2.exe → XML → Database |
| .8287 | 8287 binary format | EKMS2.exe → XML → Database |
| .bin | Generic binary 8727 format | EKMS2.exe → XML → Database |
| .key | Key binary format | EKMS2.exe → XML → Database |
| .xml | XML format (direct) | Direct import |
| .json | JSON format (direct) | Direct import |

#### Troubleshooting EKMS2.exe

**EKMS2.exe Not Found**:
```
Error: "EKMS2.exe not found at: {path}"
Resolution: Ensure EKMS2.exe is in the application directory
```

**Invalid Binary File**:
```
Error: EKMS2.exe fails with non-zero exit code
Resolution: Verify file is valid 8727 format
```

### 5.2 Serial Port Communication

#### Port Configuration

- COM ports are configured via Windows Device Manager
- Application detects available ports automatically
- Port settings: Baud rate configurable (default: 9600)

#### Permissions

Ensure user account has read/write access to COM ports:
- Windows security policies
- Device Manager port properties

### 5.2.1 Send Keys Page - load.exe Integration

The Send Keys page uses `load.exe` for FDU/key transmission via serial port.

**Location:** `SupportApps/load.exe` in the application directory

**Command-Line Arguments:**

| Argument | Flag | Condition |
|----------|------|-----------|
| Baud Rate | `-rs232 {rate}` | When RS-232 is enabled |
| Null Modem | `-rs232_nullmodem 1` | When Null Modem is enabled |
| FDU Type | `-fdu 01B0` or `-fdu 02B0` | When Mode selected OR Prepend FDU enabled |
| Discrete FDU | `-descrete_fdu 1` | When Discrete FDU enabled |
| Line Termination | `-linetermination 0` | When disabled (enabled is default) |
| Wakeup | `-wakeup {seconds}` | When Wakeup seconds is set |
| Debug Print | `-dbgprint 1` | When Debug Print is "MoreInfo" |
| Loop | `-loop {count}` | When Loop Count is set |
| Mission | `-mission "{value}"` | When Mission Data enabled |
| File Path | `-path "{filepath}"` | Always (must be last parameter) |

**Prepend FDU Feature:**

The "Prepend FDU (0x01B0)" checkbox (default: ON) automatically adds `-fdu 01B0` when Mode is "None".

| Mode | Prepend FDU | Result |
|------|-------------|--------|
| None | OFF | No `-fdu` argument |
| None | ON (default) | `-fdu 01B0` |
| Fdu01B0 | Any | `-fdu 01B0` |
| Fdu02B0 | Any | `-fdu 02B0` |

**Example Command:**
```
load.exe -rs232 9600 -fdu 01B0 -descrete_fdu 1 -dbgprint 1 -loop 3 -path "C:\Keys\mykey.8727"
```

**Settings Persistence:**

All Send Keys settings are auto-saved and persist across application restarts:
- Communication parameters (baud rate, null modem, line termination)
- FDU configuration (Mode, Prepend FDU, Discrete FDU, Debug Print, Loop Count)
- Time operation settings
- Mission data settings
- Last used file path

**Documentation:** See [Send_Keys_Page_Documentation.md](Send_Keys_Page_Documentation.md) for complete user guidance.

### 5.2.2 Send to SKL and Fill Key to ECU Features

These features provide streamlined key transmission workflows from the database hierarchical view.

#### Send to SKL

**Purpose:** Direct transmission of key segments to SKL device

**Access:** Database page → Right-click segment → "Send to SKL"

**Technical Details:**
- Uses `LoadExeService.ExecuteAsync()` to invoke load.exe
- Protocol: DS-101 (USB) - no RS-232 configuration needed
- FDU Mode: Discrete FDU (one key per transmission)
- Temp file format: `{ShortTitleName}_yyyyMMdd_HHmmss.8727.bin`
- Settings: PrependFdu=false, DiscreteFdu=true

**Output Window:**
- Real-time progress display
- Copy/Cancel/Close buttons
- Theme-aware (follows application dark/light mode)
- Close button uses accent color from settings

**Documentation:** See [Send_To_SKL_Documentation.md](Send_To_SKL_Documentation.md)

#### Fill Key to ECU

**Purpose:** Generate MIDS JTRS fill content for Electronic Control Units

**Access:** Database page → Right-click segment → "Fill Key to ECU"

**Technical Details:**
- Template-based MIDS JTRS tag generation via `MIDSJTRSTagGenerationService`
- Output: 01B0 FDU format only (no EKMS 308 header)
- Uses `FDUExportService.GenerateFillKeyOnlyContent()`
- Temp file format: `FillKey_yyyyMMdd_HHmmss.8727.bin`
- Debug output panel shows generation process

**Send to SKL Integration:**
- Can send generated content directly to SKL via load.exe
- Uses RS-232 at 9600 baud with PrependFdu=false

**Documentation:** See [Fill_Key_To_ECU_Documentation.md](Fill_Key_To_ECU_Documentation.md)

### 5.2.3 WII Management

The WII (Waveform Instance Identifier) Management feature provides a tabular interface for managing WII values used by mission plans.

**Access:** Database page → WII Management tab

#### WII Entity

| Property | Type | Constraints |
|----------|------|-------------|
| `WiiId` | `int` | Primary Key (no auto-increment; explicit values) |
| `Value` | `string` | Required, max 9 characters, unique |
| `Description` | `string` | Optional, max 255 characters |

#### Database Seeding

New databases are automatically seeded with a default WII:

| Value | Description |
|-------|-------------|
| `HHL16` | High-Level Link 16 |

The seeding logic in `DatabaseSeedService.SeedDefaultWIIs()` skips insertion if the WII table already contains records.

#### WII ID Assignment

The WII table uses `ValueGeneratedNever()` — there is no SQLite AUTOINCREMENT. When a new WII is added via the UI:

1. The new item is temporarily marked with `WiiId = -1`
2. On Save, the system assigns `max(existing WiiIds) + 1`
3. The new WII is inserted with the explicit ID

#### Multi-Select Deletion

The WII Management DataGrid supports `SelectionMode="Extended"`:

- **Ctrl+Click**: Select multiple non-contiguous rows
- **Shift+Click**: Select a range of rows
- **Delete key** or **Delete button**: Remove all selected rows
- Deletions are applied to the in-memory `ObservableCollection<WII>` immediately
- **Save** persists deletions by comparing the collection against the database and removing orphaned records

#### WII in Mission Plans

The `MissionPlanGroup` entity references WIIs via a nullable foreign key (`WiiId`), allowing mission plans to specify which WII configuration to use. The FK is configured with `.IsRequired(false)` and no cascade delete, so deleting a WII does not delete associated mission plan groups.

**Files:**
- `ReceivedKeyProcessorApp/DataBaseControls/WIIManagementControl.xaml` — XAML UI
- `ReceivedKeyProcessorApp/DataBaseControls/WIIManagementControl.xaml.cs` — Code-behind (Delete, Save, KeyDown handlers)
- `ReceivedKeyProcessorApp/ViewModels/WIIManagementViewModel.cs` — ViewModel with SaveChanges logic
- `ReceivedKeyProcessorApp/Services/DatabaseSeedService.cs` — Default WII seeding
- `Domain/Models/WII.cs` — Domain model

### 5.3 USB Libraries

The application may require USB drivers for specific cryptographic devices:
- Follow manufacturer installation instructions
- Verify device recognition in Windows Device Manager
- Test communication before production use

---

## 6. Service Registration and Lifecycle

### 6.1 Service Registration Overview

Service registration is configured in `ReceivedKeyProcessorApp/App.xaml.cs:ConfigureServices()` (lines 363-408+).

### 6.2 Singleton Services

These services are created once and shared throughout the application lifetime:

| Service | Interface | Purpose |
|---------|-----------|---------|
| `ProtocolService` | `IProtocolService` | Protocol configuration |
| `TaskService` | `ITaskService` | Task management |
| `BaudRateService` | `IBaudRateService` | Baud rate configuration |
| `EKMS2Service` | `IEKMS2Service` | EKMS2.exe integration |
| `I8727ParsingService` | `I8727ParsingService` | 8727 file parsing |
| `BinaryTagParser` | - | Binary tag parsing |
| `BinaryTagDetectionEngine` | - | Tag format detection |
| `NavigationService` | `INavigationService` | View navigation |
| `SettingsService` | `ISettingsService` | Application settings |
| `EquipmentIdLookup` | - | Equipment ID lookups |
| `FileService` | `IFileService` | File operations |
| `FDUViewerService` | `IFDUViewerService` | FDU data viewing |

### 6.3 Transient Services

These services are created per navigation request:

| Service | Purpose |
|---------|---------|
| `ShellWindow` | Main application shell |
| `ShellViewModel` | Shell view model |
| `MainViewModel` | Main view model |
| `DatabaseViewModel` | Database management view |
| Other ViewModels | View-specific logic |

### 6.4 Service Lifecycle

#### Application Startup

1. `App` constructor initializes exception logging
2. `OnStartup()` creates DI container host
3. `ConfigureServices()` registers all services
4. `ApplicationHostService` starts as hosted service
5. `CheckForDatabase()` ensures database exists

#### Application Shutdown

1. `OnExit()` triggers host shutdown
2. All singleton services disposed
3. Database connections closed
4. Logs flushed to disk

### 6.5 Dependency Injection Pattern

```csharp
// Register singleton
services.AddSingleton<IEKMS2Service, EKMS2Service>();

// Register transient
services.AddTransient<DatabaseViewModel>();

// Resolve service
var ekms2Service = _host.Services.GetService<IEKMS2Service>();
```

---

## 7. Logging and Monitoring

### 7.1 Log File Locations

| Log File | Location | Purpose |
|----------|----------|---------|
| `global_exceptions.log` | Application directory | Global exception handling |
| `ef_core_exceptions.log` | Application directory | EF Core database operations |
| `RKPA_8727_Import.log` | Temp directory | 8727 file import operations |
| `RKPA_EKMS2_Service.log` | Temp directory | EKMS2.exe service operations |
| `ReceivedKeyProcessorApp_Debug.log` | `%TEMP%` | Application debug logging |

### 7.2 Exception Handling

#### Global Exception Handler

Location: `ReceivedKeyProcessorApp/GlobalExceptionHandler.cs`

```csharp
// Automatically catches all unhandled exceptions
AppDomain.CurrentDomain.UnhandledException
TaskScheduler.UnobservedTaskException
```

#### EF Core Interceptor

Location: `Infrastructure/Data/EfCoreExceptionInterceptor.cs`

Logs all database operations:
- NonQueryExecuting/NonQueryExecuted
- ReaderExecuting/ReaderExecuted
- ScalarExecuting/ScalarExecuted
- CommandFailed (with full stack trace)

### 7.3 Log Levels

EF Core logging is configured in `KeyContext.OnConfiguring()`:

```csharp
optionsBuilder.LogTo(Console.WriteLine, LogLevel.Information);
optionsBuilder.EnableSensitiveDataLogging(true);
optionsBuilder.EnableDetailedErrors(true);
```

### 7.4 Log Rotation

Manual log rotation is required:

```bash
# Archive old logs
move global_exceptions.log global_exceptions_%DATE%.log

# Clear log file
del ef_core_exceptions.log
```

### 7.5 Monitoring Recommendations

#### Key Metrics to Monitor

1. **Database Size**
   ```bash
   dir %LOCALAPPDATA%\ReceivedKeyProcessorApp\keys.db
   ```

2. **Log File Sizes**
   - Monitor for excessive log growth
   - Set up alerts for log file > 10MB

3. **Error Rates**
   - Monitor `global_exceptions.log` for error frequency
   - Alert on > 10 errors/hour

4. **Performance Metrics**
   - Application startup time
   - Database query response times
   - Memory usage (target: < 500MB typical)

### 7.6 Debug Mode

Enable debug logging in `appsettings.json`:

```json
{
  "Logging": {
    "LogLevel": {
      "Default": "Debug"
    }
  }
}
```

---

## 8. Security Considerations

### 8.1 Data Protection

#### Secure File Deletion

The application implements secure temporary file handling via `ZeroizeFileAsync()`:

```csharp
// Location: Application/Services/EKMS2Service.cs
// Files are overwritten with zeros before deletion
// Files are renamed with random names before deletion
```

#### Zeroization Process

1. **Multiple Overwrite Passes**: Sensitive files are overwritten with zeros
2. **Random Renaming**: Files are renamed before deletion
3. **Automatic Cleanup**: Files are cleaned up in finally blocks
4. **No Data Leakage**: Sensitive data is never written to logs

### 8.2 Sensitive Data Handling

#### Logging Policy

- **NO sensitive data in logs**: Cryptographic keys are never logged
- **EF Core logging**: Sensitive data logging is enabled for debugging only
- **Production recommendation**: Disable `EnableSensitiveDataLogging(true)` in production

#### Example: Disable Sensitive Data Logging

```csharp
// In KeyContext.OnConfiguring(), change:
// optionsBuilder.EnableSensitiveDataLogging(false); // Production
```

### 8.3 Access Control

#### File System Permissions

Required permissions:
- **Application Directory**: Read/Execute
- **Database Directory**: Read/Write/Create
- **Temp Directory**: Read/Write/Create
- **COM Ports**: Read/Write (Windows Device Manager)

#### User Account

- Standard user account sufficient
- Administrator account NOT required
- Consider dedicated service account for production

### 8.4 Input Validation

#### File Upload Validation

- File extension validation (.8727, .8287, .bin, .key, .xml, .json)
- File size limits (configured per environment)
- Content validation via EKMS2.exe

#### Command Line Sanitization

EKMS2.exe arguments are sanitized to prevent command injection:

```csharp
// Proper escaping and validation implemented
// No user-supplied data passed directly to shell
```

### 8.5 Cryptographic Considerations

#### CRC Implementations

- **DS-100-1 CRC-8**: Polynomial x^8 + x^7 + x^2 + 1 (0x85)
- **MIDS JTRS CRC-16**: CCITT polynomial 0x1021
- **MIDS JTRS CRC-32**: EKMS 304 specification, polynomial 0x00400007

#### ECU KEK ID Calculation

SHA-1 hash-based validation with MSB-first byte ordering (see MIDS_JTRS_Implementation.md).

### 8.6 Security Best Practices

1. **Regular Backups**: Backup database and configuration files
2. **Access Logs**: Monitor application logs for unauthorized access
3. **Update Management**: Keep .NET runtime and dependencies updated
4. **Network Security**: If network-connected, use encrypted connections
5. **Physical Security**: Protect workstations with physical access controls
6. **User Training**: Train operators on security procedures

---

## 9. Backup and Recovery

### 9.1 Backup Strategy

#### Required Backups

1. **Database Backup**
   - Location: `%LOCALAPPDATA%\ReceivedKeyProcessorApp\keys.db`
   - Frequency: Daily (automated recommended)
   - Retention: 30 days

2. **Configuration Files**
   - `appsettings.json`
   - `settings.json` (from `%APPDATA%\ReceiveKeyProcessingUtility\`)
   - `EquipmentIds.json`

3. **Log Files** (optional, for audit trail)
   - All log files in application directory

#### Backup Script Example

```batch
@echo off
set BACKUP_DIR=C:\RKPA_Backups\%DATE:~-4,4%%DATE:~-7,2%%DATE:~-10,2%
mkdir "%BACKUP_DIR%"

:: Backup database
copy "%LOCALAPPDATA%\ReceivedKeyProcessorApp\keys.db" "%BACKUP_DIR%\keys.db"

:: Backup configurations
copy "C:\Program Files\ReceivedKeyProcessorApp\appsettings.json" "%BACKUP_DIR%\"
copy "%APPDATA%\ReceiveKeyProcessingUtility\settings.json" "%BACKUP_DIR%\"

:: Backup logs (optional)
xcopy "C:\Program Files\ReceivedKeyProcessorApp\*.log" "%BACKUP_DIR%\logs\" /Y

echo Backup completed: %BACKUP_DIR%
```

### 9.2 Restore Procedure

#### Database Restore

```batch
:: Stop application
taskkill /F /IM ReceivedKeyProcessorApp.exe

:: Restore database
copy "C:\RKPA_Backups\20260317\keys.db" "%LOCALAPPDATA%\ReceivedKeyProcessorApp\keys.db"

:: Start application
start "" "C:\Program Files\ReceivedKeyProcessorApp\ReceivedKeyProcessorApp.exe"
```

#### Configuration Restore

```batch
:: Restore appsettings.json
copy "C:\RKPA_Backups\20260317\appsettings.json" "C:\Program Files\ReceivedKeyProcessorApp\"

:: Restore user settings
copy "C:\RKPA_Backups\20260317\settings.json" "%APPDATA%\ReceiveKeyProcessingUtility\"
```

### 9.3 Disaster Recovery

#### Scenario: Database Corruption

**Symptoms**:
- Application fails to start
- Database errors in logs
- Data not displaying

**Recovery Steps**:
1. Stop application
2. Backup corrupted database (for forensic analysis)
3. Restore from latest known-good backup
4. Verify data integrity
5. Restart application

#### Scenario: Application Crash

**Symptoms**:
- Application closes unexpectedly
- Global exception log shows errors

**Recovery Steps**:
1. Review `global_exceptions.log` for error details
2. Check system resources (memory, disk space)
3. Restart application
4. If persistent, reinstall application

### 9.4 Point-in-Time Recovery

SQLite does not support point-in-time recovery natively. Consider:
1. Regular automated backups (hourly/daily)
2. Transaction logging (if implemented)
3. Application-level audit trails

---

## 10. Performance Tuning

### 10.1 Database Performance

#### SQLite Optimization

**Enable WAL Mode** (Write-Ahead Logging):
```sql
PRAGMA journal_mode=WAL;
```

**Increase Cache Size**:
```sql
PRAGMA cache_size=-20000;  -- 20MB
```

**Optimize Query Performance**:
```sql
PRAGMA optimize;
```

#### Index Optimization

Indexes are defined in `KeyContext.OnModelCreating()`:
- MaterialType.Name (unique)
- KeyType.Name (unique)
- Classification.Name (unique)
- KeyUse.Name (unique)
- KeyStatus.Name (unique)
- Ownership.Name (unique)
- AccountingLegendCode.Name (unique)
- Caveat.Name (unique)
- WII.Value (unique)

### 10.2 Application Performance

#### Memory Management

**Target Memory Usage**:
- Typical: < 500MB
- Large file processing: < 1GB
- Monitor with Windows Task Manager

**Memory Optimization Tips**:
- Close unused application windows
- Process large files in batches
- Restart application periodically (daily)

#### Processing Performance

**Performance Metrics**:

| Operation | Small File | Medium File | Large File |
|-----------|------------|-------------|------------|
| 8727 Import | < 5 seconds | < 30 seconds | < 2 minutes |
| Database Query | < 1 second | < 5 seconds | < 30 seconds |
| Tag Decoding | < 100ms | < 500ms | < 2 seconds |

### 10.3 Network Performance

If network operations are enabled:
- Use wired network connections
- Minimize network latency
- Monitor bandwidth usage

### 10.4 Disk I/O Optimization

**SSD vs HDD**:
- SSD recommended for database storage
- HDD acceptable for archival storage

**Disk Space Management**:
- Monitor free disk space (minimum 1GB free)
- Implement log rotation
- Archive old data regularly

---

## 11. Troubleshooting and Diagnostics

### 11.1 Common Issues and Solutions

#### Issue: Application Fails to Start

**Symptoms**:
- Application does not launch
- Error dialog appears

**Diagnostic Steps**:
1. Check `global_exceptions.log` for error details
2. Verify .NET 8.0 Windows Desktop Runtime is installed
3. Check database file permissions
4. Verify EKMS2.exe exists in application directory

**Resolution**:
```bash
# Verify .NET runtime
dotnet --list-runtimes

# Check database permissions
icacls "%LOCALAPPDATA%\ReceivedKeyProcessorApp\keys.db"

# Reinstall .NET runtime if needed
winget install Microsoft.DotNet.Runtime.8
```

#### Issue: Database Connection Failed

**Symptoms**:
- "Cannot open database file" error
- Data not loading

**Diagnostic Steps**:
1. Check database file exists: `%LOCALAPPDATA%\ReceivedKeyProcessorApp\keys.db`
2. Verify database is not corrupted: `sqlite3 keys.db "PRAGMA integrity_check;"`
3. Check file permissions
4. Review `ef_core_exceptions.log`

**Resolution**:
```bash
# Recreate database if corrupted
del "%LOCALAPPDATA%\ReceivedKeyProcessorApp\keys.db"
# Database will be recreated on next application launch
```

#### Issue: Serial Port Not Detected

**Symptoms**:
- COM port list empty
- "Port not available" error

**Diagnostic Steps**:
1. Open Windows Device Manager
2. Check "Ports (COM & LPT)" section
3. Verify device drivers are installed
4. Check port permissions

**Resolution**:
```powershell
# List COM ports in PowerShell
[System.IO.Ports.SerialPort]::GetPortNames()

# Check port status
Get-PnpDevice -Class Ports
```

#### Issue: EKMS2.exe Conversion Fails

**Symptoms**:
- "EKMS2.exe not found" error
- Non-zero exit code from EKMS2.exe

**Diagnostic Steps**:
1. Verify EKMS2.exe in application directory
2. Test EKMS2.exe manually: `EKMS2.exe -protocol ds101 -tasks readfdusfromfile -files.8727inputfile "test.bin" -files.outputpath "output" -files.outputtier3xml "output.xml"`
3. Check `RKPA_EKMS2_Service.log` for error details
4. Verify input file format

**Resolution**:
```bash
# Verify EKMS2.exe location
dir "C:\Program Files\ReceivedKeyProcessorApp\EKMS2.exe"

# Test EKMS2.exe manually
cd "C:\Program Files\ReceivedKeyProcessorApp"
EKMS2.exe -protocol ds101 -tasks readfdusfromfile -files.8727inputfile "test.bin" -files.outputpath "output" -files.outputtier3xml "output.xml"
```

#### Issue: Memory Leak Detected

**Symptoms**:
- Application memory grows continuously
- Performance degrades over time

**Diagnostic Steps**:
1. Monitor memory usage in Windows Task Manager
2. Check for unclosed database connections in `ef_core_exceptions.log`
3. Review event subscriptions for memory leaks

**Resolution**:
- Restart application
- Report issue to development team
- Consider automated restart schedule

### 11.2 Diagnostic Tools

#### Built-in Diagnostics

**Debug Output**:
- Application writes debug information to Visual Studio Output window
- Enable in Release build by modifying `appsettings.json`

**EF Core Logging**:
- All database operations logged to `ef_core_exceptions.log`
- Enable sensitive data logging for detailed queries

#### External Tools

**SQLite Browser**:
- Download: https://sqlitebrowser.org/
- Use to inspect database contents and structure

**Process Monitor** (Sysinternals):
- Monitor file system and registry access
- Download: https://learn.microsoft.com/sysinternals/downloads/procmon

**Performance Monitor** (Windows):
- Monitor application performance counters
- Track memory, CPU, disk I/O

### 11.3 Error Messages Reference

| Error Code | Message | Resolution |
|------------|---------|------------|
| DB-001 | Database file not found | Restart application to recreate |
| DB-002 | Database corruption detected | Restore from backup |
| EKMS-001 | EKMS2.exe not found | Verify EKMS2.exe in app directory |
| EKMS-002 | Invalid binary file | Verify file format |
| PORT-001 | No COM ports available | Check device drivers |
| PORT-002 | Port access denied | Check port permissions |
| CRC-001 | CRC validation failed | Verify data integrity |

### 11.4 Support Escalation

When to escalate:
- Unresolved issues after 24 hours
- Data loss suspected
- Security incident
- Performance degradation affecting operations

**Information to Collect**:
1. Error logs (`global_exceptions.log`, `ef_core_exceptions.log`)
2. Application version
3. Windows version and .NET runtime version
4. Steps to reproduce
5. Screenshots of error messages

---

## 12. Configuration Settings

### 12.1 Application Configuration

#### appsettings.json

Location: `ReceivedKeyProcessorApp/appsettings.json`

```json
{
  "AppConfig": {
    "configurationsFolder": "ReceivedKeyProcessorApp\\Configurations",
    "appPropertiesFileName": "AppProperties.json",
    "privacyStatement": "https://YourPrivacyUrlGoesHere/"
  },
  "SaveDirectory": "C:\\a\\a_test",
  "LastBrowseDirectory": "C:\\a\\a_test"
}
```

#### Settings

| Setting | Description | Default |
|---------|-------------|---------|
| `SaveDirectory` | Default save directory for exports | User-configurable |
| `LastBrowseDirectory` | Last used browse directory | User-configurable |
| `configurationsFolder` | Configuration files location | `Configurations/` |
| `privacyStatement` | Privacy policy URL | Configure as needed |

### 12.2 User Settings

#### Settings File

Location: `%APPDATA%\ReceiveKeyProcessingUtility\settings.json`

User-specific settings persist across application sessions:
- Theme preferences
- Window sizes and positions
- Last used directories
- Serial port configuration

### 12.3 Database Configuration

#### Custom Database Path

Set custom database path in code:

```csharp
// Call before any database operations
Infrastructure.Data.KeyContext.CustomDatabasePath = @"C:\CustomPath\keys.db";
```

#### EF Core Configuration

Located in `KeyContext.OnConfiguring()`:

```csharp
optionsBuilder.UseSqlite($"Data Source={GetDatabasePath()}",
    options => options.MigrationsAssembly("ReceivedKeyProcessorApp.Infrastructure"));

optionsBuilder.LogTo(Console.WriteLine, LogLevel.Information);
optionsBuilder.EnableSensitiveDataLogging(true);
optionsBuilder.EnableDetailedErrors(true);
optionsBuilder.AddInterceptors(new EfCoreExceptionInterceptor());
```

### 12.4 Logging Configuration

#### Log File Locations

- `global_exceptions.log`: Application directory
- `ef_core_exceptions.log`: Application directory
- `RKPA_8727_Import.log`: Temp directory
- `RKPA_EKMS2_Service.log`: Temp directory
- `ReceivedKeyProcessorApp_Debug.log`: `%TEMP%`

#### Log Level Configuration

Modify `appsettings.json`:

```json
{
  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft.EntityFrameworkCore": "Information",
      "Microsoft.EntityFrameworkCore.Database.Command": "Information"
    }
  }
}
```

### 12.5 Serial Port Configuration

Serial port settings are configured via application UI:
- Baud rate: Configurable (default: 9600)
- Data bits: 8
- Stop bits: 1
- Parity: None

### 12.6 Equipment ID Configuration

Equipment ID lookup table: `Resources/EquipmentIds.json`

Contains equipment IDs for binary tag validation. Custom IDs can be added by modifying this file.

---

## 13. Maintenance Tasks

### 13.1 Daily Tasks

- [ ] Review `global_exceptions.log` for new errors
- [ ] Verify database integrity
- [ ] Check available disk space
- [ ] Monitor application performance

### 13.2 Weekly Tasks

- [ ] Backup database and configuration files
- [ ] Review and rotate log files
- [ ] Verify EKMS2.exe functionality
- [ ] Test serial port connectivity

### 13.3 Monthly Tasks

- [ ] Archive old backups
- [ ] Review security logs
- [ ] Update application if new version available
- [ ] Perform full system backup

### 13.4 Quarterly Tasks

- [ ] Disaster recovery drill
- [ ] Performance audit
- [ ] Security audit
- [ ] User training refresher

---

## 14. Contact and Support

### 14.1 Technical Support

For technical issues or questions:

1. **Check Documentation**: Review this guide and other documentation
2. **Review Logs**: Check application logs for error details
3. **Known Issues**: Review known issues list
4. **Contact Support**: Escalate per organization procedures

### 14.2 Documentation References

- **README.md**: General application overview
- **CLAUDE.md**: Developer guidance and architecture
- **EKMS2_Integration_Documentation.md**: EKMS2.exe integration details
- **MIDS_JTRS_Implementation.md**: MIDS JTRS tag specification
- **DS-100-1_Implementation.md**: DS-100-1 TrKEK specification

### 14.3 Version Information

- **Application Version**: 1.0.107
- **Document Version**: 1.1
- **Last Updated**: 2026-05-18
- **.NET Version**: 8.0
- **EF Core Version**: 8.0

---

## Appendix A: Quick Reference

### A.1 File Paths

| Item | Path |
|------|------|
| Application | `C:\Program Files\ReceivedKeyProcessorApp\` |
| Database | `%LOCALAPPDATA%\ReceivedKeyProcessorApp\keys.db` |
| User Settings | `%APPDATA%\ReceiveKeyProcessingUtility\settings.json` |
| Logs | Application directory |
| Temp Files | `%TEMP%\RKPA_Temp\` |

### A.2 Service Ports

| Service | Port | Protocol |
|---------|------|----------|
| Serial Port | COM1-COM256 | RS-232 |

### A.3 Diagnostic Commands

```bash
# Check .NET runtime version
dotnet --info

# List COM ports
[System.IO.Ports.SerialPort]::GetPortNames()

# Database integrity check
sqlite3 "%LOCALAPPDATA%\ReceivedKeyProcessorApp\keys.db" "PRAGMA integrity_check;"

# Backup database
copy "%LOCALAPPDATA%\ReceivedKeyProcessorApp\keys.db" "keys_backup.db"

# Clear log files
del global_exceptions.log
del ef_core_exceptions.log
```

---

## Appendix B: Glossary

| Term | Definition |
|------|------------|
| 8727 Format | Binary file format for cryptographic key data |
| CRC | Cyclic Redundancy Check, used for data validation |
| DS-100-1 | Transfer Key Encryption Key specification |
| EKMS | Electronic Key Management System |
| EKMS2.exe | External tool for converting 8727 binary files |
| EF Core | Entity Framework Core, ORM for .NET |
| FDU | Fill Data Unit, container for cryptographic key data |
| load.exe | External tool for sending FDUs via serial port |
| MIDS JTRS | Joint Tactical Radio System, tactical radio standard |
| OTAR | Over-The-Air Rekeying |
| Prepend FDU | Option to automatically add FDU header (0x01B0) to transmissions |
| SQLite | Embedded SQL database engine |
| Tier3 | XML format for key data transmission |
| TrKEK | Transfer Key Encryption Key |
| WII | Waveform Instance Identifier |

---

**End of Document**