I have been generating certificates for my TCP client/server using mbedtls' gen_key/cert_write tools, and openssl to generate the .pfx file for the server. This works fine, but was only for test purposes. Now, I woud like to generate these certificates programmatically. In the below code, I create an RSA keypair and then create the client(root ca) certificate and the server .pfx file. The handshake never ends up going through, however, despite the client and server both loading the root cert and the .pfx respectively without any apparent errors.
private void GenerateCertificate()
{
if (!Directory.Exists("cert"))
{
RSA rsa = RSA.Create();
CertificateRequest rootRequest = new CertificateRequest("CN=localhost", rsa, HashAlgorithmName.SHA256,
RSASignaturePadding.Pkcs1);
rootRequest.CertificateExtensions.Add(new X509BasicConstraintsExtension(true, false, 0, true));
rootRequest.CertificateExtensions.Add(new X509SubjectKeyIdentifierExtension(rootRequest.PublicKey, false));
using (X509Certificate2 rootCert = rootRequest.CreateSelfSigned(DateTimeOffset.UtcNow.AddDays(-45),
DateTimeOffset.UtcNow.AddDays(365)))
{
//File.WriteAllText("cert\\private.key", new string(PemEncoding.Write("RSA PRIVATE KEY", rootcert.GetRSAPrivateKey().ExportRSAPrivateKey())));
//File.WriteAllText("cert\\private.key", new string(PemEncoding.Write("RSA PUBLIC KEY", rootcert.GetRSAPrivateKey().ExportRSAPrivateKey())));
CertificateRequest serverRequest = new CertificateRequest("CN=localhost", rsa, HashAlgorithmName.SHA256,
RSASignaturePadding.Pkcs1);
serverRequest.CertificateExtensions.Add(new X509BasicConstraintsExtension(false, false, 0, false));
serverRequest.CertificateExtensions.Add(new X509KeyUsageExtension(X509KeyUsageFlags.DigitalSignature |
X509KeyUsageFlags.NonRepudiation, false));
serverRequest.CertificateExtensions.Add(new X509EnhancedKeyUsageExtension( new OidCollection { new Oid("1.3.6.1.5.5.7.3.8") },
true));
serverRequest.CertificateExtensions.Add(new X509SubjectKeyIdentifierExtension(serverRequest.PublicKey, false));
using (X509Certificate2 serverCert = serverRequest.Create(rootCert, DateTimeOffset.UtcNow.AddDays(-1),
DateTimeOffset.UtcNow.AddDays(90), new byte[] { 1, 2, 3, 4 }))
{
// For clients
File.WriteAllText("cert\\certificate.crt", new string(PemEncoding.Write("CERTIFICATE",
rootCert.Export(X509ContentType.Cert))));
// For Server
File.WriteAllBytes("cert\\server.pfx", serverCert.Export(X509ContentType.Pfx));
}
}
}
/****/
}