TCP-Socket在c#中验证SslStream的SSL证书

时间:2015-07-12 14:50:42

标签: c# sockets ssl tcp

我目前正在开发一个包含服务器和通过TCP进行通信的客户端的项目。因此,我想使用SSL保护我的连接。我在http://www.dib0.nl/code/367-using-a-client-certificate-with-an-ssl-stream-in-c找到了一个很好的例子。只有一个问题。它接受所有证书。我知道我必须修改 RemoteCertificateValidationCallback 函数并检查任何 SslPolicyErrors ,但是当我这样做时,我在服务器和客户端都收到了验证错误。它说证书无效。 我使用的是用openssl创建的证书。

public static bool ValidateServerCertificate(object sender, X509Certificate certificate,
        X509Chain chain, SslPolicyErrors sslPolicyErrors)
    {
        if (sslPolicyErrors != SslPolicyErrors.None)
            return false;
        return true;
    }

我希望有人能弄明白我的错误。我认为这与证书有关。 谢谢你的帮助。

2 个答案:

答案 0 :(得分:0)

我在TCP客户端/服务器程序中使用了以下代码。它工作得很好!如果您在Same Machine中创建了TCP客户端/服务器,则必须在MMC存储中同时拥有两个客户端/服务器证书。

private static bool ValidateServerCertificate(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors)
        {
            // For Server Certificate Authentication Errors
            if (sslPolicyErrors == SslPolicyErrors.None)
                return true;

            Console.WriteLine("Certificate error: {0}", sslPolicyErrors);

            // Do not allow this client to communicate with unauthenticated servers.
            return false;

            // Return True if you want to accept all certificate.
            //return true;
        }

希望这也适合你!

答案 1 :(得分:-1)

在ValidateServerCertificate中,尝试通过为sslPolicyErrors添加日志记录行来记录错误。这将告诉您服务器证书的问题(如果有),以便您知道问题是服务器还是客户端。对于某些不同的错误,您可能想要返回true,而对于其他错误,您可能希望返回false。