Namespace: System.Net.Security
Assembly: System (in System.dll)
Specifies the level of encryption required for network communications using the SslStream class. This enumeration is used to configure the encryption requirements when establishing an SSL/TLS connection.
The EncryptionPolicy enumeration provides a set of predefined policies for controlling the encryption strength and requirements during SSL/TLS handshakes. Developers can choose a policy that balances security needs with compatibility and performance considerations.
Key policies include:
Specifies that no encryption level is enforced. This policy might allow unencrypted connections, depending on the underlying SSL/TLS provider. Use with caution.
Specifies that connections without encryption are allowed. The SSL/TLS implementation will attempt to negotiate the strongest available encryption, but will fall back to an unencrypted connection if necessary.
Specifies that the connection must be encrypted. If an SSL/TLS connection cannot be established with encryption, the connection will fail. This is the recommended policy for most applications.
.NET Framework: Supported in: 4.5, 4.0, 3.5, 3.0, 2.0
.NET Standard: Supported in: 2.1, 2.0
.NET Core: Supported in: 3.0, 2.1, 2.0
// Example usage:
using System;
using System.Net.Security;
using System.Net.Sockets;
using System.Security.Authentication;
using System.Security.Cryptography.X509Certificates;
using System.Threading.Tasks;
public class SslClient
{
public static async Task ConnectAsync(string host, int port)
{
using (var client = new TcpClient(host, port))
using (var sslStream = new SslStream(client.GetStream(), false, new RemoteCertificateValidationCallback(ValidateServerCertificate), null))
{
try
{
// Require encryption for the connection
await sslStream.AuthenticateAsClientAsync(host, null, SslProtocols.Tls12, false);
// Now you can use sslStream to send and receive encrypted data
Console.WriteLine("SSL/TLS connection established successfully with encryption.");
// ... send/receive data ...
}
catch (AuthenticationException e)
{
Console.WriteLine($"Authentication failed: {e.Message}");
// Handle authentication failure, potentially due to encryption policy
}
catch (Exception e)
{
Console.WriteLine($"An error occurred: {e.Message}");
}
}
}
public static bool ValidateServerCertificate(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors)
{
// For simplicity, accept any certificate. In production, implement proper validation.
if (sslPolicyErrors == SslPolicyErrors.None)
return true;
Console.WriteLine($"Certificate error: {sslPolicyErrors}");
return false; // Reject the certificate if there are errors
}
public static void Main(string[] args)
{
// Example: Replace with your actual host and port
// ConnectAsync("example.com", 443);
Console.WriteLine("Example usage shown. Uncomment and run with a valid host/port.");
}
}