78 lines
2.4 KiB
C#
78 lines
2.4 KiB
C#
using System.Management;
|
|
using System.Text.Json;
|
|
using Livia.Properties;
|
|
using Microsoft.Extensions.Logging;
|
|
|
|
namespace Livia.Models;
|
|
|
|
public interface ISerialKeyManager
|
|
{
|
|
bool Validate();
|
|
string HardwareId { get; }
|
|
string EncryptLicense(AuthenticationKeyLicense license);
|
|
}
|
|
|
|
public readonly record struct AuthenticationKeyLicense
|
|
{
|
|
public string HardwareId { get; init; }
|
|
public DateTime ExpireDateTime { get; init; }
|
|
}
|
|
|
|
internal class SerialKeyManager : ISerialKeyManager
|
|
{
|
|
private readonly ILogger _logger;
|
|
private readonly IAesOperation _aesOperation;
|
|
public string HardwareId { get; } = string.Empty;
|
|
|
|
private const string AesKey = "L2CzateeJgdwxVA6ipQ8aj4sxvTWTzd4";
|
|
|
|
public SerialKeyManager(ILogger logger, IAesOperation aesOperation)
|
|
{
|
|
_logger = logger;
|
|
_aesOperation = aesOperation;
|
|
|
|
using ManagementObjectSearcher searcher = new("select UUID from Win32_ComputerSystemProduct");
|
|
|
|
ManagementObjectCollection information = searcher.Get();
|
|
foreach (ManagementBaseObject? obj in information)
|
|
{
|
|
foreach (PropertyData data in obj.Properties)
|
|
{
|
|
_logger.LogInformation("{name} = {value}", data.Name, data.Value);
|
|
HardwareId = (string)data.Value;
|
|
}
|
|
}
|
|
}
|
|
|
|
public bool Validate()
|
|
{
|
|
string authenticationKey = Settings.Default.AuthenticationKey;
|
|
_logger.LogInformation("AuthenticationKey = {value}", Settings.Default.AuthenticationKey);
|
|
string jsonString = _aesOperation.DecryptString(AesKey, authenticationKey);
|
|
|
|
try
|
|
{
|
|
AuthenticationKeyLicense license = JsonSerializer.Deserialize<AuthenticationKeyLicense>(jsonString);
|
|
if (!string.Equals(HardwareId, license.HardwareId))
|
|
throw new Exception("Hardware ID mismatch");
|
|
|
|
if (license.ExpireDateTime < DateTime.Now)
|
|
throw new Exception("Auth key expired");
|
|
|
|
return true;
|
|
}
|
|
catch (Exception e)
|
|
{
|
|
_logger.LogError(e, "Cannot decrypt auth key");
|
|
}
|
|
|
|
//reset to empty if incorrect
|
|
Settings.Default.AuthenticationKey = string.Empty;
|
|
return false;
|
|
}
|
|
|
|
public string EncryptLicense(AuthenticationKeyLicense license)
|
|
{
|
|
return _aesOperation.EncryptString(AesKey, JsonSerializer.Serialize(license));
|
|
}
|
|
} |