平时做技术实践时,很多问题不是概念不会,而是细节没串起来。拿“C#中RSA 密钥生成工具”来说,它看着像小点,放到项目里常会牵出环境、配置、兼容性和维护成本。下面按实际采用顺序,把思路、关键写法和容易踩坑的地方讲清楚,便于大家直接对照操作。
以下是可直接运行的 RSA 密钥生成工具实际处理时,(2048位,适配.NET 4.5/C# 5.0),运行后会生成公钥和私钥文件,你只需将生成的公钥替换到代码中即可。
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();
}
}
}
以下是一组测试用的2048位RSA公钥(实际采用请自行生成,不要用测试密钥):
private const string RSA_PUBLIC_KEY = @"<RSAKeyValue><Modulus>qZ6e9t+8Z8X7G5F4D3S2A1Q0P9O8I7U6Y5T4R3E2W1Q9O8I7U6Y5T4R3E2W1Q9O8I7U6Y5T4R3E2W1Q9O8I7U6Y5T4R3E2W1Q9O8I7U6Y5T4R3E2W1Q9O8I7U6Y5T4R3E2W1Q9O8I7U6Y5T4R3E2W1Q9O8I7U6Y5T4R3E2W1Q9O8I7U6Y5T4R3E2W1Q9O8I7U6Y5T4R3E2W1Q9O8I7U6Y5T4R3E2W1Q9O8I7U6Y5T4R3E2W1Q9O8I7U6Y5T4R3E2W1Q==</Modulus><Exponent>AQAB</Exponent></RSAKeyValue>";
测试密钥仅用来调试:
密钥长度要求:
RSACryptoServiceProvider(2048)),1024位密钥已不安全。公钥嵌入方式:
// 拆分公钥(防硬编码提取)
private static string GetPublicKey()
{
string part1 = "<RSAKeyValue><Modulus>qZ6e9t+8Z8X7G5F4D3S2A1Q0P9O8I7U6Y5T4R3E2W1Q9O8I7U6Y5T4R3E2W1Q9O8I7U6Y5T4R3E2W1Q9O8I7U6Y5T4R3E2W1Q9O8I7U6Y5T4R3E2W1Q9O8I7U6Y5T4R3E2W1Q9O8I7U6Y5T4R3E2W1Q9O8I7U6Y5T4R3E2W1Q9O8I7U6Y5T4R3E2W1Q9O8I7U6Y5T4R3E2W1Q9O8I7U6Y5T4R3E2W1Q9O8I7U6Y5T4R3E2W1Q9O8I7U6Y5T4R3E2W1Q9O8I7U6Y5T4R3E2W1Q9O8I7U6Y5T4R3E2W1Q==</Modulus>";
string part2 = "<Exponent>AQAB</Exponent></RSAKeyValue>";
return part1 + part2;
}
私钥保管:
实际处理时,将生成的公钥替换到 LicenseValidator 类的 RSA_PUBLIC_KEY 后,可借助以下步骤验证:
理解这一步时,借助上述工具生成的公钥完全适配.NET Framework 4.5,可直接替换到你的时间管控代码中采用。
实际处理时,总的来说,C# RSA 密钥生成适合结合实际项目边做边理解。先抓住核心思路,再逐步补上细节和边界处理,最后效果会更稳定,也更容易复用。