using Microsoft.Win32; using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Management; using System.Runtime.InteropServices; using System.Security.Cryptography; using System.Text; using System.Threading.Tasks; using System.Windows; namespace ViewModel { /// /// 本软件验证 /// public class SoftwareValidation { /// /// 导出机器码 /// public void ExportMachineCode(object obj) { //获取MAC string machineCode = GetNetCardMACAddress();//+ GetBIOSSerialNumber()+ GetCPUSerialNumber()+ GetHardDiskSerialNumber(); if (string.IsNullOrEmpty(machineCode)) { MessageBox.Show("机器码获取失败"); return; } SaveFileDialog sf = new SaveFileDialog(); sf.Title = "保存机器码"; sf.DefaultExt = "txt"; sf.Filter = "ini files (*.ini)|*.ini|All files (*.*)|*.*"; sf.FilterIndex = 1; sf.RestoreDirectory = true; if ((bool)sf.ShowDialog()) { using (FileStream fs = new FileStream(sf.FileName, FileMode.Create)) { using (StreamWriter sw = new StreamWriter(fs, Encoding.Default)) { sw.WriteLine(machineCode); } } } } #region 获取网卡MAC地址 /// /// 获取网卡MAC地址 /// /// public string GetNetCardMACAddress() { try { ManagementObjectSearcher searcher = new ManagementObjectSearcher("SELECT * FROM Win32_NetworkAdapter WHERE ((MACAddress Is Not NULL) AND (Manufacturer <> 'Microsoft'))"); string NetCardMACAddress = ""; foreach (ManagementObject mo in searcher.Get()) { NetCardMACAddress = mo["MACAddress"].ToString().Trim(); } return NetCardMACAddress; } catch { return ""; } } #endregion #region 获取主板序列号 /// /// 获取主板序列号 /// /// public string GetBIOSSerialNumber() { try { ManagementObjectSearcher searcher = new ManagementObjectSearcher("Select * From Win32_BIOS"); string sBIOSSerialNumber = ""; foreach (ManagementObject mo in searcher.Get()) { sBIOSSerialNumber = mo["SerialNumber"].ToString().Trim(); } return sBIOSSerialNumber; } catch { return ""; } } #endregion #region 获取CPU序列号 /// /// 获取CPU序列号 /// /// public string GetCPUSerialNumber() { try { ManagementObjectSearcher searcher = new ManagementObjectSearcher("Select * From Win32_Processor"); string sCPUSerialNumber = ""; foreach (ManagementObject mo in searcher.Get()) { sCPUSerialNumber = mo["ProcessorId"].ToString().Trim(); } return sCPUSerialNumber; } catch { return ""; } } #endregion #region 获取硬盘序列号 /// /// 获取硬盘序列号 /// /// public string GetHardDiskSerialNumber() { try { ManagementObjectSearcher searcher = new ManagementObjectSearcher("SELECT * FROM Win32_PhysicalMedia"); string sHardDiskSerialNumber = ""; foreach (ManagementObject mo in searcher.Get()) { sHardDiskSerialNumber = mo["SerialNumber"].ToString().Trim(); break; } return sHardDiskSerialNumber; } catch { return ""; } } #endregion #region MD5加密 /// /// MD5加密 /// /// 原文字符 /// public static string MD5(string str) { byte[] data = Encoding.GetEncoding("GB2312").GetBytes(str); MD5 md5 = new MD5CryptoServiceProvider(); byte[] OutBytes = md5.ComputeHash(data); string OutString = ""; for (int i = 0; i < OutBytes.Length; i++) { OutString += OutBytes[i].ToString("x2"); } // return OutString.ToUpper(); return OutString.ToLower(); } #endregion #region DES 加(解)密。(对称加密,密钥必须为8为半角字符) /// /// DES 加密(对称加密)。使用密钥将明文加密成密文 /// /// 明文 /// 密钥 /// 密文 public static string DESEncrypt(string code, string sKey) { /* 创建一个DES加密服务提供者 */ DESCryptoServiceProvider des = new DESCryptoServiceProvider(); /* 将要加密的内容转换成一个Byte数组 */ byte[] inputByteArray = Encoding.Default.GetBytes(code); /* 设置密钥和初始化向量 */ des.Key = ASCIIEncoding.ASCII.GetBytes(sKey); des.IV = ASCIIEncoding.ASCII.GetBytes(sKey); /* 创建一个内存流对象 */ MemoryStream ms = new MemoryStream(); /* 创建一个加密流对象 */ CryptoStream cs = new CryptoStream(ms, des.CreateEncryptor(), CryptoStreamMode.Write); /* 将要加密的文本写到加密流中 */ cs.Write(inputByteArray, 0, inputByteArray.Length); /* 更新缓冲 */ cs.FlushFinalBlock(); /* 获取加密过的文本 */ StringBuilder ret = new StringBuilder(); foreach (byte b in ms.ToArray()) { ret.AppendFormat("{0:X2}", b); } /* 释放资源 */ cs.Close(); ms.Close(); /* 返回结果 */ return ret.ToString(); } /// /// DES 解密(对称加密)。使用密钥将密文解码成明文 /// /// 密文 /// 密钥 /// 明文 public static string DESDecrypt(string code, string sKey) { /* 创建一个DES加密服务提供者 */ DESCryptoServiceProvider des = new DESCryptoServiceProvider(); /* 将要解密的内容转换成一个Byte数组 */ byte[] inputByteArray = new byte[code.Length / 2]; for (int x = 0; x < code.Length / 2; x++) { int i = (Convert.ToInt32(code.Substring(x * 2, 2), 16)); inputByteArray[x] = (byte)i; } /* 设置密钥和初始化向量 */ des.Key = ASCIIEncoding.ASCII.GetBytes(sKey); des.IV = ASCIIEncoding.ASCII.GetBytes(sKey); /* 创建一个内存流对象 */ MemoryStream ms = new MemoryStream(); /* 创建一个加密流对象 */ CryptoStream cs = new CryptoStream(ms, des.CreateDecryptor(), CryptoStreamMode.Write); /* 将要解密的文本写到加密流中 */ cs.Write(inputByteArray, 0, inputByteArray.Length); /* 更新缓冲 */ cs.FlushFinalBlock(); /* 返回结果 */ return System.Text.Encoding.Default.GetString(ms.ToArray()); } #endregion #region 读取INI文件 public static string FileName; /// /// 写入 /// /// 需要写入的段落名 /// 需要写入的键名 /// 写入值 /// ini文件的完整路径 /// [DllImport("kernel32")] private static extern bool WritePrivateProfileString(string section, string key, string val, string filePath); /// /// 获取值 /// /// 段落名 /// 键名 /// 读取异常是的缺省值 /// 键名所对应的的值,没有找到返回空值 /// 返回值允许的大小 /// ini文件的完整路径 /// [DllImport("kernel32")] private static extern int GetPrivateProfileString(string section, string key, string def, byte[] retVal, int size, string filePath); /// /// 写入 /// /// 段落名称 /// 键 /// 值 public static void WriteString(string Section, string Ident, string Value) { try { if (!WritePrivateProfileString(Section, Ident, Value, FileName)) { throw (new ApplicationException("写Ini文件出错")); } } catch (Exception ex) { ex.ToString(); } } /// /// 读取 /// /// /// /// public static string ReadString(string Section, string Ident) { Byte[] Buffer = new Byte[65535]; int bufLen = GetPrivateProfileString(Section, Ident, "", Buffer, Buffer.GetUpperBound(0), FileName); string s = Encoding.GetEncoding(0).GetString(Buffer); s = s.Substring(0, bufLen); return s.Trim(); } /// /// 清除段落 /// /// public static void EraseSection(string Section) { if (!WritePrivateProfileString(Section, null, null, FileName)) { throw (new ApplicationException("无法清除Ini文件中的Section")); } } #endregion #region 软件验证 解锁 public static string errMessage { get; set; } /// /// 软件验证 /// /// public static bool SoftwareVerification() { errMessage = "软件验证失败"; string path = @"C:\\Users\Public\Documents\FeiYu"; //文件夹路径 string paths = @"C:\\Users\Public\Documents\FeiYu\\Secret.ini"; //文件路径 //创建文件夹 if (!Directory.Exists(path)) { // Directory.CreateDirectory(path); return false; } if (!File.Exists(paths)) { return false; } FileName = paths; try { string time1 = ReadString("SecretStr", "UseTime"); string time2 = ReadString("SecretStr", "diyTime"); DateTime dateTime1 = DateTime.Now; DateTime dateTime2 = DateTime.Now; if (!string.IsNullOrEmpty(time1)) { dateTime1 = Convert.ToDateTime(time1); } else { WriteString("SecretStr", "UseTime", DateTime.Now.ToString("yyyy/MM/dd HH:mm:ss.fff")); } if (!string.IsNullOrEmpty(time2)) { dateTime2 = Convert.ToDateTime(time2); } if (dateTime2 > DateTime.Now) { errMessage = "计算机时间异常,软件无法运行,请修复计算机正确的时间"; return false; } WriteString("SecretStr", "diyTime", DateTime.Now.ToString("yyyy/MM/dd HH:mm:ss.fff")); TimeSpan t = DateTime.Now - dateTime1; int a = t.Days; if (a >= 180) { errMessage = "软件已过期,请联系系统管理员"; return false; } return true; } catch (Exception) { return false; } } /// /// 软件注册 这里可以另外做一个激活工具单独激活 /// public static void SoftwareRegistration() { string path = @"C:\\Users\Public\Documents\FeiYu"; //文件夹路径 string paths = @"C:\\Users\Public\Documents\FeiYu\\Secret.ini"; //文件路径 //创建文件夹 if (!Directory.Exists(path)) { Directory.CreateDirectory(path); } FileName = paths; WriteString("SecretStr", "UseTime", DateTime.Now.ToString("yyyy/MM/dd HH:mm:ss.fff")); WriteString("SecretStr", "diyTime", DateTime.Now.ToString("yyyy/MM/dd HH:mm:ss.fff")); } #endregion #region 文件读取 /// /// 文件读取 /// /// private void Read(object parameter) { string str = ""; //指定路径地址 string textFile = @"C:\Users\show\Desktop\试试.txt"; //如果指定路径的文件存在 就打开并显示 if (File.Exists(textFile)) { using (StreamReader sr = new StreamReader(textFile, Encoding.Default)) { int lineCount = 0; while (sr.Peek() > 0) { lineCount++; string temp = sr.ReadLine(); str = str + temp; } } } else //如果文件不存在 就让用户自己 选中路径 { OpenFileDialog openFile = new OpenFileDialog(); openFile.Filter = "文本文件(*.txt)|*.txt|(*.rtf)|*.rtf"; if (openFile.ShowDialog() == true) { using (StreamReader sr = new StreamReader(openFile.FileName, Encoding.Default)) { int lineCount = 0; while (sr.Peek() > 0) { lineCount++; string temp = sr.ReadLine(); str = str + temp; } } } } MessageBox.Show(str); } #endregion } }