C#程序根据时间加密和防止反编译
|
admin
2026年2月26日 15:57
本文热度 76
|
时间加密 = 用当前时间做密钥 / 校验,防反编译 = 混淆 + 加壳,配套用)
一、C# 时间加密 2 种核心实现(直接用)
都是可直接运行的完整代码,适合做注册验证、临时授权
方案 1:时间戳 + AES 加密(最常用,可逆)
核心:用当前时间戳做密钥因子,加密字符串,解密时校验时间有效性
using System;using System.Security.Cryptography;using System.Text;public class TimeAesEncrypt{ private static string GetKeyByTime() { long timestamp = DateTime.Now.ToUniversalTime().Ticks / 10000000 / 60; return MD5.HashData(Encoding.UTF8.GetBytes("固定密钥" + timestamp)).ToHexString().Substring(0, 16); } public static string Encrypt(string content) { using Aes aes = Aes.Create(); aes.Key = Encoding.UTF8.GetBytes(GetKeyByTime()); aes.IV = Encoding.UTF8.GetBytes("1234567812345678"); ICryptoTransform encryptor = aes.CreateEncryptor(); byte[] bytes = Encoding.UTF8.GetBytes(content); return Convert.ToBase64String(encryptor.TransformFinalBlock(bytes, 0, bytes.Length)); } public static string Decrypt(string cipherText) { for (int i = 0; i <= 5; i++) { try { long timestamp = (DateTime.Now.ToUniversalTime().Ticks / 10000000 / 60) - i; string key = MD5.HashData(Encoding.UTF8.GetBytes("固定密钥" + timestamp)).ToHexString().Substring(0, 16); using Aes aes = Aes.Create(); aes.Key = Encoding.UTF8.GetBytes(key); aes.IV = Encoding.UTF8.GetBytes("1234567812345678"); ICryptoTransform decryptor = aes.CreateDecryptor(); byte[] bytes = Convert.FromBase64String(cipherText); return Encoding.UTF8.GetString(decryptor.TransformFinalBlock(bytes, 0, bytes.Length)); } catch { continue; } } throw new Exception("加密超时或内容无效"); }}
方案 2:时间校验加密(不可逆,适合授权验证)
核心:加密内容绑定有效期,解密时先验时间,再验内容,防篡改
public static string CreateTimeAuthCode(string userId){ DateTime expireTime = DateTime.Now.AddDays(7); string content = $"{userId}_{expireTime:yyyyMMddHHmmss}"; return MD5.HashData(Encoding.UTF8.GetBytes(content + "加盐字符串")).ToHexString();}public static bool VerifyTimeAuthCode(string userId, string authCode){ string content = $"{userId}_{DateTime.Now:yyyyMMddHHmmss}"; string checkCode = MD5.HashData(Encoding.UTF8.GetBytes(content + "加盐字符串")).ToHexString(); if (checkCode == authCode) return true; return false;}
二、C# 防反编译(2 个关键步骤,必做)
C# 程序(.exe/.dll)默认极易被反编译(dnSpy 直接看源码),2 步搞定防反编译,工业级实用
步骤 1:代码混淆(基础防反编译,必加)
推荐 2 个工具,不用写代码,直接处理文件
✅ 免费工具:ConfuserEx(开源,够用)
- 1、下载 ConfuserEx,添加你的 C# 程序集(.exe/.dll)
- 2、混淆规则选:
anti debug+anti tamper+rename+obfuscate - 3、点击 Protect,生成混淆后的程序(反编译后是乱码,看不了逻辑)
✅ 商用工具:SmartAssembly(更强,防 dnSpy)
直接勾选:字符串加密 + 控制流混淆 + 资源加密,一键生成,适合生产环境
步骤 2:加壳保护(进阶,防脱壳,工业级)
混淆后再加壳,双重防护,防止被脱混淆推荐工具:
- 1、Themida:对 C# 程序加壳,防内存 dump、防调试,效果最好
- 2、免费替代:Enigma Virtual Box(基础加壳,防简单脱壳)
三、关键注意事项(避坑)
- 1、时间加密别直接用本地时间!用 UTC 时间(DateTime.Now.ToUniversalTime ()),防止用户改系统时间绕过
- 2、防反编译必做 2 点:混淆(改乱代码)+ 加壳(防脱),缺一不可
- 3、生产环境:AES 密钥别写死代码里,可放配置文件加密存储,或从硬件信息读取
阅读原文:原文链接
该文章在 2026/2/27 8:48:37 编辑过