.NET Library

Documentation for .NET APIs

Namespace: System.Net.Security

Summary

Provides classes that enable secure network communications using the Transport Layer Security (TLS) protocol. This namespace is crucial for building applications that require encrypted data transfer over networks, such as HTTPS web services, secure FTP, and other client-server applications.

Key Classes and Interfaces

Usage Example

Here's a basic example of how to use SslStream to establish a secure connection:


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

public class SecureClient
{
    public static async Task ConnectAndSendAsync(string host, int port)
    {
        using (var client = new TcpClient())
        {
            await client.ConnectAsync(host, port);
            using (var stream = client.GetStream())
            using (var sslStream = new SslStream(stream, false, new RemoteCertificateValidationCallback(ValidateServerCertificate)))
            {
                try
                {
                    // Authenticate as client
                    await sslStream.AuthenticateAsClientAsync(host);

                    // Send data
                    byte[] message = Encoding.UTF8.GetBytes("Hello, secure world!");
                    await sslStream.WriteAsync(message, 0, message.Length);
                    await sslStream.FlushAsync();

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

    // Basic certificate validation callback
    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'd want more robust validation.
        // For testing, you might allow self-signed certificates.
        return false;
    }
}