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

I'm going to learn how to handle HTTPS traffic in C # on the server side, and for the first steps I have some problems.

Here is the 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! :) This is test code only where I just want to get some basic steps with SSL processing in C #.

So ... The problem arises on 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 I 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 it looks like everything is fine with the creation of the X509, and another proof is that this line works fine:

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

And the program did not select an exception in the line above.

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

+7
c # ssl x509certificate handle
source share
1 answer

Everything is in order, the answer is to use the class X509Certificate2 instead of X509Certificate .

And add your created certificate to the trust list.

+10
source share

All Articles