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
- SslStream – Provides the core SSL/TLS functionality.
- TlsCipherSuite – Represents a cipher suite negotiated during the handshake.
- CertificateValidationCallback – Delegate used to validate server certificates.
- EncryptedStream – Helper for encrypting/decrypting data streams.
Important Methods
| Method | Description |
|---|---|
AuthenticateAsClientAsync | Initiates an asynchronous client-side authentication handshake. |
AuthenticateAsServerAsync | Initiates an asynchronous server-side authentication handshake. |
ReadAsync | Reads decrypted data from the SSL stream. |
WriteAsync | Writes data to the SSL stream and encrypts it. |
Close | Closes 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
- Prefer TLS 1.2 or higher; SSL 3.0 is deprecated.
- Always validate server certificates in production code.
- Use
SslProtocolsenumeration to restrict protocol versions. - Refer to the SslStream page for advanced scenarios.