using Microsoft.Extensions.Logging; using Microsoft.Extensions.Logging.Abstractions; using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Net.NetworkInformation; using System.Security.Cryptography; using System.Text; using System.Threading.Tasks; namespace Edge.Core { public class Licensing { private static Licensing _licensing; private string licPath; private Licensing() { licPath = @"data.bin"; } public static Licensing Instance() { if (_licensing == null) { _licensing = new Licensing(); } return _licensing; } public async Task CheckLicense(string license = "") { var result = false; if (File.Exists(licPath)) { //存在文件 using (var sr = new StreamReader(licPath)) { string encryptedLicense = null; var licenseLimit = 10; while ((encryptedLicense = sr.ReadLine()) != null && licenseLimit-- > 0) { result = IsValidLicense(encryptedLicense.Trim(), GetMacAddress()); if (result == true) { break; } } sr.Close(); } } return result; } public async Task VerifyLicense(string license) { var result = IsValidLicense(license, GetMacAddress()); if (result) { if (Environment.OSVersion.Platform == PlatformID.Unix) { using (TextWriter sr = new StreamWriter(licPath, true)) { license = license.Replace(" ", "").Replace("\n", "").Replace("\r", ""); ; sr.NewLine = "\n"; sr.WriteLine(license); sr.Close(); } } else { using (var sr = new StreamWriter(licPath, true)) { sr.WriteLine(license); sr.Close(); } } } return result; } public string GetMacAddress(ILogger logger) { NetworkInterface.GetAllNetworkInterfaces().ToList().ForEach(i => logger.LogInformation($"Name: {i.Description}, " + $"PhysicalAddress: {i.GetPhysicalAddress()}, NetworkType: {i.NetworkInterfaceType}, Platform {Environment.OSVersion.Platform}")); return GetMacAddress(); } public static string MD5Encrypt(string strText) { var md5 = new MD5CryptoServiceProvider(); byte[] result = md5.ComputeHash(Encoding.UTF8.GetBytes(strText)); return BitConverter.ToString(result).Replace("-", ""); } private bool IsValidLicense(string encryptedLicense, string macString) { var s = macString + "&key=Wayne123"; var encrypted = MD5Encrypt(s); return encryptedLicense == encrypted.Substring(0, 8); } private string GetMacAddress() { string firstMacAddress = string.Empty; if (Environment.OSVersion.Platform == PlatformID.Unix) { firstMacAddress = NetworkInterface .GetAllNetworkInterfaces() //nic.OperationalStatus == OperationalStatus.Up .Where(nic => nic.NetworkInterfaceType != NetworkInterfaceType.Loopback && nic.Description.Contains("eth")) .Select(nic => nic.GetPhysicalAddress().ToString()) .FirstOrDefault(); } else { firstMacAddress = NetworkInterface .GetAllNetworkInterfaces() //nic.OperationalStatus == OperationalStatus.Up .Where(nic => nic.NetworkInterfaceType != NetworkInterfaceType.Loopback && !nic.Description.Contains("Virtual")) .Select(nic => nic.GetPhysicalAddress().ToString()) .FirstOrDefault(); } return firstMacAddress; } } }