| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354 |
- using Microsoft.Win32;
- namespace NetworkTool.Client.Services;
- public sealed class PasswordStoreService
- {
- private const string RegistryPath = @"Software\NetworkTool";
- private const string DevicePasswordPrefix = "DevicePassword_";
- public string LoadPassword(string deviceKey)
- {
- var valueName = GetValueName(deviceKey);
- if (string.IsNullOrWhiteSpace(valueName))
- {
- return string.Empty;
- }
- using var key = Registry.CurrentUser.OpenSubKey(RegistryPath, writable: false);
- return key?.GetValue(valueName) as string ?? string.Empty;
- }
- public void SavePassword(string deviceKey, string password)
- {
- var valueName = GetValueName(deviceKey);
- if (string.IsNullOrWhiteSpace(valueName))
- {
- return;
- }
- using var key = Registry.CurrentUser.CreateSubKey(RegistryPath);
- key.SetValue(valueName, password, RegistryValueKind.String);
- }
- public void ClearPassword(string deviceKey)
- {
- var valueName = GetValueName(deviceKey);
- if (string.IsNullOrWhiteSpace(valueName))
- {
- return;
- }
- using var key = Registry.CurrentUser.OpenSubKey(RegistryPath, writable: true);
- key?.DeleteValue(valueName, throwOnMissingValue: false);
- }
- private static string GetValueName(string deviceKey)
- {
- var normalized = new string(deviceKey
- .Where(char.IsLetterOrDigit)
- .Select(char.ToUpperInvariant)
- .ToArray());
- return string.IsNullOrWhiteSpace(normalized) ? string.Empty : DevicePasswordPrefix + normalized;
- }
- }
|