-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathLicenseManager.cs
More file actions
286 lines (248 loc) · 9.78 KB
/
Copy pathLicenseManager.cs
File metadata and controls
286 lines (248 loc) · 9.78 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
using System;
using System.Diagnostics;
using System.IO;
using System.Management;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Text.Json;
using System.Linq;
using System.Threading.Tasks;
namespace ShowWrite
{
public class LicenseManager
{
private const string API_URL = "http://sxvillage.dpdns.org/uuid/";
private const string API_KEY = "dbd26f55bc894afab916cb71fc678f54";
private static readonly string ConfigFilePath = Path.Combine(
Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData),
"ShowWrite",
"license.config");
private readonly HttpClient _httpClient;
private static LicenseManager? _instance;
private static readonly object _lock = new();
public string? CurrentUuid { get; private set; }
public string? MotherboardSerial { get; private set; }
public static LicenseManager Instance
{
get
{
if (_instance == null)
{
lock (_lock)
{
_instance ??= new LicenseManager();
}
}
return _instance;
}
}
private LicenseManager()
{
_httpClient = new HttpClient();
_httpClient.DefaultRequestHeaders.Accept.Add(
new MediaTypeWithQualityHeaderValue("application/json"));
}
public async Task<string> GetOrCreateLicenseAsync()
{
Debug.WriteLine("[LicenseManager] 开始获取或创建许可证");
string localUuid = ReadLocalLicense();
if (!string.IsNullOrEmpty(localUuid))
{
Debug.WriteLine($"[LicenseManager] 找到本地缓存的 UUID: {localUuid}");
CurrentUuid = localUuid;
return localUuid;
}
Debug.WriteLine("[LicenseManager] 未找到本地缓存,开始获取主板序列号");
string motherboardSn = GetMotherboardSerialNumber();
MotherboardSerial = motherboardSn;
if (string.IsNullOrEmpty(motherboardSn))
{
Debug.WriteLine("[LicenseManager] 错误:无法获取主板序列号");
throw new Exception("无法获取主板序列号");
}
Debug.WriteLine($"[LicenseManager] 主板序列号: {motherboardSn}");
Debug.WriteLine("[LicenseManager] 开始请求服务器获取 UUID");
string uuid = await RequestLicenseFromServerAsync(motherboardSn);
CurrentUuid = uuid;
Debug.WriteLine($"[LicenseManager] 成功获取 UUID: {uuid}");
SaveLocalLicense(uuid);
Debug.WriteLine("[LicenseManager] UUID 已保存到本地");
return uuid;
}
// OEM 机器未烧录序列号时返回的占位符(统一小写比较)
private static readonly string[] PlaceholderSerials =
{
"to be filled by o.e.m",
"to be filled by o.e.m.",
"to be filled",
"none",
"default string",
"not specified",
"not available",
"unknown",
"system serial number"
};
public string GetMotherboardSerialNumber()
{
string serial = QueryWmiSerial("SELECT SerialNumber FROM Win32_BaseBoard");
if (!IsPlaceholderSerial(serial))
{
return serial;
}
Debug.WriteLine("[LicenseManager] 主板序列号为占位符,回退到 BIOS 序列号");
serial = QueryWmiSerial("SELECT SerialNumber FROM Win32_BIOS");
if (!IsPlaceholderSerial(serial))
{
return serial;
}
Debug.WriteLine("[LicenseManager] BIOS 序列号也为占位符,回退到注册表 MachineGuid");
try
{
using var key = Microsoft.Win32.RegistryKey
.OpenBaseKey(Microsoft.Win32.RegistryHive.LocalMachine, Microsoft.Win32.RegistryView.Registry64)
.OpenSubKey(@"SOFTWARE\Microsoft\Cryptography");
var guid = key?.GetValue("MachineGuid")?.ToString();
if (!string.IsNullOrWhiteSpace(guid))
{
return guid;
}
}
catch
{
}
return string.Empty;
}
private static string QueryWmiSerial(string query)
{
try
{
var searcher = new ManagementObjectSearcher(query);
foreach (ManagementObject obj in searcher.Get())
{
var serial = obj["SerialNumber"]?.ToString();
if (!string.IsNullOrWhiteSpace(serial))
{
return serial.Trim();
}
}
}
catch
{
}
return string.Empty;
}
private static bool IsPlaceholderSerial(string serial)
{
if (string.IsNullOrWhiteSpace(serial))
{
return true;
}
string normalized = serial.Trim().ToLowerInvariant();
if (PlaceholderSerials.Contains(normalized))
{
return true;
}
// 全为重复字符的序列号(如 "xxxxxxxx")也视为占位符
if (normalized.Length > 1 && normalized.All(c => c == normalized[0]))
{
return true;
}
return false;
}
private string ReadLocalLicense()
{
try
{
if (File.Exists(ConfigFilePath))
{
string content = File.ReadAllText(ConfigFilePath);
return Decrypt(content);
}
}
catch
{
}
return string.Empty;
}
private void SaveLocalLicense(string uuid)
{
try
{
string? directory = Path.GetDirectoryName(ConfigFilePath);
if (!string.IsNullOrEmpty(directory) && !Directory.Exists(directory))
{
Directory.CreateDirectory(directory);
}
string encrypted = Encrypt(uuid);
File.WriteAllText(ConfigFilePath, encrypted);
File.SetAttributes(ConfigFilePath, FileAttributes.Hidden);
}
catch
{
}
}
private async Task<string> RequestLicenseFromServerAsync(string motherboardSn)
{
var requestData = new
{
motherboard_sn = motherboardSn
};
string json = JsonSerializer.Serialize(requestData);
Debug.WriteLine($"[LicenseManager] 请求数据: {json}");
var content = new StringContent(json, Encoding.UTF8, "application/json");
_httpClient.DefaultRequestHeaders.Remove("X-API-Key");
_httpClient.DefaultRequestHeaders.Add("X-API-Key", API_KEY);
try
{
Debug.WriteLine($"[LicenseManager] 发送 POST 请求到: {API_URL}");
HttpResponseMessage response = await _httpClient.PostAsync(API_URL, content);
string responseBody = await response.Content.ReadAsStringAsync();
Debug.WriteLine($"[LicenseManager] 响应状态码: {(int)response.StatusCode}");
Debug.WriteLine($"[LicenseManager] 响应内容: {responseBody}");
if (response.IsSuccessStatusCode)
{
using var doc = JsonDocument.Parse(responseBody);
if (doc.RootElement.TryGetProperty("uuid", out var uuidElement))
{
return uuidElement.GetString() ?? string.Empty;
}
Debug.WriteLine("[LicenseManager] 响应中未找到 uuid 字段");
}
else if (response.StatusCode == System.Net.HttpStatusCode.TooManyRequests)
{
throw new Exception("请求过于频繁,请稍后重试 (429)");
}
else if (response.StatusCode == System.Net.HttpStatusCode.Unauthorized)
{
throw new Exception("API Key 验证失败 (401)");
}
else
{
throw new Exception($"服务器错误:{response.StatusCode} - {responseBody}");
}
}
catch (HttpRequestException ex)
{
Debug.WriteLine($"[LicenseManager] 网络请求异常: {ex.Message}");
throw new Exception($"网络请求失败:{ex.Message}");
}
catch (Exception ex)
{
Debug.WriteLine($"[LicenseManager] 未知异常: {ex.Message}");
throw;
}
throw new Exception("获取 UUID 失败");
}
private static string Encrypt(string plainText)
{
var plainBytes = Encoding.UTF8.GetBytes(plainText);
return Convert.ToBase64String(plainBytes);
}
private static string Decrypt(string cipherText)
{
var cipherBytes = Convert.FromBase64String(cipherText);
return Encoding.UTF8.GetString(cipherBytes);
}
}
}