Why is the remoteCertificate parameter empty in the LocalCertificateSelectionCallback method?

I want to configure an SSL connection, but I donโ€™t really know everything about the rules for establishing an SSL connection and the life cycle. I wrote the code

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; } 

when I run the code, the program flow first goes to the localCertSelection method and then goes to the ValidateServerCertificate method. in 'localCertSelection' the method 'remoteCertificate' is empty, but in 'validateServerCertificate' the method 'certificate' has data. it came from the server, but why is 'sslPolicyErrors' - 'RemoteCertificateNameMismatch' RemoteCertificateChainErrors? what's wrong? what should I do?

+4
source share
1 answer

RemoteCertificateNameMismatch error can occur if your "server name" is incorrect. I mean the server name in

 sslStream.AuthenticateAsClient(serverName); 

should be "192.168.1.160", the same as in

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

RemoteCertificateChainErrors will happen if something is wrong with your root certificate. When you create the certificate, you must put the corresponding node in CN, CN = 192.168.1.160. And don't forget to import your root certificate into "trusted root certificate authorities".

0
source

All Articles