Specifies the certificate validation mode for an SslStream.
public enum SslValidationType
The remote certificate is validated.
The local certificate is validated.
Both the remote and local certificates are validated.
This enumeration is used by the SslStream class to determine which certificates should be validated during the SSL/TLS handshake.
When performing SSL/TLS communication, it is crucial to validate the identity of the other party to prevent man-in-the-middle attacks. The SslValidationType enumeration provides a flexible way to control the level of validation performed.
RemoteCertificate is the most common mode, ensuring that the server's certificate is valid and trusted.LocalCertificate can be used in scenarios where mutual authentication is required, and the client also needs to present a valid certificate to the server.AllCertificates is used when both parties need to present and have their certificates validated.System.dll
System.Net.Security
Windows 7, Windows Server 2008 R2, Windows Vista SP1, Windows XP SP2, .NET Framework 3.5, .NET Framework Client Profile, .NET Framework 4, .NET Framework 4.5
The following C# code demonstrates how to configure an SslStream to validate the remote certificate:
using System;
using System.Net.Sockets;
using System.Net.Security;
using System.Security.Cryptography.X509Certificates;
using System.Text;
public class SslExample
{
public static void Main(string[] args)
{
try
{
// Assuming you have a TcpClient connected to an SSL server
// TcpClient client = new TcpClient("server.example.com", 443);
// For demonstration, let's simulate a stream
// In a real scenario, this would be client.GetStream();
// NetworkStream networkStream = client.GetStream();
// SslStream sslStream = new SslStream(networkStream, false,
// new RemoteCertificateValidationCallback(ValidateServerCertificate), null);
// Placeholder for SslStream initialization
Console.WriteLine("Simulating SSL Stream setup...");
// In a real scenario, you'd call AuthenticateAsClient() here
// sslStream.AuthenticateAsClient("server.example.com");
// For this example, we'll just show the validation callback registration
Console.WriteLine("SslStream configured to use ValidateServerCertificate callback.");
}
catch (Exception ex)
{
Console.WriteLine("An error occurred: {ex.Message}");
}
}
// Custom certificate validation callback
public static bool ValidateServerCertificate(
object sender,
X509Certificate? certificate,
X509Chain? chain,
SslPolicyErrors sslPolicyErrors)
{
if (sslPolicyErrors == SslPolicyErrors.None)
{
// Certificate is valid.
return true;
}
Console.WriteLine("Certificate error: {sslPolicyErrors}");
// Do not allow this exception to be reported.
return false;
}
}
In this example, the ValidateServerCertificate method is provided as a callback. If sslPolicyErrors is SslPolicyErrors.None, it means the remote certificate is considered valid by the system, and the method returns true, allowing the SSL connection to proceed.