title: Is it possible to generate on the fly SSL certificates from a root CA in C#?
body: <p>I'm setting up a server under my own root CA to generate SSL certificates on the fly under .NET Core. </p>
  
  <p>I'm able to generate self-signed certificates using the <code>CertificateRequest</code> class. However, these certs obviously aren't trusted by clients with my own root CA. I'm using the <code>CertificateRequest.CreateSelfSigned()</code> method to do this. I cannot use my root CA to sign these new certs, however. Using the <code>CertificateRequest.Create()</code> method will generate my new cert, but it will not provide a private key.</p>
  
  <pre class="lang-cs prettyprint-override"><code>public static X509Certificate2 CreateSelfSignedCertificate(string domain)
  {
      SubjectAlternativeNameBuilder sanBuilder = new SubjectAlternativeNameBuilder();
      sanBuilder.AddDnsName(domain);
  
      X500DistinguishedName distinguishedName = new X500DistinguishedName($"CN=On-The-Fly Generated Cert");
  
      using (RSA rsa = RSA.Create(2048))
      {
          var request = new CertificateRequest(distinguishedName, rsa, HashAlgorithmName.SHA256, RSASignaturePadding.Pkcs1);
  
          request.CertificateExtensions.Add(
              new X509KeyUsageExtension(X509KeyUsageFlags.DataEncipherment | X509KeyUsageFlags.KeyEncipherment | X509KeyUsageFlags.DigitalSignature, false));
  
  
          request.CertificateExtensions.Add(
              new X509EnhancedKeyUsageExtension(
                  new OidCollection { new Oid("1.3.6.1.5.5.7.3.1") }, false));
  
          request.CertificateExtensions.Add(sanBuilder.Build());
  
          var ca = new X509Certificate2(File.ReadAllBytes(@"E:\testing_ca_certificate.pfx"), "password"); //Open my root CA cert, generated in OpenSSL
  
          //Generates a cert, but does not provide a private key.
          var certificate = request.Create(ca, new DateTimeOffset(DateTime.UtcNow.AddDays(-1)), new DateTimeOffset(DateTime.UtcNow.AddDays(365)), new byte[] { 0, 1, 2, 3 }); 
  
          //Generates a usable cert, but is not under my root CA
          //var certificate = request.CreateSelfSigned(new DateTimeOffset(DateTime.UtcNow.AddDays(-1)), new DateTimeOffset(DateTime.UtcNow.AddDays(365)));
  
          return new X509Certificate2(certificate.Export(X509ContentType.Pfx, "password"), "password", X509KeyStorageFlags.DefaultKeySet);
      }
  
  }
  </code></pre>
  
  <p>Using the <code>CertificateRequest.Create()</code> method, I get a valid cert without a private key. I should have this private key so I can encrypt SSL traffic. </p>