|
| 1 | +using System.Runtime.Versioning; |
| 2 | +using System.Security.Cryptography; |
| 3 | +using System.Text; |
| 4 | +using Aquiis.Infrastructure.Interfaces; |
| 5 | + |
| 6 | +namespace Aquiis.Infrastructure.Services; |
| 7 | + |
| 8 | +/// <summary> |
| 9 | +/// Secure key storage for Windows using DPAPI (Data Protection API). |
| 10 | +/// Encrypts the database password with the current user's Windows credentials |
| 11 | +/// and stores it in a file under %APPDATA%\Aquiis\. Only the same user on the |
| 12 | +/// same machine can decrypt the file — no user interaction needed on retrieval. |
| 13 | +/// </summary> |
| 14 | +[SupportedOSPlatform("windows")] |
| 15 | +public class WindowsKeychainService : IKeychainService |
| 16 | +{ |
| 17 | + private readonly string _keyFilePath; |
| 18 | + |
| 19 | + /// <summary> |
| 20 | + /// Initialize the Windows DPAPI keychain service. |
| 21 | + /// </summary> |
| 22 | + /// <param name="appName">App-specific identifier to prevent key conflicts (e.g. "SimpleStart-Electron")</param> |
| 23 | + public WindowsKeychainService(string appName = "Aquiis-Electron") |
| 24 | + { |
| 25 | + var appDataPath = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData); |
| 26 | + var aquiisDir = Path.Combine(appDataPath, "Aquiis"); |
| 27 | + Directory.CreateDirectory(aquiisDir); |
| 28 | + |
| 29 | + // Sanitize appName for use as a filename component |
| 30 | + var safeAppName = new string(appName.Where(c => char.IsLetterOrDigit(c) || c == '-' || c == '_').ToArray()); |
| 31 | + _keyFilePath = Path.Combine(aquiisDir, $"aquiis_{safeAppName}.key"); |
| 32 | + |
| 33 | + Console.WriteLine($"[WindowsKeychainService] Initialized with key file: {_keyFilePath}"); |
| 34 | + } |
| 35 | + |
| 36 | + /// <summary> |
| 37 | + /// Store the encryption password using DPAPI. The data is encrypted with the |
| 38 | + /// current user's credentials and written to a binary key file. |
| 39 | + /// </summary> |
| 40 | + public bool StoreKey(string password, string label = "Aquiis Database Encryption Key") |
| 41 | + { |
| 42 | + try |
| 43 | + { |
| 44 | + Console.WriteLine("[WindowsKeychainService] Storing password using DPAPI"); |
| 45 | + var plainBytes = Encoding.UTF8.GetBytes(password); |
| 46 | + var encryptedBytes = ProtectedData.Protect(plainBytes, null, DataProtectionScope.CurrentUser); |
| 47 | + File.WriteAllBytes(_keyFilePath, encryptedBytes); |
| 48 | + Console.WriteLine("[WindowsKeychainService] Password stored successfully using DPAPI"); |
| 49 | + return true; |
| 50 | + } |
| 51 | + catch (Exception ex) |
| 52 | + { |
| 53 | + Console.WriteLine($"[WindowsKeychainService] Failed to store password: {ex.Message}"); |
| 54 | + return false; |
| 55 | + } |
| 56 | + } |
| 57 | + |
| 58 | + /// <summary> |
| 59 | + /// Retrieve the encryption password by decrypting the key file with DPAPI. |
| 60 | + /// Returns null if the file does not exist or cannot be decrypted. |
| 61 | + /// </summary> |
| 62 | + public string? RetrieveKey() |
| 63 | + { |
| 64 | + if (!File.Exists(_keyFilePath)) |
| 65 | + { |
| 66 | + Console.WriteLine("[WindowsKeychainService] Key file not found"); |
| 67 | + return null; |
| 68 | + } |
| 69 | + |
| 70 | + try |
| 71 | + { |
| 72 | + Console.WriteLine("[WindowsKeychainService] Retrieving password using DPAPI"); |
| 73 | + var encryptedBytes = File.ReadAllBytes(_keyFilePath); |
| 74 | + var plainBytes = ProtectedData.Unprotect(encryptedBytes, null, DataProtectionScope.CurrentUser); |
| 75 | + var password = Encoding.UTF8.GetString(plainBytes); |
| 76 | + Console.WriteLine($"[WindowsKeychainService] Password retrieved successfully using DPAPI (length: {password.Length})"); |
| 77 | + return password; |
| 78 | + } |
| 79 | + catch (CryptographicException ex) |
| 80 | + { |
| 81 | + Console.WriteLine($"[WindowsKeychainService] Failed to decrypt password (DPAPI): {ex.Message}"); |
| 82 | + Console.WriteLine("[WindowsKeychainService] This usually means the key file was encrypted by a different user or machine"); |
| 83 | + return null; |
| 84 | + } |
| 85 | + catch (Exception ex) |
| 86 | + { |
| 87 | + Console.WriteLine($"[WindowsKeychainService] Failed to retrieve password: {ex.Message}"); |
| 88 | + return null; |
| 89 | + } |
| 90 | + } |
| 91 | + |
| 92 | + /// <summary> |
| 93 | + /// Delete the key file, effectively removing the stored password. |
| 94 | + /// </summary> |
| 95 | + public bool RemoveKey() |
| 96 | + { |
| 97 | + try |
| 98 | + { |
| 99 | + if (File.Exists(_keyFilePath)) |
| 100 | + { |
| 101 | + File.Delete(_keyFilePath); |
| 102 | + Console.WriteLine("[WindowsKeychainService] Key file deleted successfully"); |
| 103 | + } |
| 104 | + return true; |
| 105 | + } |
| 106 | + catch (Exception ex) |
| 107 | + { |
| 108 | + Console.WriteLine($"[WindowsKeychainService] Failed to remove key file: {ex.Message}"); |
| 109 | + return false; |
| 110 | + } |
| 111 | + } |
| 112 | + |
| 113 | + /// <summary> |
| 114 | + /// DPAPI is always available on Windows. |
| 115 | + /// </summary> |
| 116 | + public bool IsAvailable() => OperatingSystem.IsWindows(); |
| 117 | +} |
0 commit comments