XFE Git
XFE Studio Git
Git 首页 全局搜索
XFE 主站 文档 NuGet

HaloPixelToolBox

【WinUI3】基于USB HID通讯的花再音响工具箱

公开
关注 0 Fork 0 Star 0
UTF-8
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";

    /// <summary>
    /// 由 Windows 当前用户数据保护机制加密后的管理员密码。
    /// </summary>
    [ProfileProperty]
    private string _encryptedPassword = string.Empty;

    /// <summary>
    /// 用于管理端自动登录的密码;磁盘中仅保存当前 Windows 用户可解密的密文。
    /// </summary>
    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);
            }
        }
    }
}