为什么'remoteCertificate'参数在LocalCertificateSelectionCallback方法中为空?

时间:2011-09-22 07:17:15

标签: .net ssl

我想建立一个SSL连接,但实际上并不了解有关SSL握手规则和生命周期的所有信息。我写了一个代码

void main()
{
TcpClient client = new TcpClient("192.168.1.160", 4113);
SslStream sslStream = new SslStream(
                client.GetStream(),
                false,
                new RemoteCertificateValidationCallback(ValidateServerCertificate),
                new LocalCertificateSelectionCallback(localCertSelection)
                );
sslStream.AuthenticateAsClient(serverName);
}

public X509Certificate localCertSelection(object sender, string targetHost, X509CertificateCollection localCertificates, X509Certificate remoteCertificate, string[] acceptableIssuers)
        {// why here 'remoteCertificate' parameter is empty? 'acceptableIssuers' and 'localCertificates' too
            string cert = "MIIEwjCCA6qgAwIBAgIBADANBgkqhkiG9w...";
            X509Certificate clientCert = new X509Certificate(System.Text.Encoding.ASCII.GetBytes(cert));
            return clientCert;
        }

public bool ValidateServerCertificate(
              object sender,
              X509Certificate certificate,
              X509Chain chain,
              SslPolicyErrors sslPolicyErrors)
        {
// 'certificate' has data now. it has come from server
            if (sslPolicyErrors == SslPolicyErrors.None)
                return true;

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

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

当我运行代码时,程序流首先转到'localCertSelection'方法,然后转到'ValidateServerCertificate'方法。
在'localCertSelection'方法中'remoteCertificate'为空,但在'ValidateServerCertificate'方法'certificate'中有数据。它来自服务器,但为什么呢 'sslPolicyErrors'是'RemoteCertificateNameMismatch | RemoteCertificateChainErrors'? 怎么了?我该怎么做?

1 个答案:

答案 0 :(得分:0)

如果您的“服务器名称”错误,可能会发生RemoteCertificateNameMismatch错误。我的意思是

中的服务器名称
sslStream.AuthenticateAsClient(serverName); 

必须是“192.168.1.160”,与

相同
TcpClient client = new TcpClient("192.168.1.160", 4113);

如果您的根证书有问题,则会发生RemoteCertificateChainErrors。创建证书时,必须在CN中放置适当的主机, CN = 192.168.1.160。不要忘记将根证书导入“受信任的根证书颁发机构”。