LicenseMana.cs 7.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238
  1. using Newtonsoft.Json;
  2. using System;
  3. using System.Collections.Generic;
  4. using System.IO;
  5. using System.Linq;
  6. using System.Management;
  7. using System.Reflection;
  8. using System.Security.Cryptography;
  9. using System.Text;
  10. using System.Threading.Tasks;
  11. namespace MeterVision.Util
  12. {
  13. //注册管理类
  14. public class LicenseMana
  15. {
  16. public static LicenseModel mLicenseModel { get; set; }
  17. private static string _machineCode = "";
  18. //private const string LICENSE_FILE_PATH = "license.dat";
  19. private static string LICENSE_FILE_PATH = AppDomain.CurrentDomain.BaseDirectory + "\\license.dat";
  20. // 保存 licenseKey 到文件,如果文件已存在则覆盖
  21. public static void SaveLicenseKey(string licenseKey)
  22. {
  23. try
  24. {
  25. // 使用 File.WriteAllText 确保每次写入时覆盖现有内容
  26. File.WriteAllText(LICENSE_FILE_PATH, licenseKey);
  27. Console.WriteLine("许可证已成功保存。");
  28. }
  29. catch (Exception ex)
  30. {
  31. Console.WriteLine($"保存许可证时出错: {ex.Message}");
  32. }
  33. }
  34. // 加载注册信息
  35. public static bool IsLicensed()
  36. {
  37. if (File.Exists(LICENSE_FILE_PATH))
  38. {
  39. try
  40. {
  41. // 读取加密的注册信息
  42. string licenseKey = File.ReadAllText(LICENSE_FILE_PATH);
  43. // 解密注册信息
  44. //string jsonData = Decrypt(encryptedData);
  45. //// 反序列化 JSON 数据
  46. //return JsonConvert.DeserializeObject<LicenseData>(jsonData);
  47. //mLicenseModel = ValidateLicense(licenseKey);
  48. return ValidateLicense(licenseKey);
  49. }
  50. catch (Exception ex)
  51. {
  52. Console.WriteLine($"加载注册信息时出错: {ex.Message}");
  53. }
  54. }
  55. return false;
  56. }
  57. public static bool ValidateLicense(string enLicenseKey)
  58. {
  59. mLicenseModel = null;
  60. //先解密
  61. string decLicenseKey = AesEncryptionHelper.DecryptString(enLicenseKey, AesEncryptionHelper.key);
  62. string publicKey = GetPublicKeyFromResource();
  63. if(publicKey == null)
  64. {
  65. //throw new Exception("软件无法使用,请联系开发者!");
  66. return false;
  67. }
  68. // 分割注册码为签名和许可证数据
  69. //string[] parts = licenseKey.Split("::");
  70. string[] parts = decLicenseKey.Split(new string[] { "::" }, StringSplitOptions.None);
  71. if (parts.Length != 2)
  72. {
  73. Console.WriteLine("无效的注册码格式");
  74. return false;
  75. //throw new Exception("无效的注册码!");
  76. }
  77. string signatureBase64 = parts[0];
  78. string jsonData = parts[1];
  79. // 解析许可证数据
  80. var licenseData = JsonConvert.DeserializeObject<dynamic>(jsonData);
  81. string machineCode = licenseData.MachineCode;
  82. string expirationDateStr = licenseData.ExpirationDate;
  83. // 检查硬件码是否匹配
  84. string currentMachineCode = GetMachineCode();
  85. if (machineCode != currentMachineCode)
  86. {
  87. Console.WriteLine("激活码不匹配");
  88. return false;
  89. }
  90. // 检查有效期
  91. DateTime expirationDate = DateTime.Parse(expirationDateStr);
  92. if (DateTime.Now > expirationDate)
  93. {
  94. Console.WriteLine("注册码已过期");
  95. return false;
  96. }
  97. //LicenseData licenseData = new LicenseData();
  98. // 验证签名
  99. using (RSACryptoServiceProvider rsa = new RSACryptoServiceProvider())
  100. {
  101. rsa.FromXmlString(publicKey);
  102. // 将签名从 Base64 字符串转换为字节数组
  103. byte[] signature = Convert.FromBase64String(signatureBase64);
  104. // 对许可证数据进行哈希
  105. byte[] dataToVerify = Encoding.UTF8.GetBytes(jsonData);
  106. // 验证签名
  107. bool isValid = rsa.VerifyData(dataToVerify, CryptoConfig.MapNameToOID("SHA256"), signature);
  108. if (!isValid)
  109. {
  110. Console.WriteLine("无效的签名");
  111. return false;
  112. }
  113. Console.WriteLine("注册码验证成功");
  114. //return true;
  115. mLicenseModel = new LicenseModel
  116. {
  117. MachineCode = machineCode,
  118. ExpirationDate = expirationDate,
  119. IsPermanent = expirationDateStr.Substring(0, 4).Equals("9999"),
  120. LicenseKey = enLicenseKey
  121. };
  122. return true;
  123. }
  124. }
  125. public static string GetPublicKeyFromResource()
  126. {
  127. // 获取当前程序集
  128. Assembly assembly = Assembly.GetExecutingAssembly();
  129. // 列出所有嵌入的资源名称
  130. foreach (string resourceName1 in assembly.GetManifestResourceNames())
  131. {
  132. Console.WriteLine(resourceName1);
  133. }
  134. // 获取资源名称
  135. string resourceName = "MeterVision.public_key.xml"; // 注意命名空间和文件名
  136. // 读取嵌入的资源文件
  137. using (Stream stream = assembly.GetManifestResourceStream(resourceName))
  138. {
  139. if (stream == null)
  140. {
  141. return null;
  142. }
  143. //throw new FileNotFoundException("无法找到私钥资源文件");
  144. using (StreamReader reader = new StreamReader(stream))
  145. {
  146. return reader.ReadToEnd();
  147. }
  148. }
  149. }
  150. public static string GetMachineCode()
  151. {
  152. if (!string.IsNullOrWhiteSpace(_machineCode))
  153. {
  154. return _machineCode;
  155. }
  156. // 获取硬件信息
  157. //string hddSerial = GetHDDSerial();
  158. string cpuId = GetCPUId();
  159. //string macAddress = GetMACAddress();
  160. // 组合硬件信息并生成哈希
  161. using (SHA256 sha256 = SHA256.Create())
  162. {
  163. //byte[] hashBytes = sha256.ComputeHash(Encoding.UTF8.GetBytes(hddSerial + cpuId + macAddress));
  164. byte[] hashBytes = sha256.ComputeHash(Encoding.UTF8.GetBytes(cpuId));
  165. _machineCode = Convert.ToBase64String(hashBytes);
  166. return _machineCode;
  167. }
  168. }
  169. private static string GetCPUId()
  170. {
  171. try
  172. {
  173. // 查询CPU的ProcessorId
  174. using (ManagementObjectSearcher searcher = new ManagementObjectSearcher("SELECT ProcessorId FROM Win32_Processor"))
  175. {
  176. foreach (ManagementObject cpu in searcher.Get())
  177. {
  178. if (cpu["ProcessorId"] != null)
  179. {
  180. return cpu["ProcessorId"].ToString().Trim();
  181. }
  182. }
  183. }
  184. }
  185. catch (Exception ex)
  186. {
  187. Console.WriteLine("获取CPU ID时出错: " + ex.Message);
  188. }
  189. //return "无法获取CPU ID";
  190. return "CPU_ID_ABCDEF";
  191. }
  192. //------------------------------------------------------------------
  193. }
  194. // 许可证数据类
  195. public class LicenseModel
  196. {
  197. public string MachineCode { get; set; }
  198. public DateTime ExpirationDate { get; set; }
  199. public bool IsPermanent { get; set; }
  200. public string LicenseKey { get; set; }
  201. }
  202. }