CertificateValidationCallback
Overview
The CertificateValidationCallback
delegate represents a method that
validates a server's SSL certificate during an SSL/TLS handshake. It is used by
classes such as SslStream
to allow custom certificate validation logic.
Syntax
public delegate bool CertificateValidationCallback(
object sender,
X509Certificate certificate,
X509Chain chain,
SslPolicyErrors sslPolicyErrors
);
Parameters
Name | Type | Description |
---|---|---|
sender | object | The object that is invoking the callback. |
certificate | X509Certificate | The certificate presented by the remote party. |
chain | X509Chain | The chain of certificate authorities associated with the certificate. |
sslPolicyErrors | SslPolicyErrors | Any SSL policy errors detected during the handshake. |
Return Value
Returns true
to accept the certificate; false
to reject it.
Remarks
The delegate is typically assigned to the SslStream.CertificateValidationCallback
property. Implementations can perform additional checks such as hostname validation,
revocation status, or custom trust lists.
Example
using System;
using System.Net.Security;
using System.Security.Cryptography.X509Certificates;
class Program
{
static void Main()
{
var client = new TcpClient("example.com", 443);
var stream = new SslStream(client.GetStream(), false, ValidateServerCertificate);
stream.AuthenticateAsClient("example.com");
}
public static bool ValidateServerCertificate(
object sender,
X509Certificate certificate,
X509Chain chain,
SslPolicyErrors sslPolicyErrors)
{
// Accept self‑signed certificates for testing only.
if (sslPolicyErrors == SslPolicyErrors.RemoteCertificateChainErrors &&
chain.ChainStatus[0].Status == X509ChainStatusFlags.UntrustedRoot)
{
return true;
}
return sslPolicyErrors == SslPolicyErrors.None;
}
}