C# SSL server mode must use a certificate with the corresponding private key

user2402179 picture user2402179 · Apr 13, 2014 · Viewed 8.4k times · Source

I'm going to learn how to handle HTTPS traffic in C# as server-side and as for the first steps I've got some troubles.

Here is some code ( http://pastebin.com/C4ZYrS8Q ):

class Program
{
    static bool ValidateServerCertificate(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors)
    {
        if (sslPolicyErrors == SslPolicyErrors.None) return true;
        Console.WriteLine("Certificate error: {0}", sslPolicyErrors);
        return false;
    }

    static void Main()
    {
        var tcpListener = new TcpListener(IPAddress.Parse("127.0.0.1"), 8080);
        tcpListener.Start();
        var clientAccept = tcpListener.AcceptTcpClient();
        Thread.Sleep(1000);

        if (clientAccept.Available > 0)
        {
            var sslStream = new SslStream(clientAccept.GetStream(), false, new RemoteCertificateValidationCallback(ValidateServerCertificate), null);
            var certificate = new X509Certificate("path\server.pfx", "password");
            sslStream.AuthenticateAsServer(certificate);
        }

        Console.ReadLine();
    }
}

Don't argue! :) It's the test code only where I just want to achieve some basic steps with the SSL handling in C#.

So... The problem occurs at this line:

sslStream.AuthenticateAsServer(certificate);

enter image description here

From Russian it translates as:

  • SSL server mode must use a certificate with the corresponding private key.

I thought, that I've made my X509 certificate incorrect, but checked again:

makecert.exe -r -pe -n "CN=localhost" -sky exchange -sv server.pvk server.cer
pvk2pfx -pvk server.pvk -spc server.cer -pfx server.pfx -pi <password>

And seems to be that all is fine with the X509 creation, and other proof is this line works fine:

var certificate = new X509Certificate("path\server.pfx", "password");

And program didn't throw an exception on the line above.

So, what's the problem with the SSL hanlding in my code and how can I handle incoming SSL stream as server-side?

Answer

user2402179 picture user2402179 · Apr 14, 2014

All is fine, the answer is to use X509Certificate2 class instead of X509Certificate.

And to add to the trust list your created certificate.