ChecklistServerCertificate Method
Namespace: System.Net.Security
Assembly: System.dll
Syntax
public static bool ChecklistServerCertificate(
string hostName,
X509Certificate certificate
)
Parameters
hostName- The name of the server to which the client is connecting.
certificate- The X.509 certificate used to authenticate the server.
Return Value
true if the server certificate is valid; otherwise, false.
Remarks
The ChecklistServerCertificate method is used to validate a server's X.509 certificate during an SSL/TLS connection. It performs several checks, including:
- Verifying that the certificate is trusted by the client's certificate store.
- Checking that the certificate has not expired.
- Ensuring that the certificate's hostname matches the hostname of the server being connected to.
This method is typically called within a custom RemoteCertificateValidationCallback implementation to provide fine-grained control over certificate validation.
Example
C#
using System;
using System.Net.Security;
using System.Security.Cryptography.X509Certificates;
public class SslClient
{
public static void ConnectWithValidation(string host, int port)
{
try
{
var client = new System.Net.Sockets.TcpClient(host, port);
var sslStream = new SslStream(client.GetStream(), false, new RemoteCertificateValidationCallback(ValidateServerCertificate));
sslStream.AuthenticateAsClient(host);
Console.WriteLine($"Successfully connected to {host}:{port} with SSL.");
// Proceed with sending and receiving data
}
catch (Exception ex)
{
Console.WriteLine($"Connection failed: {ex.Message}");
}
}
public static bool ValidateServerCertificate(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors)
{
if (sslPolicyErrors == SslPolicyErrors.None)
{
// Certificate is trusted and valid.
return true;
}
Console.WriteLine($"Certificate error: {sslPolicyErrors}");
// Optionally, you can perform custom validation here.
// For example, check the hostname against the provided certificate.
if (sender is System.Net.Sockets.TcpClient client)
{
string hostName = ((System.Net.EndPoint)client.Client.RemoteEndPoint).ToString().Split(':')[0];
if (System.Net.Security.SslStream.CheckCertificateRevocationStatus(certificate)) // Simulates ChecklistServerCertificate logic for revocation check
{
// Further checks like hostname matching can be done here.
// For simplicity, we rely on SslPolicyErrors for common issues.
return true;
}
}
return false;
}
// Example usage (for demonstration, requires a server to connect to)
public static void Main(string[] args)
{
// ConnectWithValidation("example.com", 443); // Replace with a valid HTTPS server
}
}
Requirements
Requires at least .NET Framework 4.0 or .NET Core 2.0.