从未调用过ValidateServerCertificate

时间:2018-02-22 11:24:51

标签: c# authentication callback x509certificate2 sslstream

我尝试使用SslStream类连接到https服务器(服务器使用受信任的根证书),在sslStream.AuthenticateAsClient CertificateSelectionCallback被调用之后,它从未调用过ValidateServerCertificate所以它永远留在sslStream.AuthenticateAsClient

以下是代码:

TcpClient client = new TcpClient();
client.Connect(server, port);
SslStream sslStream = new SslStream(
    client.GetStream(),
    false,
    new RemoteCertificateValidationCallback(ValidateServerCertificate),
    new LocalCertificateSelectionCallback(CertificateSelectionCallback));

try
{ 
    sslStream.AuthenticateAsClient(
        serverName,
        collection,
        SslProtocols.Default,
        false);
catch (Exception ex)
{
    Console.WriteLine("Exception: {0}", ex.ToString());
}
...

以下是回调的两个函数:

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

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

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

static X509Certificate CertificateSelectionCallback(
    object sender,
    string targetHost,
    X509CertificateCollection localCertificates,
    X509Certificate remoteCertificate,
    string[] acceptableIssuers)
{
    return localCertificates[0];
}

有谁知道我为什么会遇到这个问题以及如何解决这个问题?

0 个答案:

没有答案