时间加密 = 用当前时间做密钥 / 校验,防反编译 = 混淆 + 加壳,配套用)
一、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");//固定IV(可改)
ICryptoTransform encryptor = aes.CreateEncryptor();
byte[] bytes = Encoding.UTF8.GetBytes(content);
return Convert.ToBase64String(encryptor.TransformFinalBlock(bytes, 0, bytes.Length));
}
// 解密(5分钟内有效,超时失效)
public static string Decrypt(string cipherText)
{
// 校验5分钟内的时间戳,兼容时间误差
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:时间校验加密(不可逆,适合授权验证)
核心:加密内容绑定有效期,解密时先验时间,再验内容,防篡改
// 授权码生成:比如生成7天有效期的授权码
public static string CreateTimeAuthCode(string userId)
{
DateTime expireTime = DateTime.Now.AddDays(7);
string content = $"{userId}_{expireTime:yyyyMMddHHmmss}";
// 加盐MD5(不可逆,验证时重新计算比对)
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(开源,够用)
- 下载 ConfuserEx,添加你的 C# 程序集(.exe/.dll)
- 混淆规则选:
anti debug+anti tamper+rename+obfuscate - 点击 Protect,生成混淆后的程序(反编译后是乱码,看不了逻辑)
✅ 商用工具:SmartAssembly(更强,防 dnSpy)直接勾选:字符串加密 + 控制流混淆 + 资源加密,一键生成,适合生产环境
步骤 2:加壳保护(进阶,防脱壳,工业级)
混淆后再加壳,双重防护,防止被脱混淆推荐工具:
- Themida:对 C# 程序加壳,防内存 dump、防调试,效果最好
- 免费替代:Enigma Virtual Box(基础加壳,防简单脱壳)
三、关键注意事项(避坑)
- 时间加密别直接用本地时间!用 UTC 时间(DateTime.Now.ToUniversalTime ()),防止用户改系统时间绕过
- 防反编译必做 2 点:混淆(改乱代码)+ 加壳(防脱),缺一不可
- 生产环境:AES 密钥别写死代码里,可放配置文件加密存储,或从硬件信息读取