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

社会主义新天地 提交于 2019-11-30 03:34:57

问题


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 the problem occurs at this line:

sslStream.AuthenticateAsServer(certificate);

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?


回答1:


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

And to add to the trust list your created certificate.



来源:https://stackoverflow.com/questions/23044914/c-sharp-ssl-server-mode-must-use-a-certificate-with-the-corresponding-private-ke

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!