3

我有一个用 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 函数会引发异常。我尝试了其他几个方法参数,但这些都不适合我。

谁能帮助我,或逐步解释如何将简单的套接字更改为安全的套接字?需要明确的是,SSL 不是必需的——如果有更简单的方法可以使连接安全,我可以使用它。


编辑:异常消息如下:

The remote certificate is invalid according to the validation procedure.
4

2 回答 2

3

有什么例外?

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

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

于 2011-06-23T09:36:07.430 回答
3

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

Now with your code only only authenticate the server. Is this what you want to do (i.e. don't you want to authenticate the client on the server as well)?

于 2011-06-23T12:35:18.767 回答