TFLH/ViewModel/SoftwareValidation.cs
2026-08-06 09:50:46 +08:00

488 lines
16 KiB
C#
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

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
{
/// <summary>
/// 本软件验证
/// </summary>
public class SoftwareValidation
{
/// <summary>
/// 导出机器码
/// </summary>
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地址
/// <summary>
/// 获取网卡MAC地址
/// </summary>
/// <returns></returns>
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 获取主板序列号
/// <summary>
/// 获取主板序列号
/// </summary>
/// <returns></returns>
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序列号
/// <summary>
/// 获取CPU序列号
/// </summary>
/// <returns></returns>
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 获取硬盘序列号
/// <summary>
/// 获取硬盘序列号
/// </summary>
/// <returns></returns>
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加密
/// <summary>
/// MD5加密
/// </summary>
/// <param name="str">原文字符</param>
/// <returns></returns>
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为半角字符)
/// <summary>
/// DES 加密(对称加密)。使用密钥将明文加密成密文
/// </summary>
/// <param name="code">明文</param>
/// <param name="sKey">密钥</param>
/// <returns>密文</returns>
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();
}
/// <summary>
/// DES 解密(对称加密)。使用密钥将密文解码成明文
/// </summary>
/// <param name="code">密文</param>
/// <param name="sKey">密钥</param>
/// <returns>明文</returns>
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;
/// <summary>
/// 写入
/// </summary>
/// <param name="section">需要写入的段落名</param>
/// <param name="key">需要写入的键名</param>
/// <param name="val">写入值</param>
/// <param name="filepath">ini文件的完整路径</param>
/// <returns></returns>
[DllImport("kernel32")]
private static extern bool WritePrivateProfileString(string section, string key, string val, string filePath);
/// <summary>
/// 获取值
/// </summary>
/// <param name="section">段落名</param>
/// <param name="key">键名</param>
/// <param name="defval">读取异常是的缺省值</param>
/// <param name="retval">键名所对应的的值,没有找到返回空值</param>
/// <param name="size">返回值允许的大小</param>
/// <param name="filepath">ini文件的完整路径</param>
/// <returns></returns>
[DllImport("kernel32")]
private static extern int GetPrivateProfileString(string section, string key, string def, byte[] retVal, int size, string filePath);
/// <summary>
/// 写入
/// </summary>
/// <param name="Section">段落名称</param>
/// <param name="Ident">键</param>
/// <param name="Value">值</param>
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(); }
}
/// <summary>
/// 读取
/// </summary>
/// <param name="Section"></param>
/// <param name="Ident"></param>
/// <returns></returns>
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();
}
/// <summary>
/// 清除段落
/// </summary>
/// <param name="Section"></param>
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; }
/// <summary>
/// 软件验证
/// </summary>
/// <returns></returns>
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;
}
}
/// <summary>
/// 软件注册 这里可以另外做一个激活工具单独激活
/// </summary>
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 文件读取
/// <summary>
/// 文件读取
/// </summary>
/// <param name="parameter"></param>
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
}
}