This topic describes the constructors for the SslStream class.
public SslStream(Stream innerStream, bool leaveInnerStreamOpen);
true to leave the inner stream open after the SslStream object is disposed; otherwise, false.SslStream class using the specified stream and a Boolean value that indicates whether the inner stream should be left open.public SslStream(Stream innerStream, bool leaveInnerStreamOpen, RemoteCertificateValidationCallback userCertificateValidationCallback);
true to leave the inner stream open after the SslStream object is disposed; otherwise, false.SslStream class using the specified stream, a Boolean value that indicates whether the inner stream should be left open, and a callback delegate for certificate validation.public SslStream(Stream innerStream, bool leaveInnerStreamOpen, RemoteCertificateValidationCallback userCertificateValidationCallback, System.Net.Security.EncryptionPolicy encryptionPolicy);
true to leave the inner stream open after the SslStream object is disposed; otherwise, false.SslStream class using the specified stream, a Boolean value indicating whether the inner stream should be left open, a callback delegate for certificate validation, and an encryption policy.
using System;
using System.Net.Security;
using System.Net.Sockets;
using System.Security.Cryptography.X509Certificates;
using System.IO;
// ...
public class SslClientExample
{
public static void Connect(string host, int port)
{
using (var client = new TcpClient(host, port))
using (var stream = client.GetStream())
{
// Using the constructor with custom validation
using (var sslStream = new SslStream(stream, false,
new RemoteCertificateValidationCallback(ValidateServerCertificate),
EncryptionPolicy.RequireEncryption))
{
try
{
sslStream.AuthenticateAsClient(host);
Console.WriteLine("SSL connection established.");
// Perform secure communication...
var buffer = new byte[2048];
int bytesRead = sslStream.Read(buffer, 0, buffer.Length);
Console.WriteLine($"Received: {System.Text.Encoding.UTF8.GetString(buffer, 0, bytesRead)}");
}
catch (Exception ex)
{
Console.WriteLine($"SSL authentication failed: {ex.Message}");
}
}
}
}
public static bool ValidateServerCertificate(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors)
{
if (sslPolicyErrors == SslPolicyErrors.None)
return true;
Console.WriteLine($"Certificate error: {sslPolicyErrors}");
// In production, you might want to perform more robust validation
// For demonstration purposes, we'll accept most certificates
return true;
}
}