简体   繁体   中英

Equalivent for openssl s_client -connect <hostname>:<port> in C#

When I execute a openssl command to connect a particular server [myadda.tie.fire.glass.... dummy server name] , it gives me some output.

openssl s_client -connect myadda.tie.fire.glass:443

It gives me some output which contains information like

  • server certificate
  • issuer information

And another command which required the certificate from above command to provide me details info about the certificate.

openssl x509 -in <Certificate_FileName.crt> -text -nout

It gives me output as information about the certificate

  • issued for server
  • Validity

I want similar kind of output using some C# classes. I am not sure how to solve this query. Can anyone help me out?

Well below code help me to retrieve the required information.

            X509Certificate2 cert = null;
            var client = new TcpClient(host, 443);
            var certValidation = new RemoteCertificateValidationCallback(delegate (object snd, X509Certificate certificate, X509Chain chainLocal, SslPolicyErrors sslPolicyErrors)
            {
                //Accept every certificate, even if it's invalid
                return true;
            });

            // Create an SSL stream and takeover client's stream
            using (var sslStream = new SslStream(client.GetStream(), true, certValidation))
            {
                sslStream.AuthenticateAsClient(host);

                var serverCertificate = sslStream.RemoteCertificate;
                cert = new X509Certificate2(serverCertificate);

                //Convert Raw Data to Base64String
                var certBytes = cert.Export(X509ContentType.Cert);

                var certAsString = Convert.ToBase64String(certBytes, Base64FormattingOptions.None);

            }

Here vertAsString gives me the certificate whereas cert gives me the other required information.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM