软件试用 防破解 防软件调试(C# )
防破解&防软件调试 实现思路
这里采用C#语言为例:
- 获取网络北京时间:向百度发送 HTTP 请求,从响应头中提取日期时间信息,将其转换为本地时间。
- 记录试用开始时间:首次运行软件时,将获取的百度北京时间作为试用开始时间,并加密存储在本地文件中。
- 检查试用是否过期:每次运行软件时,再次获取百度北京时间,与存储的试用开始时间进行比较,判断试用是否过期。
- 防破解措施:
- 检查文件是否被篡改:通过计算文件的哈希值并与之前存储的哈希值进行比较,判断文件是否被修改。
- 检查系统时间是否被篡改:比较当前获取的百度北京时间和系统时间,如果差异过大,则认为系统时间可能被篡改。
- 软件代码混淆和加壳处理。(防破解 这条很重要,这条做不好,其他都是徒劳)。
- 防软件调试。
using System;
using System.IO;
using System.Net;
using System.Security.Cryptography;
using System.Runtime.Serialization.Formatters.Binary;
class Program
{
private static readonly string trialInfoFilePath = "trialInfo.dat";
private static readonly string hashFilePath = "hash.dat";
static void Main()
{
// 获取百度北京时间
DateTime beijingTime = GetBeijingTimeFromBaidu();
if (IsSystemTimeTampered(beijingTime))
{
Console.WriteLine("检测到系统时间被篡改,软件无法正常使用。");
return;
}
if (IsTrialExpired(beijingTime))
{
Console.WriteLine("试用已到期,请购买正式版本。");
}
else
{
Console.WriteLine("当前北京时间:" + beijingTime);
Console.WriteLine("软件仍在试用期限内。");
}
Console.ReadLine();
}
// 从百度获取北京时间
private static DateTime GetBeijingTimeFromBaidu()
{
try
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://www.baidu.com");
request.Method = "HEAD";
using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
{
string dateHeader = response.GetResponseHeader("Date");
return DateTime.ParseExact(dateHeader, "ddd, dd MMM yyyy HH':'mm':'ss 'GMT'", System.Globalization.CultureInfo.InvariantCulture, System.Globalization.DateTimeStyles.AssumeUniversal | System.Globalization.DateTimeStyles.AdjustToUniversal).ToLocalTime();
}
}
catch (Exception ex)
{
Console.WriteLine($"获取北京时间时出错:{ex.Message},将使用本地时间。");
return DateTime.Now;
}
}
// 检查系统时间是否被篡改
private static bool IsSystemTimeTampered(DateTime beijingTime)
{
TimeSpan difference = beijingTime - DateTime.Now;
return Math.Abs(difference.TotalHours) > 1; // 允许 1 小时的误差
}
// 检查试用是否到期
private static bool IsTrialExpired(DateTime currentTime)
{
DateTime startTrialTime;
if (File.Exists(trialInfoFilePath))
{
if (IsFileTampered(trialInfoFilePath))
{
Console.WriteLine("检测到试用信息文件被篡改,软件无法正常使用。");
return true;
}
using (FileStream fs = new FileStream(trialInfoFilePath, FileMode.Open))
{
BinaryFormatter formatter = new BinaryFormatter();
startTrialTime = (DateTime)formatter.Deserialize(fs);
}
}
else
{
// 首次运行,记录开始试用时间
startTrialTime = currentTime;
using (FileStream fs = new FileStream(trialInfoFilePath, FileMode.Create))
{
BinaryFormatter formatter = new BinaryFormatter();
formatter.Serialize(fs, startTrialTime);
}
SaveFileHash(trialInfoFilePath);
}
// 计算试用天数
int trialDays = (currentTime - startTrialTime).Days;
return trialDays >= 15;
}
// 检查文件是否被篡改
private static bool IsFileTampered(string filePath)
{
if (!File.Exists(hashFilePath))
{
return true;
}
string storedHash = File.ReadAllText(hashFilePath);
string currentHash = CalculateFileHash(filePath);
return storedHash != currentHash;
}