title: How to use BouncyCastle to generate X509Certificate2 which can be used for WCF authentication?
body: <p>Here's my WCF service code:</p>
  
  <pre><code>        ServiceHost svh = new ServiceHost(typeof(MyClass));
  
          var tcpbinding = new NetTcpBinding(SecurityMode.TransportWithMessageCredential, true);
          //security
  
          tcpbinding.Security.Message.ClientCredentialType = MessageCredentialType.UserName;
          svh.Credentials.UserNameAuthentication.CustomUserNamePasswordValidator = new BWUserNamePasswordValidator();
          svh.Credentials.UserNameAuthentication.UserNamePasswordValidationMode =UserNamePasswordValidationMode.Custom;
          svh.Credentials.ServiceCertificate.Certificate = GenerateCertificate(myCert);
  
          svh.AddServiceEndpoint(typeof(IMyClass), tcpbinding, location);            
  
          svh.Open();
  </code></pre>
  
  <p>And here's the code, which I'm using to generate the certificate:</p>
  
  <pre><code>    static X509Certificate2 GenerateCertificate(string certName)
      {
          var keypairgen = new RsaKeyPairGenerator();
          keypairgen.Init(new KeyGenerationParameters(new SecureRandom(new CryptoApiRandomGenerator()), 1024));
  
          var keypair = keypairgen.GenerateKeyPair();
  
          var gen = new X509V3CertificateGenerator();
  
          var CN = new X509Name("CN=" + certName);
          var SN = BigInteger.ProbablePrime(120, new Random());
  
          gen.SetSerialNumber(SN);
          gen.SetSubjectDN(CN);
          gen.SetIssuerDN(CN);
          gen.SetNotAfter(DateTime.MaxValue);
          gen.SetNotBefore(DateTime.Now.Subtract(new TimeSpan(7, 0, 0, 0)));
          gen.SetSignatureAlgorithm("MD5WithRSA");
          gen.SetPublicKey(keypair.Public);
  
          gen.AddExtension(X509Extensions.SubjectKeyIdentifier, false,
                      new SubjectKeyIdentifierStructure(keypair.Public));        
  
          var newCert = gen.Generate(keypair.Private);
  
          return new X509Certificate2(DotNetUtilities.ToX509Certificate((Org.BouncyCastle.X509.X509Certificate)newCert));
      }
  </code></pre>
  
  <p>When I'm starting the server it crashes with following exception:</p>
  
  <pre><code>ArgumentException: It is likely that certificate 'CN=MyCert' may not 
  have a private key that is capable of key exchange or the process may not have 
  access rights for the private key. Please see inner exception for detail.
  </code></pre>
  
  <p>The inner exception is null.</p>
  
  <p>What did I do wrong?</p>