Microsoft Docs

SSL (Secure Sockets Layer) API Reference

The SSL namespace provides classes and methods for establishing secure communication channels over TCP/IP. It includes functionality for authentication, encryption, and data integrity.

Contents

Overview

The SSL API is built on top of the SslStream class, which encapsulates the TLS/SSL protocol. Use it to secure data transmission between a client and a server.

Key Classes

Important Methods

MethodDescription
AuthenticateAsClientAsyncInitiates an asynchronous client-side authentication handshake.
AuthenticateAsServerAsyncInitiates an asynchronous server-side authentication handshake.
ReadAsyncReads decrypted data from the SSL stream.
WriteAsyncWrites data to the SSL stream and encrypts it.
CloseCloses the SSL connection and releases resources.

Code Samples

Creating a Secure Client Connection

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

public async Task<void> ConnectAsync(string host, int port)
{
    using var client = new TcpClient();
    await client.ConnectAsync(host, port);
    using var ssl = new SslStream(client.GetStream(), false,
        (sender, cert, chain, errors) => true); // trust any cert for demo

    await ssl.AuthenticateAsClientAsync(host);
    Console.WriteLine("SSL authentication succeeded.");
    // Send/receive data...
}

Implementing a Secure Server Listener

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

public async Task<void> StartServerAsync(int port, X509Certificate2 serverCert)
{
    var listener = new TcpListener(IPAddress.Any, port);
    listener.Start();
    while (true)
    {
        var client = await listener.AcceptTcpClientAsync();
        _ = Task.Run(async () =>
        {
            using var ssl = new SslStream(client.GetStream(), false);
            await ssl.AuthenticateAsServerAsync(serverCert, clientCertificateRequired:false,
                                                enabledSslProtocols:System.Security.Authentication.SslProtocols.Tls12,
                                                checkCertificateRevocation:false);
            Console.WriteLine("Client connected securely.");
            // Handle communication...
        });
    }
}

Remarks