PasswordStoreService.cs 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. using Microsoft.Win32;
  2. namespace NetTool.Client.Services;
  3. public sealed class PasswordStoreService
  4. {
  5. private const string RegistryPath = @"Software\NetTool";
  6. private const string DevicePasswordPrefix = "DevicePassword_";
  7. public string LoadPassword(string deviceKey)
  8. {
  9. var valueName = GetValueName(deviceKey);
  10. if (string.IsNullOrWhiteSpace(valueName))
  11. {
  12. return string.Empty;
  13. }
  14. using var key = Registry.CurrentUser.OpenSubKey(RegistryPath, writable: false);
  15. return key?.GetValue(valueName) as string ?? string.Empty;
  16. }
  17. public void SavePassword(string deviceKey, string password)
  18. {
  19. var valueName = GetValueName(deviceKey);
  20. if (string.IsNullOrWhiteSpace(valueName))
  21. {
  22. return;
  23. }
  24. using var key = Registry.CurrentUser.CreateSubKey(RegistryPath);
  25. key.SetValue(valueName, password, RegistryValueKind.String);
  26. }
  27. public void ClearPassword(string deviceKey)
  28. {
  29. var valueName = GetValueName(deviceKey);
  30. if (string.IsNullOrWhiteSpace(valueName))
  31. {
  32. return;
  33. }
  34. using var key = Registry.CurrentUser.OpenSubKey(RegistryPath, writable: true);
  35. key?.DeleteValue(valueName, throwOnMissingValue: false);
  36. }
  37. private static string GetValueName(string deviceKey)
  38. {
  39. var normalized = new string(deviceKey
  40. .Where(char.IsLetterOrDigit)
  41. .Select(char.ToUpperInvariant)
  42. .ToArray());
  43. return string.IsNullOrWhiteSpace(normalized) ? string.Empty : DevicePasswordPrefix + normalized;
  44. }
  45. }