using Opsoft.Data; using System; using System.Collections.Generic; using System.IO; using System.Management; using System.Security.Cryptography; using System.Text; using System.Xml; namespace Opsoft.NetCore.O3App.WebApi { /// /// /// internal static class SecurityManage { private static string _lkey = "$ta|RT~#"; private static string strKeyList = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"; // 取得设备硬盘的卷标号 private static string GetDiskVolumeSerialNumber() { ManagementClass mc = new ManagementClass("Win32_NetworkAdapterConfiguration"); ManagementObject disk = new ManagementObject("win32_logicaldisk.deviceid=\"d:\""); disk.Get(); return disk.GetPropertyValue("VolumeSerialNumber").ToString(); } //获得CPU的序列号 private static string getCpu(bool isServer) { string strCpu = string.Empty; string strPC = string.Empty; try { if (isServer) { ManagementClass myCpu = new ManagementClass("win32_Processor"); ManagementObjectCollection myCpuConnection = myCpu.GetInstances(); foreach (ManagementObject myObject in myCpuConnection) { strPC = myObject.ToString(); strCpu = myObject.Properties["Processorid"].Value.ToString(); break; } } else { strCpu = getPCSystem(); } } catch { strCpu = strPC + GetIP(); } return strCpu; } private static string getPCSystem() { try { return Environment.MachineName + GetIP() + GetMacAddress(); } catch { return "unknow"; } } public static string GetDiskID() { try { //获取硬盘ID String HDid = ""; ManagementClass mc = new ManagementClass("Win32_DiskDrive"); ManagementObjectCollection moc = mc.GetInstances(); foreach (ManagementObject mo in moc) { HDid = (string)mo.Properties["Model"].Value; } moc = null; mc = null; return HDid; } catch { return "unknow"; } finally { } } public static string GetIP() { try { //获取IP地址 string st = ""; ManagementClass mc = new ManagementClass("Win32_NetworkAdapterConfiguration"); ManagementObjectCollection moc = mc.GetInstances(); foreach (ManagementObject mo in moc) { if ((bool)mo["IPEnabled"]) { Array ar; ar = (Array)mo.Properties["IpAddress"].Value; st = ar.GetValue(0).ToString(); break; } } moc = null; mc = null; return st; } catch { return "unknow"; } finally { } } public static string GetMacAddress() { try { //获取网卡硬件地址 string mac = ""; ManagementClass mc = new ManagementClass("Win32_NetworkAdapterConfiguration"); ManagementObjectCollection moc = mc.GetInstances(); foreach (ManagementObject mo in moc) { if ((bool)mo["IPEnabled"]) { mac = mo["MacAddress"].ToString(); break; } } moc = null; mc = null; return mac; } catch { return "unknow"; } finally { } } /// /// 得到客户序列号 /// /// public static string GetCustomerKey() { bool isServer = GetServerMode() == 1;//获取服务器模式 string TempKey = getCpu(isServer);//获得Cpu序列号 string LastKey = ""; int[] strid = new int[TempKey.Length * 2];// for (int i = 0; i < TempKey.Length; i++)//把字符赋给数组 { strid[i] = (((int)TempKey[i]) + i) % strKeyList.Length; } for (int i = TempKey.Length - 1; i >= 0; i--)//把字符赋给数组 { strid[TempKey.Length + i - 1] = (((int)TempKey[i]) + i) % strKeyList.Length; } for (int i = 0; i < strid.Length; i++)//从数组随机抽取24个字符组成新的字符生成机器码 { LastKey += strKeyList[strid[i]].ToString(); } return LastKey.Substring(0, 6) + "-" + LastKey.Substring(6, 6) + "-" + LastKey.Substring(12, 6) + "-" + LastKey.Substring(18, 6); } /// /// 得到客户序列号 /// /// public static string GetLocalCustomerKey(string ProID) { string wLicenseInfo = ""; ManagerLicenseInfo myInfo = new ManagerLicenseInfo(); wLicenseInfo = myInfo.GetMacID(); wLicenseInfo = DecryptDES(wLicenseInfo, _lkey); return wLicenseInfo; } // 默认密钥向量 private static byte[] Keys = { 0x12, 0x34, 0x56, 0x78, 0x90, 0xAB, 0xCD, 0xEF }; /// /// DES加密字符串 /// /// 待加密的字符串 /// 加密密钥,8位 /// 成功返回加密后的字符串,失敗返回源串 public static string EncryptDES(string encryptString, string encryptKey) { try { byte[] rgbKey = Encoding.UTF8.GetBytes(encryptKey.Substring(0, 8)); byte[] rgbIV = Keys; byte[] inputByteArray = Encoding.UTF8.GetBytes(encryptString); DESCryptoServiceProvider dCSP = new DESCryptoServiceProvider(); MemoryStream mStream = new MemoryStream(); CryptoStream cStream = new CryptoStream(mStream, dCSP.CreateEncryptor(rgbKey, rgbIV), CryptoStreamMode.Write); cStream.Write(inputByteArray, 0, inputByteArray.Length); cStream.FlushFinalBlock(); return Convert.ToBase64String(mStream.ToArray()); } catch { return encryptString; } } /// /// DES解密字符串 /// /// 待解密的字符串 /// 解密密鑰,8位 /// 成功返回解密后的字符串,失敗返回源串 public static string DecryptDES(string decryptString, string decryptKey) { try { byte[] rgbKey = Encoding.UTF8.GetBytes(decryptKey); byte[] rgbIV = Keys; byte[] inputByteArray = Convert.FromBase64String(decryptString); DESCryptoServiceProvider DCSP = new DESCryptoServiceProvider(); MemoryStream mStream = new MemoryStream(); CryptoStream cStream = new CryptoStream(mStream, DCSP.CreateDecryptor(rgbKey, rgbIV), CryptoStreamMode.Write); cStream.Write(inputByteArray, 0, inputByteArray.Length); cStream.FlushFinalBlock(); return Encoding.UTF8.GetString(mStream.ToArray()); } catch { return decryptString; } } /// /// /// /// /// public static LicenseInfo GetLicenseInfo(string strLicense) { string strMAC = GetCustomerKey().Replace("-", ""); return GetLicenseInfo(strLicense, strMAC, ""); } /// /// /// /// /// public static LicenseInfo GetLicenseInfo(string strLicense, string strMAC) { return GetLicenseInfo(strLicense, strMAC, ""); } /// /// /// /// /// /// public static LicenseInfo GetLicenseInfo(string strLicense, string strMAC, string wCustomerName) { if (string.IsNullOrEmpty(strMAC)) { strMAC = GetCustomerKey().Replace("-", ""); } string LastString = ""; LicenseInfo myInfo = new LicenseInfo(); StringBuilder mySB = new StringBuilder(); strLicense = SecurityManage.DecryptDES(strLicense, _lkey); mySB.Append(strLicense); try { myInfo.CustomerName = string.IsNullOrEmpty(wCustomerName) ? "" : SecurityManage.DecryptDES(wCustomerName, _lkey); int iLen = strLicense.Length - 1; LastString = ""; for (int i = 4; i >= 0; i--) { int ii = ((int)strMAC[i]) % iLen; LastString = mySB[ii].ToString() + LastString; mySB.Remove(ii, 1); iLen--; } try { if (string.IsNullOrEmpty(LastString)) myInfo.MaxUsers = 0; else myInfo.MaxUsers = Convert.ToInt16(LastString); } catch (System.Exception) { myInfo.MaxUsers = 0; } LastString = ""; for (int i = 7; i >= 0; i--) { int ii = ((int)strMAC[i]) % iLen; LastString = GetKeyChar(mySB[ii].ToString()) + LastString; mySB.Remove(ii, 1); iLen--; } myInfo.LicenseDays = new DateTime(int.Parse(LastString.Substring(0, 4)), int.Parse(LastString.Substring(4, 2)), int.Parse(LastString.Substring(6, 2))); LastString = ""; for (int i = 3; i >= 0; i--) { int ii = ((int)strMAC[i]) % iLen; LastString = GetKeyChar(mySB[ii].ToString()) + LastString; mySB.Remove(ii, 1); iLen--; } //myInfo.ProductVer = "V" + int.Parse(LastString.Substring(0, 2)).ToString() + "." + int.Parse(LastString.Substring(2, 2)).ToString(); // LastString = ""; for (int i = 7; i >= 0; i--) { int ii = ((int)strMAC[i]) % iLen; LastString = GetKeyChar(mySB[ii].ToString()) + LastString; mySB.Remove(ii, 1); iLen--; } myInfo.SerialDate = new DateTime(int.Parse(LastString.Substring(0, 4)), int.Parse(LastString.Substring(4, 2)), int.Parse(LastString.Substring(6, 2))); LastString = ""; for (int i = strMAC.Length - 1; i >= 0; i--) { int ii = ((int)strMAC[i]) % iLen; LastString = mySB[ii].ToString() + LastString; mySB.Remove(ii, 1); iLen--; } if (LastString == strMAC) { myInfo.SerialNumber = LastString = LastString.Substring(0, 6) + "-" + LastString.Substring(6, 6) + "-" + LastString.Substring(12, 6) + "-" + LastString.Substring(18, 6); } else { myInfo.SerialNumber = ""; } for (int i = 2; i >= 0; i--) { int ii = ((int)strMAC[i]) % iLen; LastString = mySB[ii].ToString() + LastString; mySB.Remove(ii, 1); iLen--; } myInfo.SoftMode = LastString; //myInfo.ProductID = LastString; //myInfo.ProductName = GetProductID(LastString); } catch (System.Exception) { myInfo.SerialNumber = ""; } return myInfo; } private static string GetKeyChar(string key) { int iKey = (int)key[0]; string _Seed = "0"; if (iKey >= (int)'A' && iKey <= (int)'B') { return "0"; } if (iKey >= (int)'C' && iKey <= (int)'D') { return "1"; } if (iKey >= (int)'E' && iKey <= (int)'F') { return "2"; } if (iKey >= (int)'G' && iKey <= (int)'I') { return "3"; } if (iKey >= (int)'J' && iKey <= (int)'L') { return "4"; } if (iKey >= (int)'M' && iKey <= (int)'O') { return "5"; } if (iKey >= (int)'P' && iKey <= (int)'R') { return "6"; } if (iKey >= (int)'S' && iKey <= (int)'U') { return "7"; } if (iKey >= (int)'V' && iKey <= (int)'X') { return "8"; } if (iKey >= (int)'Y' && iKey <= (int)'Z') { return "9"; } return _Seed; } /// /// /// /// /// public static List GetLocalSystemLicenseInfo(string wMacID) { // 改写成文件形式,不再写入注册表 if (string.IsNullOrEmpty(wMacID)) wMacID = SecurityManage.GetCustomerKey(); string mMacID = wMacID.Replace("-", ""); List myList = new List(); ManagerLicenseInfo myInfo = new ManagerLicenseInfo(); List infoList = myInfo.GetLocalSystemLicenseInfo(); foreach (tagLicenseString strInfo in infoList) { string wLicenseInfo = DecryptDES(strInfo.LiInfo, _lkey); string wCU = strInfo.CuInfo; LicenseInfo subInfo = GetLicenseInfo(wLicenseInfo, mMacID, wCU); if (subInfo.SerialNumber == wMacID) { myList.Add(subInfo); } } return myList; } /// /// /// /// /// /// 没有加密的客户识别码 /// 没有加密的客户识别码 public static void WriteLicenseInfo(string wLicenseInfo, string wMacID, string wCustomerName, string wMode) { wMacID = SecurityManage.EncryptDES(wMacID, _lkey); ManagerLicenseInfo myInfo = new ManagerLicenseInfo(); myInfo.WriteLicenseInfo(wLicenseInfo, wMacID, wCustomerName, wMode); } /// /// 查询服务器注册模式 /// /// public static int GetServerMode() { ManagerLicenseInfo myInfo = new ManagerLicenseInfo(); return myInfo.GetServerMode(); } /// /// 更新服务器注册模式 /// 服务器注册模式 public static string WriteServerMode(string wMode) { ManagerLicenseInfo myInfo = new ManagerLicenseInfo(); myInfo.WriteModeInfo(wMode); string key = GetCustomerKey(); return key; } } /// /// /// internal static class LicenseFunction { /// /// 得到版本号 /// /// 主版本号 /// 次版本号 /// public static string GetVer(int Ver1, int Ver2) { string strVer1 = Ver1.ToString().PadLeft(2, '0'); string strVer2 = Ver2.ToString().PadLeft(2, '0'); string rtnCode = ""; rtnCode += GetKeyChar(strVer1.Substring(0, 1)); rtnCode += GetKeyChar(strVer1.Substring(1, 1)); rtnCode += GetKeyChar(strVer2.Substring(0, 1)); rtnCode += GetKeyChar(strVer2.Substring(1, 1)); return rtnCode; } /// /// 得到使用期限 /// /// /// /// public static string GetDays(string wKey, DateTime wPDate) { DateTime wToday = DateTime.Today; switch (wKey) { case "A": // 1 年 wPDate = wToday.AddYears(1); break; case "B": // 2 年 wPDate = wToday.AddYears(2); break; case "C": // 3 年 wPDate = wToday.AddYears(3); break; case "E": break; case "F": //无期限 + 100年 wPDate = new DateTime(2099, 12, 31); break; } return wPDate.Year.ToString().PadLeft(4, '0') + wPDate.Month.ToString().PadLeft(2, '0') + wPDate.Day.ToString().PadLeft(2, '0'); } private static string GetKeyChar(string key) { int _Seed = 65; switch (key) { case "0": _Seed = GetSeed((int)'A', (int)'B'); break; case "1": _Seed = GetSeed((int)'C', (int)'D'); break; case "2": _Seed = GetSeed((int)'E', (int)'F'); break; case "3": _Seed = GetSeed((int)'G', (int)'I'); break; case "4": _Seed = GetSeed((int)'J', (int)'L'); break; case "5": _Seed = GetSeed((int)'M', (int)'O'); break; case "6": _Seed = GetSeed((int)'P', (int)'R'); break; case "7": _Seed = GetSeed((int)'S', (int)'U'); break; case "8": _Seed = GetSeed((int)'V', (int)'X'); break; case "9": _Seed = GetSeed((int)'Y', (int)'Z'); break; } return ((char)_Seed).ToString(); } private static int GetSeed(int fromN, int toN) { DateTime dt = new DateTime(); dt = DateTime.Now; Random rnd = new Random(dt.Millisecond); return rnd.Next(fromN, toN); } /// /// 产生注册码 /// /// 使用限限 /// 机器码 /// public static string GetProductKey(string ProID, string Days, string MacKey, int MaxUsers) { string Ver = GetVer(7, 0); //string Ver = LicenseFunction.GetVer(7,0); string strMAC = MacKey.Replace("-", ""); //分开机器码 string ProductKey = Guid.NewGuid().ToString().ToUpper(); StringBuilder mySB = new StringBuilder(); mySB.Append(ProductKey); int iLen = ProductKey.Length; //总长度 for (int i = 0; i < ProID.Length; i++) { int ii = ((int)strMAC[i]) % iLen; mySB.Insert(ii, ProID[i]); iLen++; } for (int i = 0; i < strMAC.Length; i++) { int ii = ((int)strMAC[i]) % iLen; mySB.Insert(ii, strMAC[i]); iLen++; } string wToDay = DateTime.Now.Year.ToString().PadLeft(4, '0') + DateTime.Now.Month.ToString().PadLeft(2, '0') + DateTime.Now.Day.ToString().PadLeft(2, '0'); for (int i = 0; i < wToDay.Length; i++) { int ii = ((int)strMAC[i]) % iLen; mySB.Insert(ii, GetKeyChar(wToDay[i].ToString())); iLen++; } for (int i = 0; i < Ver.Length; i++) { int ii = ((int)strMAC[i]) % iLen; mySB.Insert(ii, Ver[i]); iLen++; } for (int i = 0; i < Days.Length; i++) { int ii = ((int)strMAC[i]) % iLen; mySB.Insert(ii, GetKeyChar(Days[i].ToString())); iLen++; } string strMaxUsers = MaxUsers.ToString().PadLeft(5, '0').Left(5); for (int i = 0; i < strMaxUsers.Length; i++) { int ii = ((int)strMAC[i]) % iLen; mySB.Insert(ii, strMaxUsers[i]); iLen++; } return mySB.ToString(); } } /// /// /// internal class ManagerLicenseInfo : XmlDocument { /// /// XML 文件路径 /// private string tXMLPath { get { return Path.Combine(DBConnectionInfo.DBFilename); } } /// /// /// public ManagerLicenseInfo() { Init(this.tXMLPath); } private void Init(string FileNameAll) { if (!File.Exists(FileNameAll)) { //如果文件不存,先创建文件 XmlDocument myFile = new XmlDocument(); myFile.LoadXml( " \r\n" + " " + "\r\n" + "" + "\r\n" + "" + "\r\n" + "" + "\r\n" + "" + "\r\n" + "" + "\r\n" + "" + "\r\n" + "" + "\r\n" + "" + "\r\n" + "" + "\r\n" + ""); myFile.Save(FileNameAll); } this.Load(FileNameAll); } /// /// 写入LicenseInfo /// /// /// /// public void WriteLicenseInfo(string wLicenseInfo, string wMacID, string wCustomerName, string wMode) { WriteMode(wMode); WriteMacID(wMacID); WriteLicense(wLicenseInfo, wCustomerName); this.Save(tXMLPath); } /// /// 写入Mode /// public void WriteModeInfo(string wMode) { WriteMode(wMode); this.Save(tXMLPath); } /// /// /// /// public List GetLocalSystemLicenseInfo() { List myList = new List(); XmlNode rootNode = this.FindNode("DBManage/LicenseList"); if (rootNode != null) { if (rootNode.HasChildNodes) { for (int i = 0; i < rootNode.ChildNodes.Count; i++) { XmlAttribute subA = rootNode.ChildNodes[i].Attributes["CustomerName"]; string wCU = ""; if (subA != null) { wCU = subA.InnerXml; } tagLicenseString mSub = new tagLicenseString() { LiInfo = rootNode.ChildNodes[i].InnerXml, CuInfo = wCU }; myList.Add(mSub); } } } return myList; } private void WriteMode(string mode) { XmlNode xmlMode = this.FindNode("DBManage/ServerMode"); if (xmlMode == null) { XmlNode Root = FindNode("DBManage"); this.CreateNode(Root, "ServerMode", mode); } else { xmlMode.InnerXml = mode; } } private void WriteMacID(string wMacID) { XmlNode xmlMacID = this.FindNode("DBManage/MacCodeInfo"); if (xmlMacID == null) { XmlNode Root = FindNode("DBManage"); this.CreateNode(Root, "MacCodeInfo", wMacID); } else { xmlMacID.InnerXml = wMacID; } } private void WriteLicense(string wLicenseInfo, string wCustomerName) { string ProID = "WE"; XmlNode xmlLicenseList = this.FindNode("DBManage/LicenseList"); if (xmlLicenseList == null) { XmlNode Root = FindNode("DBManage"); xmlLicenseList = this.CreateNode(Root, "LicenseList", ""); } XmlNode xmlProID = this.FindNode("DBManage/LicenseList/" + ProID); if (xmlProID == null) { XmlNode Root = FindNode("DBManage/LicenseList"); XmlNode subNote = this.CreateNode(Root, ProID, wLicenseInfo); XmlAttribute subAttribute = this.CreateAttribute("CustomerName"); subAttribute.InnerXml = wCustomerName; subNote.Attributes.Append(subAttribute); } else { xmlProID.InnerXml = wLicenseInfo; XmlAttribute subAttribute = xmlProID.Attributes["CustomerName"]; if (subAttribute == null) { subAttribute = this.CreateAttribute("CustomerName"); subAttribute.InnerXml = wCustomerName; xmlProID.Attributes.Append(subAttribute); } else { subAttribute.InnerXml = wCustomerName; } } } /// /// 得到授权模式 /// /// public int GetServerMode() { XmlNode xmlMode = this.FindNode("DBManage/ServerMode"); if (xmlMode == null) { return 1; } else { if (xmlMode.InnerXml.ToStringEx().Equals("2")) { return 2; } else { return 1; } } } /// /// 得到机器码 /// /// public string GetMacID() { XmlNode xmlMacID = this.FindNode("DBManage/MacCodeInfo"); if (xmlMacID == null) { return ""; } else { return xmlMacID.InnerXml; } } private XmlNode CreateNode(XmlNode ParaNode, string Name, string Value) { XmlNode objNodeChild = this.CreateElement(Name); objNodeChild.InnerXml = Value; ParaNode.AppendChild(objNodeChild); return objNodeChild; } private XmlNode FindNode(string xPath) { XmlNode xmlNode = this.SelectSingleNode(xPath); return xmlNode; } } /// /// 用于保存LicenseInfo /// internal class tagLicenseString { public string LiInfo { get; set; } public string CuInfo { get; set; } } internal class LicenseInfo { public LicenseInfo() { } public string CustomerName { get; set; } public string ErrType { get; set; } public bool HaveLicense { get { if (string.IsNullOrEmpty(SerialNumber)) return false; else return true; } } public DateTime LicenseDays { get; set; } /// /// 软件期限 /// public string LicenseString { get { if (SerialDate.AddYears(100) == LicenseDays) { return "终身使用"; } else { return LicenseDays.ToLongDateString(); } } } public int MaxUsers { get; set; } public DateTime SerialDate { get; set; } public string SerialNumber { get; set; } public string SoftMode { get; set; } } }