using System.Text.Json; using LehrerApp.Sync.Crypto; namespace LehrerApp.Sync; /// /// Selbstverwalteter Wiederherstellungsweg für den lokalen Sync-Schlüssel (TODO 10.3.2). Anders /// als das Geräte-Pairing () läuft das komplett offline, ohne /// Server-Beteiligung: der Nutzer sichert die verschlüsselte Schlüsseldatei selbst (z.B. /// USB-Stick, eigene Cloud) und merkt sich den Code getrennt davon — Datei und Code zusammen /// ergeben erst den Schlüssel. /// public class SyncKeyRecoveryService(byte[] syncKey, string keyPath) { public string CreateRecoveryFile(string code) => JsonSerializer.Serialize(new SyncKeyRecoveryFile( SyncCrypto.EncryptKeyWithRecoveryCode(syncKey, code), DateTime.UtcNow)); /// /// Falscher Code oder beschädigte/manipulierte Datei. /// Datei ist kein gültiges Wiederherstellungsformat. public void RestoreFromFile(string fileContent, string code) { var file = JsonSerializer.Deserialize(fileContent); if (file is null || string.IsNullOrWhiteSpace(file.WrappedKey)) throw new InvalidOperationException("Ungültige Wiederherstellungsdatei."); var restoredKey = SyncCrypto.DecryptKeyWithRecoveryCode(file.WrappedKey, code); SyncCrypto.SaveKey(restoredKey, keyPath); } } public record SyncKeyRecoveryFile(string WrappedKey, DateTime CreatedAt);