SslStream.SetSslProtocol Method
Namespace: System.Net.Security
Assembly: System.Net.Security.dll
Syntax
public void SetSslProtocol(SslProtocols sslProtocolType)
Parameters
| Name | Description | Type |
|---|---|---|
sslProtocolType |
One of the SslProtocols enumeration values that specifies the SSL protocol to use. | SslProtocols |
Remarks
The SetSslProtocol method allows you to explicitly specify the SSL protocol version that the SslStream will attempt to negotiate with the remote party. This method must be called before the AuthenticateAsClient or AuthenticateAsServer methods.
If this method is not called, the SslStream will use the default SSL protocol settings, which are typically determined by the operating system.
It is recommended to use the latest secure protocols such as Tls12 or Tls13 when possible. Avoid using older protocols like Ssl2 or Ssl3 due to known security vulnerabilities.
Possible values for SslProtocols:
Ssl2Ssl3Tls10(TLS 1.0)Tls11(TLS 1.1)Tls12(TLS 1.2)Tls13(TLS 1.3)Default(Uses the system default)
Example
using System;
using System.Net.Security;
using System.Net.Sockets;
using System.Security.Cryptography.X509Certificates;
public class SslExample {
public static void Main(string[] args) {
try {
TcpClient client = new TcpClient("example.com", 443);
SslStream sslStream = new SslStream(
client.GetStream(),
false,
new RemoteCertificateValidationCallback(ValidateServerCertificate),
null);
// Explicitly set the SSL protocol to TLS 1.2
sslStream.SetSslProtocol(SslProtocols.Tls12);
sslStream.AuthenticateAsClient("example.com");
Console.WriteLine("SSL connection established using TLS 1.2.");
// Perform secure communication...
sslStream.Close();
client.Close();
} catch (Exception ex) {
Console.WriteLine($"Error: {ex.Message}");
}
}
public static bool ValidateServerCertificate(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors) {
// In a production application, you should carefully validate the certificate.
// For demonstration purposes, we'll accept any valid certificate.
if (sslPolicyErrors == SslPolicyErrors.None)
return true;
Console.WriteLine($"Certificate error: {sslPolicyErrors}");
return false;
}
}
Requirements
| Product | .NET Framework 4.5, .NET Core 1.0, .NET Standard 1.3, .NET 5 and later versions. |
| Namespace | System.Net.Security |
| Assembly | System.Net.Security.dll |