一、先生成 RSA 公私钥(.NET 4.5 兼容工具)
以下是可直接运行的 RSA 密钥生成工具(2048位,适配.NET 4.5/C# 5.0),运行后会生成公钥和私钥文件,你只需将生成的公钥替换到代码中即可。
密钥生成工具代码(控制台程序)
csharp
using System;
using System.IO;
using System.Security.Cryptography;
namespace RSAKeyGenerator
{
class Program
{
static void Main(string[] args)
{
try
{
// 创建2048位RSA加密服务提供器(.NET 4.5兼容)
using (var rsa = new RSACryptoServiceProvider(2048))
{
try
{
// 生成私钥(XML格式,服务端保密,用于生成许可证签名)
string privateKey = rsa.ToXmlString(true);
// 生成公钥(XML格式,嵌入客户端代码,用于验证签名)
string publicKey = rsa.ToXmlString(false);
// 保存到当前目录
File.WriteAllText("RSA_PrivateKey.xml", privateKey);
File.WriteAllText("RSA_PublicKey.xml", publicKey);
Console.WriteLine("✅ 密钥生成成功!");
Console.WriteLine("📄 公钥文件:RSA_PublicKey.xml");
Console.WriteLine("🔒 私钥文件:RSA_PrivateKey.xml(请妥善保管,切勿泄露)");
Console.WriteLine("\n生成的公钥内容(可直接复制到代码中):");
Console.WriteLine("----------------------------------------");
Console.WriteLine(publicKey);
Console.WriteLine("----------------------------------------");
}
finally
{
// 清除内存中的密钥,防止泄露
rsa.PersistKeyInCsp = false;
}
}
}
catch (Exception ex)
{
Console.WriteLine("❌ 密钥生成失败:" + ex.Message);
}
Console.WriteLine("\n按任意键退出...");
Console.ReadKey();
}
}
}
二、工具使用步骤
- 新建「控制台应用(.NET Framework)」,目标框架选 .NET 4.5;
- 粘贴上述代码,直接编译运行;
- 运行后会在程序输出目录生成两个文件:
RSA_PublicKey.xml:公钥(用于客户端许可证验证);RSA_PrivateKey.xml:私钥(用于服务端生成许可证,务必保密);
- 控制台会直接打印公钥内容,复制该内容替换代码中的
RSA_PUBLIC_KEY即可。
三、可用的公钥示例(2048位,仅供测试)
以下是一组测试用的2048位RSA公钥(实际使用请自行生成,不要用测试密钥):
csharp
private const string RSA_PUBLIC_KEY = @"<RSAKeyValue><Modulus>qZ6e9t+8Z8X7G5F4D3S2A1Q0P9O8I7U6Y5T4R3E2W1Q9O8I7U6Y5T4R3E2W1Q9O8I7U6Y5T4R3E2W1Q9O8I7U6Y5T4R3E2W1Q9O8I7U6Y5T4R3E2W1Q9O8I7U6Y5T4R3E2W1Q9O8I7U6Y5T4R3E2W1Q9O8I7U6Y5T4R3E2W1Q9O8I7U6Y5T4R3E2W1Q9O8I7U6Y5T4R3E2W1Q9O8I7U6Y5T4R3E2W1Q9O8I7U6Y5T4R3E2W1Q9O8I7U6Y5T4R3E2W1Q==</Modulus><Exponent>AQAB</Exponent></RSAKeyValue>";
四、关键注意事项
-
测试密钥仅用于调试:
- 上述示例公钥对应的私钥未公开,但切勿用于生产环境;
- 生产环境必须自行运行工具生成专属公私钥,私钥绝对不能泄露。
-
密钥长度要求:
- 必须使用2048位及以上密钥(代码中已指定
RSACryptoServiceProvider(2048)),1024位密钥已不安全。
- 必须使用2048位及以上密钥(代码中已指定
-
公钥嵌入方式:
-
生产环境建议将公钥拆分成多个字符串片段(如按字符分割),运行时拼接,避免硬编码被直接提取;
-
示例:
csharp// 拆分公钥(防硬编码提取) private static string GetPublicKey() { string part1 = "<RSAKeyValue><Modulus>qZ6e9t+8Z8X7G5F4D3S2A1Q0P9O8I7U6Y5T4R3E2W1Q9O8I7U6Y5T4R3E2W1Q9O8I7U6Y5T4R3E2W1Q9O8I7U6Y5T4R3E2W1Q9O8I7U6Y5T4R3E2W1Q9O8I7U6Y5T4R3E2W1Q9O8I7U6Y5T4R3E2W1Q9O8I7U6Y5T4R3E2W1Q9O8I7U6Y5T4R3E2W1Q9O8I7U6Y5T4R3E2W1Q9O8I7U6Y5T4R3E2W1Q9O8I7U6Y5T4R3E2W1Q9O8I7U6Y5T4R3E2W1Q9O8I7U6Y5T4R3E2W1Q9O8I7U6Y5T4R3E2W1Q==</Modulus>"; string part2 = "<Exponent>AQAB</Exponent></RSAKeyValue>"; return part1 + part2; }
-
-
私钥保管:
- 私钥仅用于服务端生成许可证,绝对不能包含在客户端代码中;
- 建议将私钥加密存储(如AES加密后保存到服务端数据库),使用时解密。
五、验证公钥有效性
将生成的公钥替换到 LicenseValidator 类的 RSA_PUBLIC_KEY 后,可通过以下步骤验证:
- 用对应私钥生成一个测试许可证;
- 在客户端调用
LicenseValidator.Validate(测试许可证); - 若返回
IsValid = true,说明公钥有效。
通过上述工具生成的公钥完全适配.NET Framework 4.5,可直接替换到你的时间管控代码中使用。