EncryptedStream

Namespace: System.Net.Security

Class Overview

Provides a stream that encrypts and decrypts data using an SslStream.

The EncryptedStream class allows you to wrap an existing stream to add encryption and decryption capabilities on top of an established SSL/TLS connection. This is typically used in network communication protocols where secure data transfer is required.

Constructors

Properties

Methods

See Also

Example

The following code example demonstrates how to use EncryptedStream to wrap a TCP client's network stream for secure communication.


using System;
using System.Net.Sockets;
using System.Net.Security;
using System.Security.Cryptography.X509Certificates;
using System.IO;
using System.Text;

// This is a simplified example. Real-world SSL/TLS implementation
// requires careful certificate management and error handling.

public class SecureClient
{
    public static void ConnectAndCommunicate(string hostname, int port)
    {
        using (TcpClient client = new TcpClient())
        {
            try
            {
                client.Connect(hostname, port);
                using (NetworkStream stream = client.GetStream())
                {
                    // Use EncryptedStream to wrap the NetworkStream
                    // For client authentication, typically you don't provide client certs unless required by server
                    // targetHost should match the certificate's common name or subject alternative name
                    EncryptedStream encryptedStream = new EncryptedStream(stream, true);

                    // Authenticate as client. Null certificate means no client certificate is presented.
                    encryptedStream.AuthenticateAsClient(hostname);

                    // Now you can use encryptedStream for sending and receiving encrypted data
                    string messageToSend = "Hello, secure server!";
                    byte[] messageBytes = Encoding.ASCII.GetBytes(messageToSend);
                    encryptedStream.Write(messageBytes, 0, messageBytes.Length);
                    encryptedStream.Flush();
                    //Console.WriteLine($"Sent: {messageToSend}");

                    // Example: Reading response (simplified)
                    byte[] buffer = new byte[1024];
                    int bytesRead = encryptedStream.Read(buffer, 0, buffer.Length);
                    string response = Encoding.ASCII.GetString(buffer, 0, bytesRead);
                    //Console.WriteLine($"Received: {response}");
                }
            }
            catch (Exception ex)
            {
                //Console.Error.WriteLine($"An error occurred: {ex.Message}");
            }
        }
    }
}