using System.Security.Cryptography; using System.Text; using HaloPixelToolBox.Backend.Utilities; using XFEExtension.NetCore.AutoConfig; using XFEExtension.NetCore.WinUIHelper.Utilities.Helper; namespace HaloPixelToolBox.Backend.Profiles.CacheProfiles; public partial class CacheProfile : XFEProfile { private static readonly byte[] s_passwordEntropy = Encoding.UTF8.GetBytes("HaloPixelToolBox.Backend.AdministratorCredential.v1"); public CacheProfile() => ProfilePath = $@"{AppPathHelper.CacheProfile}\{nameof(CacheProfile)}"; [ProfileProperty] private string _session = string.Empty; [ProfileProperty] private string _account = "admin"; /// /// 由 Windows 当前用户数据保护机制加密后的管理员密码。 /// [ProfileProperty] private string _encryptedPassword = string.Empty; /// /// 用于管理端自动登录的密码;磁盘中仅保存当前 Windows 用户可解密的密文。 /// public static string Password { get { if (string.IsNullOrWhiteSpace(EncryptedPassword)) return string.Empty; try { var encryptedBytes = Convert.FromBase64String(EncryptedPassword); var passwordBytes = WindowsDataProtection.Unprotect(encryptedBytes, s_passwordEntropy); try { return Encoding.UTF8.GetString(passwordBytes); } finally { CryptographicOperations.ZeroMemory(passwordBytes); } } catch (Exception ex) when (ex is FormatException or System.ComponentModel.Win32Exception) { EncryptedPassword = string.Empty; return string.Empty; } } set { if (string.IsNullOrEmpty(value)) { EncryptedPassword = string.Empty; return; } var passwordBytes = Encoding.UTF8.GetBytes(value); try { var encryptedBytes = WindowsDataProtection.Protect(passwordBytes, s_passwordEntropy); EncryptedPassword = Convert.ToBase64String(encryptedBytes); } finally { CryptographicOperations.ZeroMemory(passwordBytes); } } } }