System.Net.Security Namespace

The System.Net.Security namespace provides classes that enable secure network communication using the Transport Layer Security (TLS) and Secure Sockets Layer (SSL) protocols. These classes allow you to create secure client and server applications that can encrypt and authenticate data transmitted over a network.

Key functionalities include:

  • Establishing secure connections using certificates.
  • Authenticating clients and servers.
  • Encrypting and decrypting data streams.
  • Handling certificate validation and management.

Code Example: Basic SSL Client

This example demonstrates how to create a simple SSL/TLS client that connects to a secure server.

using System;
using System.Net.Sockets;
using System.Net.Security;
using System.Security.Cryptography.X509Certificates;
using System.Text;
using System.Threading.Tasks;

public class SslClient
{
    public static async Task ConnectAsync(string host, int port)
    {
        using (var client = new TcpClient())
        {
            await client.ConnectAsync(host, port);
            Console.WriteLine($"Connected to {host}:{port}");

            using (var sslStream = new SslStream(client.GetStream(), false, new RemoteCertificateValidationCallback(ValidateServerCertificate), null))
            {
                try
                {
                    // Authenticate as client
                    await sslStream.AuthenticateAsClientAsync(host);

                    // Data to send
                    byte[] message = Encoding.UTF8.GetBytes("Hello from SSL Client!");
                    await sslStream.WriteAsync(message, 0, message.Length);
                    await sslStream.FlushAsync();
                    Console.WriteLine("Sent: Hello from SSL Client!");

                    // Receive response
                    byte[] buffer = new byte[2048];
                    int bytesRead = await sslStream.ReadAsync(buffer, 0, buffer.Length);
                    string response = Encoding.UTF8.GetString(buffer, 0, bytesRead);
                    Console.WriteLine($"Received: {response}");
                }
                catch (Exception ex)
                {
                    Console.WriteLine($"Error: {ex.Message}");
                }
            }
        }
    }

    // Callback to validate the server certificate
    public static bool ValidateServerCertificate(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors)
    {
        if (sslPolicyErrors == SslPolicyErrors.None)
            return true;

        Console.WriteLine($"Certificate error: {sslPolicyErrors}");

        // Do not allow this sample to communicate with servers that
        // cause certificate chain errors.
        return false;
    }

    public static async Task Main(string[] args)
    {
        // Replace with a valid SSL server host and port
        await ConnectAsync("example.com", 443);
    }
}