C#SSL安全套接字

我有一个很好的,有效的沟通应用程序,用C#编写。 现在我需要实现与服务器的安全连接。 我已经尝试将Socket和TcpClient对象更改为SslStream,但是我遇到了一些错误。

首先,我使用makecert生成了一个.cer证书。 OpenSSL证书对我没用,因为它们不包含私钥。 接下来,我在服务器上创建了一个证书对象,并将其绑定到SslStream:

X509Certificate serverCertificate = X509Certificate.CreateFromCertFile("ca.cer"); TcpClient clientSocket = this.tcpListener.AcceptTcpClient(); SslStream ssls = new SslStream(clientSocket.GetStream(), false); ssls.AuthenticateAsServer(serverCertificate, false, SslProtocols.Tls, true); 

在客户端我这样做:

 TcpClient client = new TcpClient(settings.IP, settings.Port); sslStream = new SslStream(client.GetStream(), false, new RemoteCertificateValidationCallback(ValidateServerCertificate), null); sslStream.AuthenticateAsClient(settings.IP); public 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; } 

但AuthenticateAsClient函数会抛出exception。 我尝试了其他几个方法参数,但这些都不适用于我。

任何人都可以帮助我,或者一步一步地解释如何将简单套接字改为安全套接字? 需要明确的是,SSL不是必需的 – 如果有更简单的方法可以使连接安全,我可以使用它。


编辑:exception中的消息如下:

 The remote certificate is invalid according to the validation procedure. 

有什么例外?

我猜你得到了例外,因为你的客户端证书被拒绝为有效的服务器(除非你做了必要的事情来设置信任)。

当您使用自签名证书(由makecert创建的证书)时,您还必须在创建SslStream对象时提供客户端证书validation回调。 使用此构造函数重载http://msdn.microsoft.com/en-us/library/ms145056.aspx

.CER文件通常包含没有私钥的证书。 将其加载到服务器中将无法正常工作。 您还需要一个私钥。 最简单的方法是生成证书和密钥,并将它们一起保存为PFX格式。 然后从服务器上的PFX加载证书和密钥。

现在只使用您的代码validation服务器。 这是你想要做的(即你不想在服务器上validation客户端)?