惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

S
Secure Thoughts
S
SegmentFault 最新的问题
云风的 BLOG
云风的 BLOG
T
Tailwind CSS Blog
博客园 - 聂微东
小众软件
小众软件
J
Java Code Geeks
MyScale Blog
MyScale Blog
人人都是产品经理
人人都是产品经理
量子位
GbyAI
GbyAI
让小产品的独立变现更简单 - ezindie.com
让小产品的独立变现更简单 - ezindie.com
M
MIT News - Artificial intelligence
Apple Machine Learning Research
Apple Machine Learning Research
有赞技术团队
有赞技术团队
月光博客
月光博客
B
Blog RSS Feed
D
DataBreaches.Net
酷 壳 – CoolShell
酷 壳 – CoolShell
Cyber Security Advisories - MS-ISAC
Cyber Security Advisories - MS-ISAC
D
Darknet – Hacking Tools, Hacker News & Cyber Security
Cyberwarzone
Cyberwarzone
I
Intezer
The Register - Security
The Register - Security
博客园 - 【当耐特】
博客园 - 司徒正美
L
Lohrmann on Cybersecurity
U
Unit 42
N
News and Events Feed by Topic
S
Security Affairs
V
Visual Studio Blog
Y
Y Combinator Blog
Security Latest
Security Latest
Know Your Adversary
Know Your Adversary
Google DeepMind News
Google DeepMind News
大猫的无限游戏
大猫的无限游戏
S
Schneier on Security
P
Privacy International News Feed
TaoSecurity Blog
TaoSecurity Blog
Spread Privacy
Spread Privacy
G
Google Developers Blog
NISL@THU
NISL@THU
Project Zero
Project Zero
P
Palo Alto Networks Blog
Help Net Security
Help Net Security
宝玉的分享
宝玉的分享
Stack Overflow Blog
Stack Overflow Blog
S
Security @ Cisco Blogs
G
GRAHAM CLULEY
www.infosecurity-magazine.com
www.infosecurity-magazine.com

博客园 - AI一族

GitHub 热门项目 | 2026年04月26日 GitHub 热门项目 | 2026年04月25日 GitHub 热门项目 | 2026年04月19日 GitHub 热门项目 | 2026年04月18日 GitHub 热门项目 | 2026年04月17日 GitHub 热门项目 | 2026年04月16日 GitHub 热门项目 | 2026年04月15日 GitHub 热门 | 2026 年 04 月 14 日 Github日报|2026年04月13日 GitHub 热门项目 | 2026年04月12日 GitHub 热门项目 | 2026年04月10日 ClawHub 24 小时热门 Top 10 | 2026 年 04 月 09 日 GitHub 热门项目 | 2026-04-09 ClawHub 精选 Skill | 2026 年 04 月 08 日 GitHub 热门项目 Top 10 | 2026 年 04 月 08 日 AI 资讯日报 | 2026 年 04 月 08 日 AI 资讯日报 | 2026年04月07日 GitHub 热门项目 Top 10 | 2026年04月07日 GitHub 热门项目 Top 10 | 2026 年 04 月 05 日 ASP.NET Core WebApi 集成 MCP 协议完全指南 Docker容器获取宿主机信息 VUE 条件编译 Centos7 上安装配置 RabbitMQ
Net8 使用BouncyCastle 生成自签名证书
AI一族 · 2024-03-13 · via 博客园 - AI一族
 private AsymmetricCipherKeyPair GenerateKeyPair()
 {
     var generator = new RsaKeyPairGenerator();
     generator.Init(new KeyGenerationParameters(new SecureRandom(new CryptoApiRandomGenerator()), 2048));

     return generator.GenerateKeyPair();
 }

 private X509Certificate GenerateRootCertificate(AsymmetricCipherKeyPair keyPair, string subject, string[] ipAddresses)
 {

     Asn1SignatureFactory signatureFactory = new Asn1SignatureFactory("SHA256WithRSA", keyPair.Private, null);
     var certGenerator = new X509V3CertificateGenerator();
     certGenerator.SetSerialNumber(BigInteger.ValueOf(DateTime.Now.Ticks));
     certGenerator.SetIssuerDN(new X509Name(subject));
     certGenerator.SetSubjectDN(new X509Name(subject));
     certGenerator.SetNotBefore(DateTime.UtcNow);
     certGenerator.SetNotAfter(DateTime.UtcNow.AddYears(1));

     List<Asn1Encodable> asn1Encodables = new List<Asn1Encodable>();
     foreach (var ipAddress in ipAddresses)
     {
         asn1Encodables.Add(new GeneralName(GeneralName.IPAddress, ipAddress));
     }
     certGenerator.AddExtension(X509Extensions.SubjectAlternativeName, false, new DerSequence(new Asn1EncodableVector([.. asn1Encodables])));
     certGenerator.SetPublicKey(keyPair.Public);
     var cert = certGenerator.Generate(signatureFactory);
     return cert;
 }

 private X509Certificate GenerateCertificate(AsymmetricCipherKeyPair keyPair, X509Certificate issuerCert, AsymmetricKeyParameter issuerKey, string subject, string[] ipAddresses)
 {
     Asn1SignatureFactory signatureFactory = new Asn1SignatureFactory("SHA256WithRSA", issuerKey, null);
     var certGenerator = new X509V3CertificateGenerator();
     certGenerator.SetSerialNumber(BigInteger.ValueOf(DateTime.Now.Ticks));
     certGenerator.SetIssuerDN(issuerCert.SubjectDN);
     certGenerator.SetSubjectDN(new X509Name(subject));
     certGenerator.SetNotBefore(DateTime.UtcNow);
     certGenerator.SetNotAfter(DateTime.UtcNow.AddYears(1));
     certGenerator.SetPublicKey(keyPair.Public);
     List<Asn1Encodable> asn1Encodables = new List<Asn1Encodable>();
     foreach (var ipAddress in ipAddresses)
     {
         asn1Encodables.Add(new GeneralName(GeneralName.IPAddress, ipAddress));
     }
     certGenerator.AddExtension(X509Extensions.SubjectAlternativeName, false, new DerSequence(new Asn1EncodableVector([.. asn1Encodables])));
     var cert = certGenerator.Generate(signatureFactory);
     return cert;
 }

 private void SaveToPem(string certFileName, string keyFileName, X509Certificate cert, AsymmetricKeyParameter key)
 {
     // 保存证书
     using (TextWriter certTW = File.CreateText(certFileName))
     {
         PemWriter certPemWriter = new PemWriter(certTW);
         certPemWriter.WriteObject(cert);
         certPemWriter.Writer.Flush();
     }

     // 保存私钥
     using (TextWriter keyTW = File.CreateText(keyFileName))
     {
         PemWriter keyPemWriter = new PemWriter(keyTW);
         keyPemWriter.WriteObject(key);
         keyPemWriter.Writer.Flush();
     }
 }


 public static void ExportCertificateToPfx(X509Certificate2 certificate, string fileName, string password)
 {
     File.WriteAllBytes(fileName, certificate.Export(X509ContentType.Pfx, password));
 }

 public X509Certificate LoadBouncyCastleCertificate(string certFilePath)
 {
     // 读取Bouncy Castle生成的证书文件
     X509CertificateParser parser = new X509CertificateParser();
     X509Certificate bcCert = parser.ReadCertificate(File.ReadAllBytes(certFilePath));
     return bcCert;
 }


  public void GenerateCertificates()
  {
      string[] ipAddresses = { "192.168.0.101", "10.0.0.1" };

      // 生成根证书
      AsymmetricCipherKeyPair rootKeyPair = GenerateKeyPair();
      X509Certificate rootCert = GenerateRootCertificate(rootKeyPair, "CN=Root CA", ipAddresses);

      // 生成客户端证书
      AsymmetricCipherKeyPair clientKeyPair = GenerateKeyPair();
      X509Certificate clientCert = GenerateCertificate(clientKeyPair, rootCert, rootKeyPair.Private, "CN=Client", ipAddresses);

      // 生成服务端证书
      AsymmetricCipherKeyPair serverKeyPair = GenerateKeyPair();
      X509Certificate serverCert = GenerateCertificate(serverKeyPair, rootCert, rootKeyPair.Private, "CN=Server", ipAddresses);


      // 将证书和私钥保存为PEM格式的文件
      // 将证书和私钥分别保存为PEM格式的文件
      SaveToPem("bouncyCastle/ca.crt", "bouncyCastle/ca.key", rootCert, rootKeyPair.Private);
      SaveToPem("bouncyCastle/client.crt", "bouncyCastle/client.key", clientCert, clientKeyPair.Private);
      SaveToPem("bouncyCastle/server.crt", "bouncyCastle/server.key", serverCert, serverKeyPair.Private);


      // Convert to X509Certificate2 format
      X509Certificate2 certRoot = new X509Certificate2(rootCert.GetEncoded());
      ExportCertificateToPfx(certRoot, "bouncyCastle/ca.pfx", "123456");

      X509Certificate2 certServer = new X509Certificate2(serverCert.GetEncoded());
      ExportCertificateToPfx(certServer, "bouncyCastle/server.pfx", "123456");

      X509Certificate2 certClient = new X509Certificate2(clientCert.GetEncoded());
      ExportCertificateToPfx(certClient, "bouncyCastle/client.pfx", "123456");
  }