增加主板绑定的离线签名授权与自然月试用

This commit is contained in:
tfarcraw 2026-11-23 09:27:25 +08:00
parent db64c27267
commit 5ebd36124f
8 changed files with 451 additions and 0 deletions

View File

@ -0,0 +1,149 @@
using System.Security.Cryptography;
using System.Text;
using System.Text.Json;
namespace SopHelper.Engine.Licensing;
/// <summary>发行方签名的授权内容;Month 表示一次性延长一个自然月,Permanent 表示永久。</summary>
public sealed record LicenseGrant(int Version, string Id, string Machine, string Kind, DateTimeOffset IssuedUtc);
/// <summary>界面使用的授权快照;到期时刻采用 UTC,显示时由客户端转换为本地时间。</summary>
public sealed record LicenseStatus(bool Allowed, bool Permanent, DateTimeOffset? ExpiresUtc, string Message);
/// <summary>存储受保护的试用起点、已兑换码及时间水位;实现必须在损坏时抛错,禁止重建试用。</summary>
public interface ILicenseStore
{
byte[]? Read();
void Write(byte[] value);
}
/// <summary>离线授权状态机:验签、主板匹配、防重复兑换与时间回拨检查集中在此处理。</summary>
public sealed class LicenseService
{
private sealed record State(string Machine, DateTimeOffset StartedUtc, DateTimeOffset LastUtc,
DateTimeOffset ExpiresUtc, bool Permanent, List<string> UsedIds);
private readonly ILicenseStore _store;
private readonly string _publicKey;
private readonly Func<DateTimeOffset> _clock;
private readonly object _sync = new();
public string Machine { get; }
/// <summary>注入时钟及存储便于验证边界;生产环境使用嵌入公钥,禁止通过配置替换信任根。</summary>
public LicenseService(string machine, ILicenseStore store, string publicKey, Func<DateTimeOffset>? clock = null)
{
if (!IsMachineCode(machine)) throw new ArgumentException("主板机器码无效");
Machine = machine; _store = store; _publicKey = publicKey; _clock = clock ?? (() => DateTimeOffset.UtcNow);
}
/// <summary>从程序集读取发行方公钥;私钥不参与客户端构建。</summary>
public static string ReadIssuerPublicKey()
{
using var stream = typeof(LicenseService).Assembly.GetManifestResourceStream(
"SopHelper.CrossPlatform.Engine.Licensing.issuer-public.pem") ?? throw new InvalidDataException("缺少授权公钥");
using var reader = new StreamReader(stream);
return reader.ReadToEnd();
}
/// <summary>检查并持久化时间水位;首次运行从当前 UTC 时刻开始试用一个自然月。</summary>
public LicenseStatus Check()
{
lock (_sync)
{
try
{
using var lease = AcquireLease();
var now = _clock();
var state = Load(now);
if (!state.Permanent && now < state.LastUtc.AddMinutes(-5))
return new(false, false, state.ExpiresUtc, "检测到系统时间回拨,请恢复正确时间后重试。");
state = state with { LastUtc = now > state.LastUtc ? now : state.LastUtc };
Save(state);
return Describe(state, now);
}
catch (Exception error) { return new(false, false, null, "授权检查失败:" + error.Message); }
}
}
/// <summary>仅在签名、版本、机器码及兑换记录均有效时写盘;写盘失败不视为激活成功。</summary>
public LicenseStatus Activate(string code)
{
lock (_sync)
{
using var lease = AcquireLease();
var grant = Verify(code);
var now = _clock();
if (grant.Machine != Machine) throw new InvalidOperationException("授权码与本机主板不匹配。");
if (grant.IssuedUtc > now.AddMinutes(5)) throw new InvalidOperationException("授权码签发时间晚于系统时间,请校准时间。");
var state = Load(now);
if (!state.Permanent && now < state.LastUtc.AddMinutes(-5))
throw new InvalidOperationException("请先恢复正确的系统时间。");
if (state.UsedIds.Contains(grant.Id)) throw new InvalidOperationException("此授权码已经使用,不能重复延长。");
if (state.Permanent) throw new InvalidOperationException("本机已永久授权,无需再次激活。");
var permanent = grant.Kind == "Permanent";
var basis = state.ExpiresUtc > now ? state.ExpiresUtc : now;
state = state with { Permanent = permanent, ExpiresUtc = permanent ? state.ExpiresUtc : basis.AddMonths(1),
LastUtc = now > state.LastUtc ? now : state.LastUtc, UsedIds = [.. state.UsedIds, grant.Id] };
Save(state);
return Describe(state, now);
}
}
private LicenseGrant Verify(string code)
{
try
{
if (code.Length > 16384) throw new FormatException();
var parts = string.Concat(code.Where(c => !char.IsWhiteSpace(c))).Split('.');
if (parts.Length != 3 || parts[0] != "AISOP1") throw new FormatException();
var payload = Convert.FromBase64String(parts[1]);
using var rsa = RSA.Create(); rsa.ImportFromPem(_publicKey);
if (!rsa.VerifyData(payload, Convert.FromBase64String(parts[2]), HashAlgorithmName.SHA256, RSASignaturePadding.Pss))
throw new FormatException();
var grant = JsonSerializer.Deserialize<LicenseGrant>(payload) ?? throw new FormatException();
if (grant.Version != 1 || !Guid.TryParseExact(grant.Id, "N", out _) || !IsMachineCode(grant.Machine)
|| grant.Kind is not ("Month" or "Permanent") || grant.IssuedUtc == default) throw new FormatException();
return grant;
}
catch (Exception e) when (e is FormatException or JsonException or CryptographicException or ArgumentException)
{ throw new InvalidOperationException("授权码无效、内容被修改或签名不可信。", e); }
}
private State Load(DateTimeOffset now)
{
var bytes = _store.Read();
if (bytes is null) return new(Machine, now, now, now.AddMonths(1), false, []);
var state = JsonSerializer.Deserialize<State>(bytes) ?? throw new InvalidDataException("授权记录为空");
if (state.Machine != Machine) throw new InvalidDataException("主板已更换或授权记录来自其他电脑,请联系发行方。");
if (state.StartedUtc == default || state.LastUtc < state.StartedUtc || state.ExpiresUtc <= state.StartedUtc
|| state.UsedIds is null) throw new InvalidDataException("授权记录损坏,请恢复备份并联系发行方。");
return state;
}
private void Save(State state) => _store.Write(JsonSerializer.SerializeToUtf8Bytes(state));
// 多个软件实例必须串行读取和更新,防止同一码并发兑换或新实例覆盖已延长的有效期。
private IDisposable AcquireLease()
{
var mutex = new Mutex(false, "AISOP-License-" + Machine);
try
{
try { if (!mutex.WaitOne(TimeSpan.FromSeconds(10))) throw new IOException("授权记录正在被其他实例更新,请重试"); }
catch (AbandonedMutexException) { /* 前一进程退出后仍持有此锁;当前线程已接管锁。 */ }
return new Lease(mutex);
}
catch { mutex.Dispose(); throw; }
}
private sealed class Lease(Mutex mutex) : IDisposable
{
public void Dispose() { mutex.ReleaseMutex(); mutex.Dispose(); }
}
private static LicenseStatus Describe(State state, DateTimeOffset now) => state.Permanent
? new(true, true, null, "永久授权(已绑定本机主板)")
: new(now < state.ExpiresUtc, false, state.ExpiresUtc,
$"{(state.UsedIds.Count == 0 ? "试用" : "短期授权")}{(now < state.ExpiresUtc ? "有效至" : "已到期于")} {state.ExpiresUtc.ToLocalTime():yyyy-MM-dd HH:mm},{(now < state.ExpiresUtc ? "可输入授权码续期" : "请输入授权码后继续使用")}。");
/// <summary>机器码仅暴露主板标识的 SHA-256,不在授权码里存储原始硬件序列号。</summary>
public static string MachineCode(string hardwareIdentity) => Convert.ToHexString(SHA256.HashData(Encoding.UTF8.GetBytes("AISOP1|" + hardwareIdentity.Trim().ToUpperInvariant())));
private static bool IsMachineCode(string value) => value is { Length: 64 } && value.All(c => c is >= '0' and <= '9' or >= 'A' and <= 'F');
}

View File

@ -0,0 +1,50 @@
using System.Diagnostics;
using System.Text.Json;
namespace SopHelper.Engine.Licensing;
/// <summary>读取固件主板序列号;无法识别时明确拒绝,不能退回所有机器共用的空值或随机值。</summary>
public static class MotherboardIdentity
{
/// <summary>Windows 通过 CIM 读取主板,Linux 读取 DMI;更换硬盘或移动程序目录不改变机器码。</summary>
public static string ReadMachineCode()
{
string serial, vendor, model;
if (OperatingSystem.IsWindows())
{
var info = new ProcessStartInfo("powershell.exe")
{ UseShellExecute = false, CreateNoWindow = true, RedirectStandardOutput = true, RedirectStandardError = true };
foreach (var argument in new[] { "-NoProfile", "-NonInteractive", "-Command",
"$ErrorActionPreference='Stop'; Get-CimInstance Win32_BaseBoard | Select-Object -First 1 SerialNumber,Manufacturer,Product | ConvertTo-Json -Compress" })
info.ArgumentList.Add(argument);
using var process = Process.Start(info) ?? throw new InvalidOperationException("无法读取主板信息");
var output = process.StandardOutput.ReadToEndAsync();
var error = process.StandardError.ReadToEndAsync();
if (!process.WaitForExit(15000)) { process.Kill(true); throw new TimeoutException("读取主板信息超时"); }
if (process.ExitCode != 0) throw new InvalidOperationException("读取主板信息失败,请检查 Windows CIM 服务:" + error.GetAwaiter().GetResult());
using var data = JsonDocument.Parse(output.GetAwaiter().GetResult());
serial = data.RootElement.GetProperty("SerialNumber").GetString() ?? "";
vendor = data.RootElement.GetProperty("Manufacturer").GetString() ?? "";
model = data.RootElement.GetProperty("Product").GetString() ?? "";
}
else if (OperatingSystem.IsLinux())
{
serial = File.ReadAllText("/sys/class/dmi/id/board_serial");
vendor = File.ReadAllText("/sys/class/dmi/id/board_vendor");
model = File.ReadAllText("/sys/class/dmi/id/board_name");
}
else throw new PlatformNotSupportedException("当前平台不支持读取主板信息");
return FromBoard(serial, vendor, model);
}
/// <summary>过滤厂商占位序列号,防止没有真实序列号的不同主板生成相同机器码。</summary>
public static string FromBoard(string serial, string vendor, string model)
{
var normalized = serial.Trim().ToUpperInvariant();
if (normalized.Length < 4 || normalized.All(c => c is '0' or 'F' or '-' or ' ')
|| new[] { "DEFAULT", "TO BE FILLED", "UNKNOWN", "NONE", "NOT SPECIFIED", "SYSTEM SERIAL", "INVALID", "N/A", "OEM" }
.Any(normalized.Contains))
throw new InvalidOperationException("主板未提供有效序列号,无法绑定授权,请联系设备供应商。");
return LicenseService.MachineCode($"{vendor.Trim()}|{model.Trim()}|{normalized}");
}
}

View File

@ -0,0 +1,111 @@
using System.ComponentModel;
using System.Runtime.InteropServices;
using System.Security.Cryptography;
using System.Text;
using Microsoft.Win32;
namespace SopHelper.Engine.Licensing;
/// <summary>授权记录独立于安装目录;Windows 使用当前账号 DPAPI 并镜像到注册表,避免重装或删单个文件重置试用。</summary>
public sealed class ProtectedLicenseStore : ILicenseStore
{
private const string RegistryPath = @"Software\Bellwether\AISOP\Licensing";
private readonly string _path;
private readonly byte[] _entropy;
/// <summary>固定用户数据目录,不受配方工作区和程序位置影响;Linux 使用主板派生密钥及仅本人可读写权限。</summary>
public ProtectedLicenseStore(string machine)
{
_path = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "Bellwether", "AISOP", "license.dat");
_entropy = SHA256.HashData(Encoding.UTF8.GetBytes("AISOP-state-v1|" + machine));
}
/// <summary>文件和镜像均存在时必须一致;损坏、主板不匹配和权限错误均上抛,禁止静默重置。</summary>
public byte[]? Read()
{
byte[]? file = File.Exists(_path) ? File.ReadAllBytes(_path) : null;
if (OperatingSystem.IsWindows())
{
using var key = Registry.CurrentUser.OpenSubKey(RegistryPath);
var mirror = key?.GetValue("State") as byte[];
if (file is not null && mirror is not null && !file.SequenceEqual(mirror))
throw new InvalidDataException("授权文件与注册表记录不一致,请恢复一致的备份并联系发行方。");
file ??= mirror;
}
if (file is null) return null;
return OperatingSystem.IsWindows() ? Dpapi(file, false) : Decrypt(file);
}
/// <summary>先原子替换文件,再写入相同密文的注册表镜像;任一步失败都必须向调用方报告。</summary>
public void Write(byte[] value)
{
var encrypted = OperatingSystem.IsWindows() ? Dpapi(value, true) : Encrypt(value);
var directory = Path.GetDirectoryName(_path)!;
Directory.CreateDirectory(directory);
if (!OperatingSystem.IsWindows()) File.SetUnixFileMode(directory, UnixFileMode.UserRead | UnixFileMode.UserWrite | UnixFileMode.UserExecute);
var temporary = _path + ".tmp";
File.WriteAllBytes(temporary, encrypted);
if (!OperatingSystem.IsWindows()) File.SetUnixFileMode(temporary, UnixFileMode.UserRead | UnixFileMode.UserWrite);
File.Move(temporary, _path, true);
if (OperatingSystem.IsWindows())
{
using var key = Registry.CurrentUser.CreateSubKey(RegistryPath);
key.SetValue("State", encrypted, RegistryValueKind.Binary);
key.Flush();
}
}
// Linux 没有 DPAPI;此密钥只阻止随意编辑,无法抵御具有本机调试能力的管理员。
private byte[] Encrypt(byte[] value)
{
var result = new byte[28 + value.Length];
RandomNumberGenerator.Fill(result.AsSpan(0, 12));
using var aes = new AesGcm(_entropy, 16);
aes.Encrypt(result.AsSpan(0, 12), value, result.AsSpan(28), result.AsSpan(12, 16));
return result;
}
private byte[] Decrypt(byte[] value)
{
if (value.Length < 28) throw new InvalidDataException("授权记录损坏");
var result = new byte[value.Length - 28];
using var aes = new AesGcm(_entropy, 16);
aes.Decrypt(value.AsSpan(0, 12), value.AsSpan(28), value.AsSpan(12, 16), result);
return result;
}
// 使用系统 DPAPI 避免引入额外运行时包;所有非托管缓冲区由当前调用负责释放。
private byte[] Dpapi(byte[] value, bool protect)
{
var input = new Blob { Length = value.Length, Data = Marshal.AllocHGlobal(value.Length) };
var entropy = new Blob { Length = _entropy.Length, Data = Marshal.AllocHGlobal(_entropy.Length) };
var output = new Blob();
try
{
Marshal.Copy(value, 0, input.Data, value.Length);
Marshal.Copy(_entropy, 0, entropy.Data, _entropy.Length);
var success = protect
? CryptProtectData(ref input, null, ref entropy, IntPtr.Zero, IntPtr.Zero, 1, out output)
: CryptUnprotectData(ref input, IntPtr.Zero, ref entropy, IntPtr.Zero, IntPtr.Zero, 1, out output);
if (!success) throw new Win32Exception(Marshal.GetLastWin32Error(), "授权记录保护校验失败");
var result = new byte[output.Length];
Marshal.Copy(output.Data, result, 0, result.Length);
return result;
}
finally
{
Marshal.FreeHGlobal(input.Data); Marshal.FreeHGlobal(entropy.Data);
if (output.Data != IntPtr.Zero) LocalFree(output.Data);
}
}
[StructLayout(LayoutKind.Sequential)]
private struct Blob { public int Length; public IntPtr Data; }
[DllImport("crypt32.dll", CharSet = CharSet.Unicode, SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
private static extern bool CryptProtectData(ref Blob input, string? description, ref Blob entropy, IntPtr reserved, IntPtr prompt, int flags, out Blob output);
[DllImport("crypt32.dll", SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
private static extern bool CryptUnprotectData(ref Blob input, IntPtr description, ref Blob entropy, IntPtr reserved, IntPtr prompt, int flags, out Blob output);
[DllImport("kernel32.dll")]
private static extern IntPtr LocalFree(IntPtr memory);
}

View File

@ -0,0 +1,11 @@
-----BEGIN PUBLIC KEY-----
MIIBojANBgkqhkiG9w0BAQEFAAOCAY8AMIIBigKCAYEA2eI1DhOeFtJsA35awDMq
SgdU9f6gqTmJPyIrd/tP6QSqhQcr6T9ZWGFMQkBfCAcXSTdjHlR8GKVhZYY9Oath
B+XTqvNYDbs3T6yHLs/mJNpWD1hUmpbD2oACkjSTcWiC3Lu8Szc4pwRf91AMIv0T
usJVZEVMldlhLgKy1qxzu8xfsHy7A5S1LPqNI8TTzTCLKdET9+3iuBpMyrPjXWBF
LExMa7FG2wbTPz5MJ7IbDLvj+qSqpTYU2bCXtI8Kd4rWGn0oDn3R94zFPRXzN+/F
WKVMCiiRp1qm96Y0TOMGhzZT10dMeklEEwPRCx0v8+T4srUEmBloFWvi/gSjCvWY
Om7zhtNoYNOf2L54NvMfaALCWgdN5sNpSrE2y2j26oDVgd1dVL4aer/4WTUk4WAC
Uism8xTnfIIGkaf8dul1eUckw7rpAvHsSyjuSVtcUQmYe3arFEH/jewPWKV0Mgfe
UZjI7iLLrInZI3qCSTZhu1U2OyBk70/NbYCJxUyMLbKtAgMBAAE=
-----END PUBLIC KEY-----

View File

@ -10,6 +10,8 @@
<NativePlatform Condition="'$(NativePlatform)' == ''">Linux</NativePlatform>
</PropertyGroup>
<ItemGroup>
<!-- 客户端仅打包验签公钥,发码私钥始终保留在发行方电脑。 -->
<EmbeddedResource Include="Licensing/issuer-public.pem" />
<PackageReference Include="OpenCvSharp5" Version="5.0.0.20261107" />
<PackageReference Include="OpenCvSharp5.runtime.win" Version="5.0.0.20261107" Condition="'$(NativePlatform)' == 'Windows'" />
<PackageReference Include="OpenCvSharp5.official.runtime.linux-x64" Version="5.0.0.20261107" Condition="'$(NativePlatform)' == 'Linux'" />

View File

@ -0,0 +1,94 @@
using System.Security.Cryptography;
using System.Text.Json;
using SopHelper.Engine.Licensing;
/// <summary>离线授权回归:使用临时签名密钥和内存状态,不触碰发行方私钥或本机正式试用记录。</summary>
internal static class LicenseTests
{
public static void Run()
{
using var issuer = RSA.Create(2048);
var machine = LicenseService.MachineCode("test-board-1");
var store = new MemoryStore();
var now = new DateTimeOffset(2026, 1, 31, 12, 0, 0, TimeSpan.Zero);
LicenseService Create(string? board = null) => new(board ?? machine, store, issuer.ExportSubjectPublicKeyInfoPem(), () => now);
var service = Create();
void Check(bool ok, string message) { if (!ok) throw new Exception(message); Console.WriteLine("PASS: " + message); }
void Reject(Action action, string message)
{
try { action(); } catch (Exception e) when (e is InvalidOperationException or IOException) { Console.WriteLine("PASS: " + message); return; }
throw new Exception(message);
}
string Code(string kind = "Month", string? board = null, string? id = null, int version = 1, RSA? signer = null)
{
var payload = JsonSerializer.SerializeToUtf8Bytes(new LicenseGrant(version, id ?? Guid.NewGuid().ToString("N"), board ?? machine, kind, now));
return "AISOP1." + Convert.ToBase64String(payload) + "." + Convert.ToBase64String((signer ?? issuer).SignData(payload, HashAlgorithmName.SHA256, RSASignaturePadding.Pss));
}
var trial = service.Check();
Check(trial.Allowed && trial.ExpiresUtc == now.AddMonths(1), "首次试用按自然月计算,1月31日到2月28日");
now = now.AddDays(3);
Check(Create().Check().ExpiresUtc == trial.ExpiresUtc, "重启不会重新计算试用起点");
var shortCode = Code();
var renewed = service.Activate(" \n" + shortCode + "\n");
Check(renewed.Allowed && renewed.ExpiresUtc == trial.ExpiresUtc!.Value.AddMonths(1), "提前激活保留剩余期限并增加一个月");
Reject(() => Create().Activate(shortCode), "重启后仍拒绝重复兑换同一码");
Reject(() => service.Activate(Code(board: LicenseService.MachineCode("other"))), "拒绝其他主板的授权码");
using var stranger = RSA.Create(2048);
Reject(() => service.Activate(Code(signer: stranger)), "拒绝非发行方签名");
Reject(() => service.Activate(Code(kind: "Unknown")), "拒绝未知授权类型");
Reject(() => service.Activate(Code(version: 2)), "拒绝未知协议版本");
Reject(() => service.Activate("AISOP1.a.b"), "拒绝格式错误的授权码");
var parts = Code().Split('.');
var bytes = Convert.FromBase64String(parts[1]); bytes[5] ^= 1; parts[1] = Convert.ToBase64String(bytes);
Reject(() => service.Activate(string.Join('.', parts)), "拒绝被篡改的签名内容");
Check(!Create(LicenseService.MachineCode("replacement")).Check().Allowed, "更换主板后原记录不可使用");
now = renewed.ExpiresUtc!.Value;
Check(!service.Check().Allowed, "到期时刻立即失效");
now = now.AddDays(5);
var afterExpiry = service.Activate(Code());
Check(afterExpiry.ExpiresUtc == now.AddMonths(1), "过期续费从激活时刻延长一个月");
var watermark = now;
now = now.AddHours(-1);
Check(!service.Check().Allowed, "运行中时间回拨禁止继续使用");
Reject(() => service.Activate(Code()), "时间回拨时不能兑换短期码");
now = watermark;
Check(service.Check().Allowed, "校准时间后恢复使用");
var future = now.AddDays(1); now = future;
var futureCode = Code(); now = watermark;
Reject(() => service.Activate(futureCode), "拒绝未来签发的授权码");
var permanent = service.Activate(Code("Permanent"));
Check(permanent.Allowed && permanent.Permanent && permanent.ExpiresUtc is null, "长期码切换永久授权");
now = now.AddYears(30);
Check(Create().Check().Allowed && Create().Check().Permanent, "永久授权多年后仍有效");
Reject(() => service.Activate(Code()), "永久授权不再消耗短期码");
store.Data = "broken"u8.ToArray();
Check(!service.Check().Allowed, "记录损坏时禁止重置试用");
store.Fail = true;
Check(!service.Check().Allowed, "读取存储失败时禁止放行");
store.Fail = false; store.Data = null; store.FailWrite = true;
Check(!service.Check().Allowed, "试用记录写盘失败时禁止放行");
Reject(() => service.Activate(Code()), "激活写盘失败不返回成功");
Reject(() => MotherboardIdentity.FromBoard("To be filled by O.E.M.", "vendor", "model"), "拒绝主板占位序列号");
Check(MotherboardIdentity.FromBoard(" Serial-123 ", "Vendor", "Model") == MotherboardIdentity.FromBoard("serial-123", "vendor", "model"), "主板标识忽略大小写与外部空白");
using var publicKey = RSA.Create(); publicKey.ImportFromPem(LicenseService.ReadIssuerPublicKey());
Check(publicKey.KeySize >= 3072, "生产验签公钥已嵌入程序集");
if (OperatingSystem.IsWindows()) Check(MotherboardIdentity.ReadMachineCode().Length == 64, "本机 CIM 主板读取成功");
// 可选验收发行脚本真实输出,仍只写入内存,不激活当前电脑的正式记录。
var integrationPath = Environment.GetEnvironmentVariable("AISOP_TEST_LICENSE_FILE");
if (integrationPath is not null)
{
var integration = new LicenseService(machine, new MemoryStore(), LicenseService.ReadIssuerPublicKey());
Check(integration.Activate(File.ReadAllText(integrationPath)).Allowed, "PowerShell 发行工具与客户端验签兼容");
}
}
private sealed class MemoryStore : ILicenseStore
{
public byte[]? Data;
public bool Fail, FailWrite;
public byte[]? Read() => Fail ? throw new IOException("test read failure") : Data;
public void Write(byte[] value) { if (FailWrite) throw new IOException("test write failure"); Data = value; }
}
}

View File

@ -2,6 +2,9 @@ using System.Net;
using System.Text.Json;
using SopHelper.Engine.Sop;
// 复用已有测试工程验证授权状态机,避免创建额外构建目录或重复测试宿主。
if (args.Contains("--license-only")) { LicenseTests.Run(); return; }
if(args.Length==3&&args[0]=="--djev-live")
{
var installed=Path.GetFullPath(args[1]);

31
tools/New-License.ps1 Normal file
View File

@ -0,0 +1,31 @@
<#
.SYNOPSIS
发行方离线签发绑定主板的短期或永久授权;要求 PowerShell 7,不能把私钥发给客户。
.EXAMPLE
pwsh -File tools/New-License.ps1 -Machine 64位主板机器码 -Kind Month
#>
[CmdletBinding()]
param(
[Parameter(Mandatory)][ValidatePattern('^[A-F0-9]{64}$')][string]$Machine,
[Parameter(Mandatory)][ValidateSet('Month', 'Permanent')][string]$Kind,
[string]$PrivateKeyPath = (Join-Path $env:USERPROFILE '.codex/secrets/aisop-license/issuer-private.pem'),
# 同一订单重发时必须沿用原 Id,避免重复发码导致额外续期。
[ValidatePattern('^[a-f0-9]{32}$')][string]$Id = ([guid]::NewGuid().ToString('N'))
)
$ErrorActionPreference = 'Stop'
if ($PSVersionTable.PSVersion.Major -lt 7) { throw '请使用 PowerShell 7(pwsh)运行发码工具' }
$rsa = [System.Security.Cryptography.RSA]::Create()
try {
$rsa.ImportFromPem([IO.File]::ReadAllText((Resolve-Path -LiteralPath $PrivateKeyPath)))
# 防止误用另一个产品的私钥,签发前先与本仓库公钥比对。
$publicRsa = [System.Security.Cryptography.RSA]::Create()
try {
$publicRsa.ImportFromPem([IO.File]::ReadAllText((Join-Path $PSScriptRoot '../src/SopHelper.CrossPlatform.Engine/Licensing/issuer-public.pem')))
if ($rsa.ExportSubjectPublicKeyInfoPem() -cne $publicRsa.ExportSubjectPublicKeyInfoPem()) { throw '私钥与当前软件的验签公钥不匹配' }
} finally { $publicRsa.Dispose() }
$payload = [Text.Encoding]::UTF8.GetBytes(([ordered]@{
Version = 1; Id = $Id; Machine = $Machine; Kind = $Kind; IssuedUtc = [DateTimeOffset]::UtcNow.ToString('O')
} | ConvertTo-Json -Compress))
$signature = $rsa.SignData($payload, [Security.Cryptography.HashAlgorithmName]::SHA256, [Security.Cryptography.RSASignaturePadding]::Pss)
Write-Output ('AISOP1.' + [Convert]::ToBase64String($payload) + '.' + [Convert]::ToBase64String($signature))
} finally { $rsa.Dispose() }