title: Generate a self-signed certificate on the fly
body: <p>I searched around, but I didn't find a clear example.
  <strong>I want to create a self-signed (self-)trusted certificate programmatically (C#)</strong>, following these steps:</p>
  
  <p><strong>STEP 1:</strong></p>
  
  <p>Create a root CA certificate on the fly and add it to the certificate store in the folder "Trusted Root certification Authorities"</p>
  
  <p>I want to do exactly what this command line tool does:</p>
  
  <pre><code>makecert.exe -sk RootCA -sky signature -pe -n CN=MY_CA -r -sr LocalMachine -ss Root MyCA.cer
  </code></pre>
  
  <p><strong>STEP 2:</strong></p>
  
  <p>Create a certificate based on the previously created root CA certificate and put it in the certificate store, in the folder "Personal"</p>
  
  <p>I want to do exactly what this command line tool does:</p>
  
  <pre><code>makecert.exe -sk server -sky exchange -pe -n CN=127.0.0.1 -ir LocalMachine -is Root -ic MyCA.cer -sr LocalMachine -ss My MyCertificate.cer
  </code></pre>
  
  <p>I want to obtain this:</p>
  
  <p><img src="https://i.stack.imgur.com/6bNsj.png" alt="Enter image description here"></p>
  
  <p>I did that (see the following code - STEP 1). How do I make STEP 2? Target machines is Windows XP/7.</p>
  
  <p><strong>I tried both a pure .NET approach and <a href="https://en.wikipedia.org/wiki/Bouncy_Castle_(cryptography)" rel="noreferrer">Bouncy Castle</a> library</strong>.</p>
  
  <pre><code>// STEP 1
  mycerRoot = generateRootCertV1("MY_CA"); // Tried also generateRootCertV2(BouncyCastle)
  addCertToStore(mycerRoot, StoreName.Root, StoreLocation.LocalMachine);
  
  // STEP 2
  mycer = generateCert("127.0.0.1", mycerRoot); // ?????? &lt;-- Something like that How to implement generateCert??
  addCertToStore(mycer, StoreName.My, StoreLocation.LocalMachine);
  
  public static Org.BouncyCastle.X509.X509Certificate generateRootCertV2(string certName)
  {
      X509V1CertificateGenerator certGen = new X509V1CertificateGenerator();
  
      X509Name CN = new X509Name("CN=" + certName);
  
      RsaKeyPairGenerator keypairgen = new RsaKeyPairGenerator();
      keypairgen.Init(new KeyGenerationParameters(new SecureRandom(new CryptoApiRandomGenerator()), 1024));
  
      AsymmetricCipherKeyPair keypair = keypairgen.GenerateKeyPair();
  
      certGen.SetSerialNumber(BigInteger.ProbablePrime(120, new Random()));
      certGen.SetIssuerDN(CN);
      certGen.SetNotAfter(DateTime.MaxValue);
      certGen.SetNotBefore(DateTime.Now.Subtract(new TimeSpan(7, 0, 0, 0)));
      certGen.SetSubjectDN(CN);
      certGen.SetPublicKey(keypair.Public);
      certGen.SetSignatureAlgorithm("MD5WithRSA");
  
      Org.BouncyCastle.X509.X509Certificate newCert = certGen.Generate(keypair.Private);
  
      return newCert;
  }
  
  public static X509Certificate2 GenerateRootCertV1(string HostNameOrIP_or_CertName)
  {
      X509Certificate2 cert = null;
  
      try
      {
          using (CryptContext ctx = new CryptContext())
          {
              ctx.Open();
              cert = ctx.CreateSelfSignedCertificate(
                  new SelfSignedCertProperties
                  {
                      IsPrivateKeyExportable = true,
                      KeyBitLength = 4096,
                      Name = new X500DistinguishedName("cn=" + HostNameOrIP_or_CertName),
                      ValidFrom = DateTime.Today.AddDays(-1),
                      ValidTo = DateTime.Today.AddYears(20),
                  });
          }
      }
      catch (Exception ex)
      {
      }
  
      return cert;
  }
  
  public static bool addCertToStore(X509Certificate2 cert, StoreName st, StoreLocation sl)
  {
      bool bRet = false;
  
      try
      {
          X509Store store = new X509Store(st, sl);
          store.Open(OpenFlags.ReadWrite);
  
          if (cert != null)
          {
              byte[] pfx = cert.Export(X509ContentType.Pfx);
              cert = new X509Certificate2(pfx, (string)null, X509KeyStorageFlags.PersistKeySet | X509KeyStorageFlags.MachineKeySet);
  
              if (!certExists(store, cert.SubjectName.Name))
              {
                  store.Add(cert);
                  bRet = true;
              }
          }
          store.Close();
      }
      catch
      {
  
      }
      return bRet;
  }
  </code></pre>