为什么'remoteCertificate'参数在本地证书选择回调方法中为空?



我想建立一个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' ?怎么了?我该怎么做?

如果您的"servername"错误,可能会出现RemoteCertificateNameMismatch错误。我指的是

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

必须为192.168.1.160,与

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

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

最新更新