SslStream Classe

Definizione

Fornisce un flusso usato per la comunicazione client-server che usa il protocollo di sicurezza SSL (Secure Socket Layer) per autenticare il server ed eventualmente il client.

public ref class SslStream : System::Net::Security::AuthenticatedStream
public class SslStream : System.Net.Security.AuthenticatedStream
type SslStream = class
    inherit AuthenticatedStream
type SslStream = class
    inherit AuthenticatedStream
    interface IDisposable
Public Class SslStream
Inherits AuthenticatedStream
Ereditarietà
Ereditarietà
Implementazioni

Esempio

L'esempio di codice seguente illustra la creazione di un oggetto TcpListener che usa la SslStream classe per comunicare con i client.

#using <System.dll>

using namespace System;
using namespace System::Collections;
using namespace System::Net;
using namespace System::Net::Sockets;
using namespace System::Net::Security;
using namespace System::Security::Authentication;
using namespace System::Text;
using namespace System::Security::Cryptography::X509Certificates;
using namespace System::IO;
public ref class SslTcpServer sealed
{
private:
   static X509Certificate^ serverCertificate = nullptr;

public:

   // The certificate parameter specifies the name of the file 
   // containing the machine certificate.
   static void RunServer( String^ certificate )
   {
      serverCertificate = X509Certificate::CreateFromCertFile( certificate );
      
      // Create a TCP/IP (IPv4) socket and listen for incoming connections.
      TcpListener^ listener = gcnew TcpListener( IPAddress::Any,8080 );
      listener->Start();
      
      while (true) 
      {
         Console::WriteLine( L"Waiting for a client to connect..." );
         
         // Application blocks while waiting for an incoming connection.
         // Type CNTL-C to terminate the server.
         TcpClient^ client = listener->AcceptTcpClient();
         ProcessClient( client );

      }
   }


   static void ProcessClient( TcpClient^ client )
   {
      
      // A client has connected. Create the 
      // SslStream using the client's network stream.
      SslStream^ sslStream = gcnew SslStream( client->GetStream(),false );
      
      // Authenticate the server but don't require the client to authenticate.
      try
      {
         sslStream->AuthenticateAsServer( serverCertificate, false, true );
         // false == no client cert required; true == check cert revocation.
         
         // Display the properties and settings for the authenticated stream.
         DisplaySecurityLevel( sslStream );
         DisplaySecurityServices( sslStream );
         DisplayCertificateInformation( sslStream );
         DisplayStreamProperties( sslStream );
         
         // Set timeouts for the read and write to 5 seconds.
         sslStream->ReadTimeout = 5000;
         sslStream->WriteTimeout = 5000;
         
         // Read a message from the client.   
         Console::WriteLine( L"Waiting for client message..." );
         String^ messageData = ReadMessage( sslStream );
         Console::WriteLine( L"Received: {0}", messageData );
         
         // Write a message to the client.
         array<Byte>^message = Encoding::UTF8->GetBytes( L"Hello from the server.<EOF>" );
         Console::WriteLine( L"Sending hello message." );
         sslStream->Write( message );
      }
      catch ( AuthenticationException^ e ) 
      {
         Console::WriteLine( L"Exception: {0}", e->Message );
         if ( e->InnerException != nullptr )
         {
            Console::WriteLine( L"Inner exception: {0}", e->InnerException->Message );
         }
         Console::WriteLine( L"Authentication failed - closing the connection." );
         sslStream->Close();
         client->Close();
         return;
      }
      finally
      {
         
         // The client stream will be closed with the sslStream
         // because we specified this behavior when creating
         // the sslStream.
         sslStream->Close();
         client->Close();
      }

   }


   static String^ ReadMessage( SslStream^ sslStream )
   {
      
      // Read the  message sent by the client.
      // The client signals the end of the message using the
      // "<EOF>" marker.
      array<Byte>^buffer = gcnew array<Byte>(2048);
      StringBuilder^ messageData = gcnew StringBuilder;
      int bytes = -1;
      do
      {
         
         // Read the client's test message.
         bytes = sslStream->Read( buffer, 0, buffer->Length );
         
         // Use Decoder class to convert from bytes to UTF8
         // in case a character spans two buffers.
         Decoder^ decoder = Encoding::UTF8->GetDecoder();
         array<Char>^chars = gcnew array<Char>(decoder->GetCharCount( buffer, 0, bytes ));
         decoder->GetChars( buffer, 0, bytes, chars, 0 );
         messageData->Append( chars );
         
         // Check for EOF or an empty message.
         if ( messageData->ToString()->IndexOf( L"<EOF>" ) != -1 )
         {
            break;
         }
      }
      while ( bytes != 0 );

      return messageData->ToString();
   }


   static void DisplaySecurityLevel( SslStream^ stream )
   {
      Console::WriteLine( L"Cipher: {0} strength {1}", stream->CipherAlgorithm, stream->CipherStrength );
      Console::WriteLine( L"Hash: {0} strength {1}", stream->HashAlgorithm, stream->HashStrength );
      Console::WriteLine( L"Key exchange: {0} strength {1}", stream->KeyExchangeAlgorithm, stream->KeyExchangeStrength );
      Console::WriteLine( L"Protocol: {0}", stream->SslProtocol );
   }


   static void DisplaySecurityServices( SslStream^ stream )
   {
      Console::WriteLine( L"Is authenticated: {0} as server? {1}", stream->IsAuthenticated, stream->IsServer );
      Console::WriteLine( L"IsSigned: {0}", stream->IsSigned );
      Console::WriteLine( L"Is Encrypted: {0}", stream->IsEncrypted );
   }


   static void DisplayStreamProperties( SslStream^ stream )
   {
      Console::WriteLine( L"Can read: {0}, write {1}", stream->CanRead, stream->CanWrite );
      Console::WriteLine( L"Can timeout: {0}", stream->CanTimeout );
   }


   static void DisplayCertificateInformation( SslStream^ stream )
   {
      Console::WriteLine( L"Certificate revocation list checked: {0}", stream->CheckCertRevocationStatus );
      X509Certificate^ localCertificate = stream->LocalCertificate;
      if ( stream->LocalCertificate != nullptr )
      {
         Console::WriteLine( L"Local cert was issued to {0} and is valid from {1} until {2}.", 
             localCertificate->Subject, 
             localCertificate->GetEffectiveDateString(), 
             localCertificate->GetExpirationDateString() );
      }
      else
      {
         Console::WriteLine( L"Local certificate is null." );
      }

      X509Certificate^ remoteCertificate = stream->RemoteCertificate;
      if ( stream->RemoteCertificate != nullptr )
      {
         Console::WriteLine( L"Remote cert was issued to {0} and is valid from {1} until {2}.", 
            remoteCertificate->Subject, 
            remoteCertificate->GetEffectiveDateString(), 
            remoteCertificate->GetExpirationDateString() );
      }
      else
      {
         Console::WriteLine( L"Remote certificate is null." );
      }
   }


private:

   static void DisplayUsage()
   {
      Console::WriteLine( L"To start the server specify:" );
      Console::WriteLine( L"serverSync certificateFile.cer" );
      Environment::Exit( 1 );
   }

public:
   int RunServerASync()
   {
      array<String^>^args = Environment::GetCommandLineArgs();
      String^ certificate = nullptr;
      if ( args == nullptr || args->Length < 2 )
      {
         DisplayUsage();
      }

      certificate = args[ 1 ];
      SslTcpServer::RunServer( certificate );
      return 0;
   }

};

int main(){
    SslTcpServer^ sts = gcnew SslTcpServer();
    sts->RunServerASync();
}
using System;
using System.Collections;
using System.Net;
using System.Net.Sockets;
using System.Net.Security;
using System.Security.Authentication;
using System.Text;
using System.Security.Cryptography.X509Certificates;
using System.IO;

namespace Examples.System.Net
{
    public sealed class SslTcpServer
    {
        static X509Certificate serverCertificate = null;
        // The certificate parameter specifies the name of the file
        // containing the machine certificate.
        public static void RunServer(string certificate)
        {
            serverCertificate = X509Certificate.CreateFromCertFile(certificate);
            // Create a TCP/IP (IPv4) socket and listen for incoming connections.
            TcpListener listener = new TcpListener(IPAddress.Any, 8080);
            listener.Start();
            while (true)
            {
                Console.WriteLine("Waiting for a client to connect...");
                // Application blocks while waiting for an incoming connection.
                // Type CNTL-C to terminate the server.
                TcpClient client = listener.AcceptTcpClient();
                ProcessClient(client);
            }
        }
        static void ProcessClient (TcpClient client)
        {
            // A client has connected. Create the
            // SslStream using the client's network stream.
            SslStream sslStream = new SslStream(
                client.GetStream(), false);
            // Authenticate the server but don't require the client to authenticate.
            try
            {
                sslStream.AuthenticateAsServer(serverCertificate, clientCertificateRequired: false, checkCertificateRevocation: true);

                // Display the properties and settings for the authenticated stream.
                DisplaySecurityLevel(sslStream);
                DisplaySecurityServices(sslStream);
                DisplayCertificateInformation(sslStream);
                DisplayStreamProperties(sslStream);

                // Set timeouts for the read and write to 5 seconds.
                sslStream.ReadTimeout = 5000;
                sslStream.WriteTimeout = 5000;
                // Read a message from the client.
                Console.WriteLine("Waiting for client message...");
                string messageData = ReadMessage(sslStream);
                Console.WriteLine("Received: {0}", messageData);

                // Write a message to the client.
                byte[] message = Encoding.UTF8.GetBytes("Hello from the server.<EOF>");
                Console.WriteLine("Sending hello message.");
                sslStream.Write(message);
            }
            catch (AuthenticationException e)
            {
                Console.WriteLine("Exception: {0}", e.Message);
                if (e.InnerException != null)
                {
                    Console.WriteLine("Inner exception: {0}", e.InnerException.Message);
                }
                Console.WriteLine ("Authentication failed - closing the connection.");
                sslStream.Close();
                client.Close();
                return;
            }
            finally
            {
                // The client stream will be closed with the sslStream
                // because we specified this behavior when creating
                // the sslStream.
                sslStream.Close();
                client.Close();
            }
        }
        static string ReadMessage(SslStream sslStream)
        {
            // Read the  message sent by the client.
            // The client signals the end of the message using the
            // "<EOF>" marker.
            byte [] buffer = new byte[2048];
            StringBuilder messageData = new StringBuilder();
            int bytes = -1;
            do
            {
                // Read the client's test message.
                bytes = sslStream.Read(buffer, 0, buffer.Length);

                // Use Decoder class to convert from bytes to UTF8
                // in case a character spans two buffers.
                Decoder decoder = Encoding.UTF8.GetDecoder();
                char[] chars = new char[decoder.GetCharCount(buffer,0,bytes)];
                decoder.GetChars(buffer, 0, bytes, chars,0);
                messageData.Append (chars);
                // Check for EOF or an empty message.
                if (messageData.ToString().IndexOf("<EOF>") != -1)
                {
                    break;
                }
            } while (bytes !=0);

            return messageData.ToString();
        }
         static void DisplaySecurityLevel(SslStream stream)
         {
            Console.WriteLine("Cipher: {0} strength {1}", stream.CipherAlgorithm, stream.CipherStrength);
            Console.WriteLine("Hash: {0} strength {1}", stream.HashAlgorithm, stream.HashStrength);
            Console.WriteLine("Key exchange: {0} strength {1}", stream.KeyExchangeAlgorithm, stream.KeyExchangeStrength);
            Console.WriteLine("Protocol: {0}", stream.SslProtocol);
         }
         static void DisplaySecurityServices(SslStream stream)
         {
            Console.WriteLine("Is authenticated: {0} as server? {1}", stream.IsAuthenticated, stream.IsServer);
            Console.WriteLine("IsSigned: {0}", stream.IsSigned);
            Console.WriteLine("Is Encrypted: {0}", stream.IsEncrypted);
         }
         static void DisplayStreamProperties(SslStream stream)
         {
            Console.WriteLine("Can read: {0}, write {1}", stream.CanRead, stream.CanWrite);
            Console.WriteLine("Can timeout: {0}", stream.CanTimeout);
         }
        static void DisplayCertificateInformation(SslStream stream)
        {
            Console.WriteLine("Certificate revocation list checked: {0}", stream.CheckCertRevocationStatus);

            X509Certificate localCertificate = stream.LocalCertificate;
            if (stream.LocalCertificate != null)
            {
                Console.WriteLine("Local cert was issued to {0} and is valid from {1} until {2}.",
                    localCertificate.Subject,
                    localCertificate.GetEffectiveDateString(),
                    localCertificate.GetExpirationDateString());
             } else
            {
                Console.WriteLine("Local certificate is null.");
            }
            // Display the properties of the client's certificate.
            X509Certificate remoteCertificate = stream.RemoteCertificate;
            if (stream.RemoteCertificate != null)
            {
            Console.WriteLine("Remote cert was issued to {0} and is valid from {1} until {2}.",
                remoteCertificate.Subject,
                remoteCertificate.GetEffectiveDateString(),
                remoteCertificate.GetExpirationDateString());
            } else
            {
                Console.WriteLine("Remote certificate is null.");
            }
        }
        private static void DisplayUsage()
        {
            Console.WriteLine("To start the server specify:");
            Console.WriteLine("serverSync certificateFile.cer");
            Environment.Exit(1);
        }
        public static int Main(string[] args)
        {
            string certificate = null;
            if (args == null ||args.Length < 1 )
            {
                DisplayUsage();
            }
            certificate = args[0];
            SslTcpServer.RunServer (certificate);
            return 0;
        }
    }
}
Imports System.Collections
Imports System.Net
Imports System.Net.Sockets
Imports System.Net.Security
Imports System.Security.Authentication
Imports System.Text
Imports System.Security.Cryptography.X509Certificates
Imports System.IO

Namespace Examples.System.Net
    Public NotInheritable Class SslTcpServer
        Shared serverCertificate As X509Certificate = Nothing

        ' The certificate parameter specifies the name of the file 
        ' containing the machine certificate.
        Public Shared Sub RunServer(certificate As String)
            serverCertificate = X509Certificate.CreateFromCertFile(certificate)
            ' Create a TCP/IP (IPv4) socket And listen for incoming connections.
            Dim listener = New TcpListener(IPAddress.Any, 8080)
            listener.Start()

            While True
                Console.WriteLine("Waiting for a client to connect...")
                ' Application blocks while waiting for an incoming connection.
                ' Type CNTL-C to terminate the server.
                Dim client As TcpClient = listener.AcceptTcpClient()
                ProcessClient(client)
            End While
        End Sub
        Private Shared Sub ProcessClient(client As TcpClient)
            ' A client has connected. Create the 
            ' SslStream using the client's network stream.
            Dim sslStream = New SslStream(client.GetStream(), False)

            Try

                sslStream.AuthenticateAsServer(serverCertificate, clientCertificateRequired:=False, checkCertificateRevocation:=True)
                ' Display the properties And settings for the authenticated stream.
                DisplaySecurityLevel(sslStream)
                DisplaySecurityServices(sslStream)
                DisplayCertificateInformation(sslStream)
                DisplayStreamProperties(sslStream)

                ' Set timeouts for the read and write to 5 seconds.
                sslStream.ReadTimeout = 5000
                sslStream.WriteTimeout = 5000

                ' Read a message from the client.   
                Console.WriteLine("Waiting for client message...")
                Dim messageData As String = ReadMessage(sslStream)
                Console.WriteLine("Received: {0}", messageData)

                ' Write a message to the client.
                Dim message As Byte() = Encoding.UTF8.GetBytes("Hello from the server.<EOF>")
                Console.WriteLine("Sending hello message.")
                sslStream.Write(message)
            Catch e As AuthenticationException
                Console.WriteLine("Exception: {0}", e.Message)

                If e.InnerException IsNot Nothing Then
                    Console.WriteLine("Inner exception: {0}", e.InnerException.Message)
                End If

                Console.WriteLine("Authentication failed - closing the connection.")
                sslStream.Close()
                client.Close()
                Return
            Finally
                ' The client stream will be closed with the sslStream
                ' because we specified this behavior when creating
                ' the sslStream.
                sslStream.Close()
                client.Close()
            End Try
        End Sub

        Private Shared Function ReadMessage(sslStream As SslStream) As String

            ' Read the  message sent by the client.
            ' The client signals the end of the message using the
            ' "<EOF>" marker.
            Dim buffer As Byte() = New Byte(2048) {}
            Dim messageData As StringBuilder = New StringBuilder()
            Dim bytes As Integer = -1

            Do
                ' Read the client's test message.
                bytes = sslStream.Read(buffer, 0, buffer.Length)

                ' Use decoder class to convert from bytes to UTF8
                ' in case a character spans two buffers.
                Dim decoder As Decoder = Encoding.UTF8.GetDecoder()
                Dim chars As Char() = New Char(decoder.GetCharCount(buffer, 0, bytes) - 1) {}
                decoder.GetChars(buffer, 0, bytes, chars, 0)
                messageData.Append(chars)

                ' Check for EOF or an empty message.
                If messageData.ToString().IndexOf("<EOF>") <> -1 Then
                    Exit Do
                End If
            Loop While bytes <> 0

            Return messageData.ToString()
        End Function

        Private Shared Sub DisplaySecurityLevel(stream As SslStream)
            Console.WriteLine("Cipher: {0} strength {1}", stream.CipherAlgorithm, stream.CipherStrength)
            Console.WriteLine("Hash: {0} strength {1}", stream.HashAlgorithm, stream.HashStrength)
            Console.WriteLine("Key exchange: {0} strength {1}", stream.KeyExchangeAlgorithm, stream.KeyExchangeStrength)
            Console.WriteLine("Protocol: {0}", stream.SslProtocol)
        End Sub

        Private Shared Sub DisplaySecurityServices(stream As SslStream)
            Console.WriteLine("Is authenticated: {0} as server? {1}", stream.IsAuthenticated, stream.IsServer)
            Console.WriteLine("IsSigned: {0}", stream.IsSigned)
            Console.WriteLine("Is Encrypted: {0}", stream.IsEncrypted)
        End Sub

        Private Shared Sub DisplayStreamProperties(stream As SslStream)
            Console.WriteLine("Can read: {0}, write {1}", stream.CanRead, stream.CanWrite)
            Console.WriteLine("Can timeout: {0}", stream.CanTimeout)
        End Sub

        Private Shared Sub DisplayCertificateInformation(stream As SslStream)
            Console.WriteLine("Certificate revocation list checked: {0}", stream.CheckCertRevocationStatus)
            Dim localCertificate As X509Certificate = stream.LocalCertificate

            If stream.LocalCertificate IsNot Nothing Then
                Console.WriteLine("Local cert was issued to {0} and is valid from {1} until {2}.", localCertificate.Subject, localCertificate.GetEffectiveDateString(), localCertificate.GetExpirationDateString())
            Else
                Console.WriteLine("Local certificate is null.")
            End If

            ' Display the properties of the client's certificate.
            Dim remoteCertificate As X509Certificate = stream.RemoteCertificate

            If stream.RemoteCertificate IsNot Nothing Then
                Console.WriteLine("Remote cert was issued to {0} and is valid from {1} until {2}.", remoteCertificate.Subject, remoteCertificate.GetEffectiveDateString(), remoteCertificate.GetExpirationDateString())
            Else
                Console.WriteLine("Remote certificate is null.")
            End If
        End Sub

        Private Shared Sub DisplayUsage()
            Console.WriteLine("To start the server specify:")
            Console.WriteLine("serverSync certificateFile.cer")
            Environment.[Exit](1)
        End Sub

        Public Shared Function Main(ByVal args As String()) As Integer
            Dim certificate As String

            If args Is Nothing OrElse args.Length < 1 Then
                DisplayUsage()
            End If

            certificate = args(0)
            RunServer(certificate)
            Return 0
        End Function
    End Class
End Namespace

L'esempio di codice seguente illustra la creazione di un oggetto TcpClient che usa la SslStream classe per comunicare con un server.

#using <System.dll>
#using <System.Security.dll>

using namespace System;
using namespace System::Collections;
using namespace System::Globalization;
using namespace System::Net;
using namespace System::Net::Security;
using namespace System::Net::Sockets;
using namespace System::Security::Authentication;
using namespace System::Text;
using namespace System::Security::Cryptography::X509Certificates;
using namespace System::IO;

namespace NlsClientSync
{
    public ref class SslTcpClient
    {
    private:
        static Hashtable^ certificateErrors = gcnew Hashtable;
        // Load a table of errors that might cause 
        // the certificate authentication to fail.
        static void InitializeCertificateErrors()
        {
            certificateErrors->Add(0x800B0101,
                "The certification has expired.");
            certificateErrors->Add(0x800B0104,
                "A path length constraint "
                "in the certification chain has been violated.");
            certificateErrors->Add(0x800B0105,
                "A certificate contains an unknown extension "
                "that is marked critical.");
            certificateErrors->Add(0x800B0107,
                "A parent of a given certificate in fact "
                "did not issue that child certificate.");
            certificateErrors->Add(0x800B0108,
                "A certificate is missing or has an empty value "
                "for a necessary field.");
            certificateErrors->Add(0x800B0109,
                "The certificate root is not trusted.");
            certificateErrors->Add(0x800B010C,
                "The certificate has been revoked.");
            certificateErrors->Add(0x800B010F,
                "The name in the certificate does not not match "
                "the host name requested by the client.");
            certificateErrors->Add(0x800B0111,
                "The certificate was explicitly marked "
                "as untrusted by the user.");
            certificateErrors->Add(0x800B0112,
                "A certification chain processed correctly, "
                "but one of the CA certificates is not trusted.");
            certificateErrors->Add(0x800B0113,
                "The certificate has an invalid policy.");
            certificateErrors->Add(0x800B0114,
                "The certificate name is either not "
                "in the permitted list or is explicitly excluded.");
            certificateErrors->Add(0x80092012,
                "The revocation function was unable to check "
                "revocation for the certificate.");
            certificateErrors->Add(0x80090327,
                "An unknown error occurred while "
                "processing the certificate.");
            certificateErrors->Add(0x80096001,
                "A system-level error occurred "
                "while verifying trust.");
            certificateErrors->Add(0x80096002,
                "The certificate for the signer of the message "
                "is invalid or not found.");
            certificateErrors->Add(0x80096003,
                "One of the counter signatures was invalid.");
            certificateErrors->Add(0x80096004,
                "The signature of the certificate "
                "cannot be verified.");
            certificateErrors->Add(0x80096005,
                "The time stamp signature or certificate "
                "could not be verified or is malformed.");
            certificateErrors->Add(0x80096010,
                "The digital signature of the object "
                "was not verified.");
            certificateErrors->Add(0x80096019,
                "The basic constraint extension of a certificate "
                "has not been observed.");
        }

        static String^ CertificateErrorDescription(UInt32 problem)
        {
            // Initialize the error message dictionary 
            // if it is not yet available.
            if (certificateErrors->Count == 0)
            {
                InitializeCertificateErrors();
            }

            String^ description = safe_cast<String^>(
                certificateErrors[problem]);
            if (description == nullptr)
            {
                description = String::Format(
                    CultureInfo::CurrentCulture,
                    "Unknown certificate error - 0x{0:x8}",
                    problem);
            }

            return description;
        }

    public:
        // The following method is invoked 
        // by the CertificateValidationDelegate.
    static bool ValidateServerCertificate(
            Object^ sender,
            X509Certificate^ certificate,
            X509Chain^ chain,
            SslPolicyErrors sslPolicyErrors)
        {
        
            Console::WriteLine("Validating the server certificate.");
            if (sslPolicyErrors == SslPolicyErrors::None)
                return true;

            Console::WriteLine("Certificate error: {0}", sslPolicyErrors);

            // Do not allow this client to communicate with unauthenticated servers.
            return false;
        }

        static void RunClient(String^ machineName, String^ serverName)
        {
              
            // Create a TCP/IP client socket.
            // machineName is the host running the server application.
            TcpClient^ client = gcnew TcpClient(machineName, 8080);
            Console::WriteLine("Client connected.");
              
            // Create an SSL stream that will close 
            // the client's stream.
            SslStream^ sslStream = gcnew SslStream(
                client->GetStream(), false,
                gcnew RemoteCertificateValidationCallback(ValidateServerCertificate),
                nullptr);
              
            // The server name must match the name
            // on the server certificate.
            try
            {
                sslStream->AuthenticateAsClient(serverName);
            }
            catch (AuthenticationException^ ex) 
            {
                Console::WriteLine("Exception: {0}", ex->Message);
                if (ex->InnerException != nullptr)
                {
                    Console::WriteLine("Inner exception: {0}", 
                        ex->InnerException->Message);
                }

                Console::WriteLine("Authentication failed - "
                    "closing the connection.");
                sslStream->Close();
                client->Close();
                return;
            }
            // Encode a test message into a byte array.
            // Signal the end of the message using the "<EOF>".
            array<Byte>^ messsage = Encoding::UTF8->GetBytes(
                "Hello from the client.<EOF>");
              
            // Send hello message to the server.
            sslStream->Write(messsage);
            sslStream->Flush();
            // Read message from the server.
            String^ serverMessage = ReadMessage(sslStream);
            Console::WriteLine("Server says: {0}", serverMessage);
           
            // Close the client connection.
            sslStream->Close();
            client->Close();
            Console::WriteLine("Client closed.");
        }
    private:
        static String^ ReadMessage(SslStream^ sslStream)
        {
              
            // Read the  message sent by the server.
            // The end of the message is signaled using the
            // "<EOF>" marker.
            array<Byte>^ buffer = gcnew array<Byte>(2048);
            StringBuilder^ messageData = gcnew StringBuilder;
            // Use Decoder class to convert from bytes to UTF8
            // in case a character spans two buffers.
            Encoding^ u8 = Encoding::UTF8;
            Decoder^ decoder = u8->GetDecoder();

            int bytes = -1;
            do
            {
                bytes = sslStream->Read(buffer, 0, buffer->Length);
                 
                array<__wchar_t>^ chars = gcnew array<__wchar_t>(
                    decoder->GetCharCount(buffer, 0, bytes));
                decoder->GetChars(buffer, 0, bytes, chars, 0);
                messageData->Append(chars);
                 
                // Check for EOF.
                if (messageData->ToString()->IndexOf("<EOF>") != -1)
                {
                    break;
                }
            }
            while (bytes != 0);

            return messageData->ToString();
        }
    };
}

int main()
{
    array<String^>^ args = Environment::GetCommandLineArgs();
    String^ serverCertificateName = nullptr;
    String^ machineName = nullptr;
    if (args == nullptr || args->Length < 2)
    {
        Console::WriteLine("To start the client specify:");
        Console::WriteLine("clientSync machineName [serverName]");
        return 1;
    }
        
    // User can specify the machine name and server name.
    // Server name must match the name on 
    // the server's certificate.
    machineName = args[1];
    if (args->Length < 3)
    {
        serverCertificateName = machineName;
    }
    else
    {
        serverCertificateName = args[2];
    };

    NlsClientSync::SslTcpClient::RunClient(machineName,
        serverCertificateName);

    return 0;
}
using System;
using System.Collections;
using System.Net;
using System.Net.Security;
using System.Net.Sockets;
using System.Security.Authentication;
using System.Text;
using System.Security.Cryptography.X509Certificates;
using System.IO;

namespace Examples.System.Net
{
    public class SslTcpClient
    {
        private static Hashtable certificateErrors = new Hashtable();

        // The following method is invoked by the RemoteCertificateValidationDelegate.
        public static bool ValidateServerCertificate(
              object sender,
              X509Certificate certificate,
              X509Chain chain,
              SslPolicyErrors sslPolicyErrors)
        {
           if (sslPolicyErrors == SslPolicyErrors.None)
                return true;

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

            // Do not allow this client to communicate with unauthenticated servers.
            return false;
        }
        public static void RunClient(string machineName, string serverName)
        {
            // Create a TCP/IP client socket.
            // machineName is the host running the server application.
            TcpClient client = new TcpClient(machineName,443);
            Console.WriteLine("Client connected.");
            // Create an SSL stream that will close the client's stream.
            SslStream sslStream = new SslStream(
                client.GetStream(),
                false,
                new RemoteCertificateValidationCallback (ValidateServerCertificate),
                null
                );
            // The server name must match the name on the server certificate.
            try
            {
                sslStream.AuthenticateAsClient(serverName);
            }
            catch (AuthenticationException e)
            {
                Console.WriteLine("Exception: {0}", e.Message);
                if (e.InnerException != null)
                {
                    Console.WriteLine("Inner exception: {0}", e.InnerException.Message);
                }
                Console.WriteLine ("Authentication failed - closing the connection.");
                client.Close();
                return;
            }
            // Encode a test message into a byte array.
            // Signal the end of the message using the "<EOF>".
            byte[] messsage = Encoding.UTF8.GetBytes("Hello from the client.<EOF>");
            // Send hello message to the server.
            sslStream.Write(messsage);
            sslStream.Flush();
            // Read message from the server.
            string serverMessage = ReadMessage(sslStream);
            Console.WriteLine("Server says: {0}", serverMessage);
            // Close the client connection.
            client.Close();
            Console.WriteLine("Client closed.");
        }
        static string ReadMessage(SslStream sslStream)
        {
            // Read the  message sent by the server.
            // The end of the message is signaled using the
            // "<EOF>" marker.
            byte [] buffer = new byte[2048];
            StringBuilder messageData = new StringBuilder();
            int bytes = -1;
            do
            {
                bytes = sslStream.Read(buffer, 0, buffer.Length);

                // Use Decoder class to convert from bytes to UTF8
                // in case a character spans two buffers.
                Decoder decoder = Encoding.UTF8.GetDecoder();
                char[] chars = new char[decoder.GetCharCount(buffer,0,bytes)];
                decoder.GetChars(buffer, 0, bytes, chars,0);
                messageData.Append (chars);
                // Check for EOF.
                if (messageData.ToString().IndexOf("<EOF>") != -1)
                {
                    break;
                }
            } while (bytes != 0);

            return messageData.ToString();
        }
        private static void DisplayUsage()
        {
            Console.WriteLine("To start the client specify:");
            Console.WriteLine("clientSync machineName [serverName]");
            Environment.Exit(1);
        }
        public static int Main(string[] args)
        {
            string serverCertificateName = null;
            string machineName = null;
            if (args == null ||args.Length <1 )
            {
                DisplayUsage();
            }
            // User can specify the machine name and server name.
            // Server name must match the name on the server's certificate.
            machineName = args[0];
            if (args.Length <2 )
            {
                serverCertificateName = machineName;
            }
            else
            {
                serverCertificateName = args[1];
            }
            SslTcpClient.RunClient (machineName, serverCertificateName);
            return 0;
        }
    }
}
Imports System.Collections
Imports System.Net
Imports System.Net.Security
Imports System.Net.Sockets
Imports System.Security.Authentication
Imports System.Text
Imports System.Security.Cryptography.X509Certificates
Imports System.IO

Namespace Examples.System.Net

    Public Class SslTcpClient
        
        ' The following method is invoked by the RemoteCertificateValidationDelegate.
        Public Shared Function ValidateServerCertificate(
            sender As Object, 
            certificate As X509Certificate, 
            chain As X509Chain, 
            sslPolicyErrors As SslPolicyErrors) As Boolean
            
            If sslPolicyErrors = SslPolicyErrors.None Then Return True

            Console.WriteLine("Certificate error: {0}", sslPolicyErrors)

            ' Do not allow this client to communicate with unauthenticated servers.
            Return False
        End Function
        Public Shared Sub RunClient(machineName As String, serverName As String)

            ' Create a TCP/IP client socket.
            ' machineName is the host running the server application.
            Dim client = New TcpClient(machineName, 443)
            Console.WriteLine("Client connected.")

            ' Create an SSL stream that will close the client's stream.
            Dim sslStream = New SslStream(
                client.GetStream(), False, 
                New RemoteCertificateValidationCallback(AddressOf ValidateServerCertificate), Nothing)

            ' The server name must match the name on the server certificate.
            Try
                sslStream.AuthenticateAsClient(serverName)
            Catch e As AuthenticationException
                Console.WriteLine("Exception: {0}", e.Message)

                If e.InnerException IsNot Nothing Then
                    Console.WriteLine("Inner exception: {0}", e.InnerException.Message)
                End If

                Console.WriteLine("Authentication failed - closing the connection.")
                client.Close()
                Return
            End Try
            
            ' Encode a test message into a byte array.
            ' Signal the end of the message using the "<EOF>".
            Dim messsage As Byte() = Encoding.UTF8.GetBytes("Hello from the client.<EOF>")
            
            ' Send hello message to the server.
            sslStream.Write(messsage)
            sslStream.Flush()
            ' Read message from the server.
            Dim serverMessage = ReadMessage(sslStream)
            Console.WriteLine("Server says: {0}", serverMessage)

            ' Close the client connection
            client.Close()
            Console.WriteLine("Client closed.")
        End Sub
        
        Private Shared Function ReadMessage(sslStream As SslStream) As String

            ' Read the  message sent by the server.
            ' The end of the message is signaled using the "<EOF>" marker.
            Dim buffer = New Byte(2048) {}
            Dim messageData = New StringBuilder()
            Dim bytes As Integer

            Do
                bytes = sslStream.Read(buffer, 0, buffer.Length)

                ' Use Decoder class to convert from bytes to UTF8
                ' in case a character spans two buffers.        
                Dim decoder As Decoder = Encoding.UTF8.GetDecoder()
                Dim chars = New Char(decoder.GetCharCount(buffer, 0, bytes) - 1) {}
                decoder.GetChars(buffer, 0, bytes, chars, 0)
                messageData.Append(chars)

                ' Check for EOF.
                If messageData.ToString().IndexOf("<EOF>") <> -1 Then Exit Do
                
            Loop While bytes <> 0

            Return messageData.ToString()

        End Function

        Private Shared Sub DisplayUsage()

            Console.WriteLine("To start the client specify:")
            Console.WriteLine("clientSync machineName [serverName]")
            Environment.[Exit](1)

        End Sub

        Public Shared Function Main(args As String()) As Integer

            Dim serverCertificateName As String
            Dim machineName As String

            If args Is Nothing OrElse args.Length < 1 Then
                DisplayUsage()
            End If

            ' User can specify the machine name and server name.
            ' Server name must match the name on the server's certificate. 
            machineName = args(0)

            If args.Length < 2 Then
                serverCertificateName = machineName
            Else
                serverCertificateName = args(1)
            End If

            SslTcpClient.RunClient(machineName, serverCertificateName)

            Return 0

        End Function

    End Class

End Namespace

Commenti

I protocolli SSL consentono di fornire la riservatezza e il controllo dell'integrità per i messaggi trasmessi tramite un SslStreamoggetto . Una connessione SSL, ad esempio quella fornita da SslStream, deve essere usata durante la comunicazione di informazioni riservate tra un client e un server. L'uso di un SslStream aiuta a impedire a chiunque di leggere e manomettere le informazioni mentre è in transito sulla rete.

Un'istanza SslStream trasmette i dati usando un flusso fornito durante la creazione di SslStream. Quando si specifica questo flusso sottostante, è possibile specificare se chiudere anche il SslStream flusso sottostante. In genere, la SslStream classe viene usata con le TcpClient classi e TcpListener . Il GetStream metodo fornisce un NetworkStream oggetto adatto per l'uso con la SslStream classe .

Dopo aver creato un SslStreamoggetto , il server e facoltativamente, il client deve essere autenticato. Il server deve fornire un certificato X509 che stabilisce la prova dell'identità e può richiedere che il client lo faccia anche. L'autenticazione deve essere eseguita prima di trasmettere informazioni usando un SslStreamoggetto . I client avviano l'autenticazione usando i metodi sincroni AuthenticateAsClient , che bloccano fino al completamento dell'autenticazione o ai metodi asincroni BeginAuthenticateAsClient , che non bloccano l'attesa del completamento dell'autenticazione. I server avviano l'autenticazione usando i metodi sincroni AuthenticateAsServer o asincroni BeginAuthenticateAsServer . Sia il client che il server devono avviare l'autenticazione.

L'autenticazione viene gestita dal provider di canale SSPI (Security Support Provider). Il client ha la possibilità di controllare la convalida del certificato del server specificando un RemoteCertificateValidationCallback delegato durante la creazione di un SslStreamoggetto . Il server può anche controllare la convalida fornendo un RemoteCertificateValidationCallback delegato. Il metodo a cui fa riferimento il delegato include il certificato della entità remota e eventuali errori rilevati da SSPI durante la convalida del certificato. Si noti che se il server specifica un delegato, il metodo del delegato viene richiamato indipendentemente dal fatto che il server abbia richiesto l'autenticazione client. Se il server non ha richiesto l'autenticazione client, il metodo delegato del server riceve un certificato Null e una matrice vuota di errori del certificato.

Se il server richiede l'autenticazione client, il client deve specificare uno o più certificati per l'autenticazione. Se il client ha più certificati, il client può fornire un LocalCertificateSelectionCallback delegato per selezionare il certificato corretto per il server. I certificati del client devono trovarsi nell'archivio certificati "My" dell'utente corrente. L'autenticazione client tramite certificati non è supportata per il Ssl2 protocollo SSL versione 2.

Se l'autenticazione ha esito negativo, viene visualizzato un AuthenticationExceptionoggetto e non SslStream è più utilizzabile. È necessario chiudere questo oggetto e rimuovere tutti i riferimenti a esso in modo che possa essere raccolto dal Garbage Collector.

Quando il processo di autenticazione, noto anche come handshake SSL, ha esito positivo, l'identità del server (e facoltativamente, il client) viene stabilito e può SslStream essere usato dal client e dal server per scambiare messaggi. Prima di inviare o ricevere informazioni, il client e il server devono controllare i servizi di sicurezza e i livelli forniti dall'oggetto SslStream per determinare se il protocollo, gli algoritmi e i punti di forza selezionati soddisfano i requisiti di integrità e riservatezza. Se le impostazioni correnti non sono sufficienti, il flusso deve essere chiuso. È possibile controllare i servizi di sicurezza forniti dall'oggetto SslStream usando le IsEncrypted proprietà e IsSigned . Nella tabella seguente vengono illustrati gli elementi che segnalano le impostazioni crittografiche usate per l'autenticazione, la crittografia e la firma dei dati.

Elemento Membri
Protocollo di sicurezza usato per autenticare il server e, facoltativamente, il client. Proprietà SslProtocol e enumerazione associata SslProtocols .
Algoritmo di scambio delle chiavi. Proprietà KeyExchangeAlgorithm e enumerazione associata ExchangeAlgorithmType .
Algoritmo di integrità del messaggio. Proprietà HashAlgorithm e enumerazione associata HashAlgorithmType .
Algoritmo di riservatezza dei messaggi. Proprietà CipherAlgorithm e enumerazione associata CipherAlgorithmType .
I punti di forza degli algoritmi selezionati. Proprietà KeyExchangeStrength, HashStrengthe CipherStrength .

Dopo un'autenticazione riuscita, è possibile inviare dati usando i metodi sincroni Write o asincroni BeginWrite . È possibile ricevere dati usando i metodi sincroni Read o asincroni BeginRead .

Se si specifica che SslStream il flusso sottostante deve essere lasciato aperto, si è responsabili della chiusura del flusso al termine dell'uso.

Nota

Se l'applicazione che crea l'oggetto SslStream viene eseguita con le credenziali di un utente normale, l'applicazione non sarà in grado di accedere ai certificati installati nell'archivio computer locale, a meno che l'autorizzazione non sia stata assegnata esplicitamente all'utente.

SslStream presuppone che un timeout insieme a qualsiasi altro IOException quando uno viene generato dal flusso interno verrà considerato irreversibile dal chiamante. La riutilizzo di un'istanza dopo un SslStream timeout restituirà garbage. Un'applicazione deve Close SslStream generare un'eccezione in questi casi.

Il .NET Framework 4.6 include una nuova funzionalità di sicurezza che blocca algoritmi di crittografia e hash non sicuri per le connessioni. Le applicazioni che usano TLS/SSL tramite API, ad esempio HttpClient, HttpWebRequest, FTPClient, SmtpClient, SslStream e così via, nonché la destinazione .NET Framework 4.6 ottengono il comportamento più sicuro per impostazione predefinita.

Gli sviluppatori potrebbero voler rifiutare esplicitamente questo comportamento per mantenere l'interoperabilità con i propri servizi SSL3 O i servizi TLS w/ RC4 esistenti. Questo articolo illustra come modificare il codice in modo che il nuovo comportamento sia disabilitato.

Il .NET Framework 4.7 aggiunge nuovi overload per i metodi che autenticano SslStreams che non specificano una versione TLS, ma usano invece la versione TLS definita come impostazione predefinita del sistema in SCHANNEL. Usare questi metodi nell'app come modo per poter modificare le impostazioni predefinite in seguito come modifiche consigliate per la versione TLS nel tempo, senza dover ricompilare e ridistribuire l'app.

Vedere Anche le procedure consigliate di Transport Layer Security (TLS) con il .NET Framework.

Costruttori

SslStream(Stream)

Inizializza una nuova istanza della classe SslStream usando il Stream specificato.

SslStream(Stream, Boolean)

Inizializza una nuova istanza della classe SslStream tramite l'oggetto Stream specificato e il comportamento di chiusura del flusso.

SslStream(Stream, Boolean, RemoteCertificateValidationCallback)

Inizializza una nuova istanza della classe SslStream tramite l'oggetto Stream specificato, il comportamento di chiusura del flusso e il delegato di convalida del certificato.

SslStream(Stream, Boolean, RemoteCertificateValidationCallback, LocalCertificateSelectionCallback)

Inizializza una nuova istanza della classe SslStream tramite l'oggetto Stream specificato, il comportamento di chiusura del flusso, il delegato di convalida del certificato e il delegato di selezione del certificato.

SslStream(Stream, Boolean, RemoteCertificateValidationCallback, LocalCertificateSelectionCallback, EncryptionPolicy)

Inizializza una nuova istanza della classe SslStream usando il Stream specificato.

Proprietà

CanRead

Ottiene un valore Booleanche indica se il flusso sottostante è leggibile.

CanSeek

Ottiene un valore Boolean che indica se il flusso sottostante consente le ricerche.

CanTimeout

Ottiene un valore Boolean che indica se il flusso sottostante supporta i timeout.

CanWrite

Ottiene un valore Boolean che indica se è possibile scrivere nel flusso sottostante.

CheckCertRevocationStatus

Ottiene un valore Boolean che indica se l'elenco certificati revocati viene verificato durante il processo di convalida del certificato.

CipherAlgorithm

Ottiene un valore che identifica l'algoritmo di crittografia di massa utilizzato dalla classe SslStream.

CipherStrength

Ottiene un valore che identifica il livello dell'algoritmo di crittografia utilizzato dalla classe SslStream.

HashAlgorithm

Ottiene l'algoritmo utilizzato per generare codici di autenticazione MAC (Message Authentication Code).

HashStrength

Ottiene un valore che identifica il livello dell'algoritmo di hash utilizzato da questa istanza.

InnerStream

Ottiene il flusso utilizzato dalla classe AuthenticatedStream per inviare e ricevere dati.

(Ereditato da AuthenticatedStream)
IsAuthenticated

Ottiene un valore Boolean che indica se l'autenticazione è stata effettuata con esito positivo.

IsEncrypted

Ottiene un valore Boolean che indica se la classe SslStream utilizza la crittografia dei dati.

IsMutuallyAuthenticated

Ottiene un valore Boolean che indica se il client e il server sono stati entrambi autenticati.

IsServer

Ottiene un valore Boolean che indica se il lato locale della connessione utilizzato da questa classe SslStream è stato autenticato come il server.

IsSigned

Ottiene un valore Boolean che indica se i dati inviati utilizzando questo flusso vengono firmati.

KeyExchangeAlgorithm

Ottiene l'algoritmo di scambio delle chiavi utilizzato dalla classe SslStream.

KeyExchangeStrength

Ottiene un valore che identifica il livello dell'algoritmo di scambio delle chiavi utilizzato da questa istanza.

LeaveInnerStreamOpen

Consente di sapere se il flusso utilizzato dalla classe AuthenticatedStream per inviare e ricevere dati è stato lasciato aperto.

(Ereditato da AuthenticatedStream)
Length

Ottiene la lunghezza del flusso sottostante.

LocalCertificate

Ottiene il certificato utilizzato per autenticare l'endpoint locale.

NegotiatedApplicationProtocol

Protocollo dell'applicazione negoziata nell'handshake TLS.

NegotiatedCipherSuite

Ottiene il pacchetto di crittografia negoziato per la connessione.

Position

Ottiene o imposta la posizione corrente nel flusso sottostante.

ReadTimeout

Ottiene o imposta l'intervallo di tempo, espresso in millisecondi, per il quale un'operazione di lettura si blocca in attesa dei dati.

RemoteCertificate

Ottiene il certificato utilizzato per autenticare l'endpoint remoto.

SslProtocol

Ottiene un valore che indica il certificato di sicurezza utilizzato per autenticare questa connessione.

TargetHostName

Ottiene il nome del server a cui il client sta tentando di connettersi. Tale nome viene usato per la convalida del certificato del server. Può essere un nome DNS o un indirizzo IP.

TransportContext

Ottiene l'oggetto TransportContext utilizzato per l'autenticazione tramite la protezione estesa.

WriteTimeout

Ottiene o imposta l'intervallo di tempo durante il quale un'operazione di scrittura si blocca in attesa dei dati.

Metodi

AuthenticateAsClient(SslClientAuthenticationOptions)

Chiamato dai client per autenticare il server e, facoltativamente, il client in una connessione client-server.

AuthenticateAsClient(String)

Chiamato dai client per autenticare il server e, facoltativamente, il client in una connessione client-server.

AuthenticateAsClient(String, X509CertificateCollection, Boolean)

Chiamato dai client per autenticare il server e, facoltativamente, il client in una connessione client-server. Il processo di autenticazione usa la raccolta di certificati specificata e il protocollo SSL predefinito di sistema.

AuthenticateAsClient(String, X509CertificateCollection, SslProtocols, Boolean)

Chiamato dai client per autenticare il server e, facoltativamente, il client in una connessione client-server. Nel processo di autenticazione vengono utilizzati l'insieme di certificati specificato e il protocollo SSL.

AuthenticateAsClientAsync(SslClientAuthenticationOptions, CancellationToken)

Chiamato dai client per autenticare il server e, facoltativamente, il client in una connessione client-server come operazione asincrona. Il processo di autenticazione usa le informazioni specificate nel contenitore delle proprietà sslClientAuthenticationOptions.

AuthenticateAsClientAsync(String)

Chiamato dai client per autenticare il server e, facoltativamente, il client in una connessione client-server come operazione asincrona.

AuthenticateAsClientAsync(String, X509CertificateCollection, Boolean)

Chiamato dai client per autenticare il server e, facoltativamente, il client in una connessione client-server come operazione asincrona. Il processo di autenticazione usa la raccolta di certificati specificata e il protocollo SSL predefinito di sistema.

AuthenticateAsClientAsync(String, X509CertificateCollection, SslProtocols, Boolean)

Chiamato dai client per autenticare il server e, facoltativamente, il client in una connessione client-server come operazione asincrona. Nel processo di autenticazione vengono utilizzati l'insieme di certificati specificato e il protocollo SSL.

AuthenticateAsServer(SslServerAuthenticationOptions)

Viene chiamato dai server per l'autenticazione del server e, facoltativamente, del client, in una connessione client-server che utilizza il certificato specificato.

AuthenticateAsServer(X509Certificate)

Viene chiamato dai server per l'autenticazione del server e, facoltativamente, del client, in una connessione client-server che utilizza il certificato specificato.

AuthenticateAsServer(X509Certificate, Boolean, Boolean)

Chiamato dai server per autenticare il server e, facoltativamente, il client in una connessione client-server usando i certificati e i requisiti specificati nonché il protocollo di sicurezza predefinito del sistema.

AuthenticateAsServer(X509Certificate, Boolean, SslProtocols, Boolean)

Chiamato dai server per autenticare il server ed eventualmente il client in una connessione client-server usando i certificati, i requisiti e il protocollo di sicurezza specificati.

AuthenticateAsServerAsync(ServerOptionsSelectionCallback, Object, CancellationToken)

Viene chiamato dai server per l'autenticazione del server e, facoltativamente, del client, in una connessione client-server come un'operazione asincrona. Il processo di autenticazione usa le informazioni restituite da optionsCallback.

AuthenticateAsServerAsync(SslServerAuthenticationOptions, CancellationToken)

Viene chiamato dai server per l'autenticazione del server e, facoltativamente, del client, in una connessione client-server come un'operazione asincrona. Il processo di autenticazione usa le informazioni specificate nel contenitore delle proprietà sslClientAuthenticationOptions.

AuthenticateAsServerAsync(X509Certificate)

Viene chiamato dai server per l'autenticazione del server e, facoltativamente, del client, in una connessione client-server che utilizza il certificato specificato come un'operazione asincrona.

AuthenticateAsServerAsync(X509Certificate, Boolean, Boolean)

Chiamato dai server per autenticare il server ed eventualmente il client in una connessione client-server usando i certificati specificati, i requisiti e il protocollo di sicurezza come operazione asincrona.

AuthenticateAsServerAsync(X509Certificate, Boolean, SslProtocols, Boolean)

Chiamato dai server per autenticare il server ed eventualmente il client in una connessione client-server usando i certificati specificati, i requisiti e il protocollo di sicurezza come operazione asincrona.

BeginAuthenticateAsClient(String, AsyncCallback, Object)

Viene chiamato dai client per avviare un'operazione asincrona di autenticazione del server e, facoltativamente, del client.

BeginAuthenticateAsClient(String, X509CertificateCollection, Boolean, AsyncCallback, Object)

Chiamato dai client per avviare un'operazione asincrona per autenticare il server e, facoltativamente, il client usando i certificati specificati e il protocollo di sicurezza predefinito del sistema.

BeginAuthenticateAsClient(String, X509CertificateCollection, SslProtocols, Boolean, AsyncCallback, Object)

Viene chiamato dai client per avviare un'operazione asincrona di autenticazione del server e, facoltativamente, del client, utilizzando i certificati e il protocollo di sicurezza specificati.

BeginAuthenticateAsServer(X509Certificate, AsyncCallback, Object)

Viene chiamato dai server per avviare un'operazione asincrona di autenticazione del client e, facoltativamente, del server, in una connessione client-server.

BeginAuthenticateAsServer(X509Certificate, Boolean, Boolean, AsyncCallback, Object)

Chiamato dai server per avviare un'operazione asincrona per autenticare il server e, facoltativamente, il client usando i certificati e i requisiti specificati nonché il protocollo di sicurezza predefinito del sistema.

BeginAuthenticateAsServer(X509Certificate, Boolean, SslProtocols, Boolean, AsyncCallback, Object)

Chiamato dai server per avviare un'operazione asincrona per autenticare il server ed eventualmente il client usando i certificati, i requisiti e il protocollo di sicurezza specificati.

BeginRead(Byte[], Int32, Int32, AsyncCallback, Object)

Avvia un'operazione di lettura asincrona dei dati del flusso, archiviandoli nella matrice specificata.

BeginRead(Byte[], Int32, Int32, AsyncCallback, Object)

Inizia un'operazione di lettura asincrona. Si consiglia di usare ReadAsync(Byte[], Int32, Int32).

(Ereditato da Stream)
BeginWrite(Byte[], Int32, Int32, AsyncCallback, Object)

Avvia un'operazione di scrittura asincrona che scrive i Byte dal buffer specificato nel flusso.

BeginWrite(Byte[], Int32, Int32, AsyncCallback, Object)

Inizia un'operazione di scrittura asincrona. Si consiglia di usare WriteAsync(Byte[], Int32, Int32).

(Ereditato da Stream)
Close()

Chiude il flusso corrente e libera le risorse, come socket e handle di file, ad esso associate. Anziché chiamare questo metodo, assicurarsi che il flusso sia eliminato correttamente.

(Ereditato da Stream)
CopyTo(Stream)

Legge i byte dal flusso corrente e li scrive in un altro flusso.

(Ereditato da Stream)
CopyTo(Stream, Int32)

Legge tutti i byte dal flusso corrente e li scrive in un altro flusso, usando una dimensione di buffer specificata.

(Ereditato da Stream)
CopyToAsync(Stream)

Legge in modo asincrono i byte dal flusso corrente e li scrive in un altro flusso.

(Ereditato da Stream)
CopyToAsync(Stream, CancellationToken)

Legge in modo asincrono i byte dal flusso corrente e li scrive in un altro flusso, usando un token di annullamento specificato.

(Ereditato da Stream)
CopyToAsync(Stream, Int32)

Legge in modo asincrono tutti i byte dal flusso corrente e li scrive in un altro flusso, utilizzando una dimensione di buffer specificata.

(Ereditato da Stream)
CopyToAsync(Stream, Int32, CancellationToken)

Legge in modo asincrono i byte dal flusso corrente e li scrive in un altro flusso, usando una dimensione di buffer specificata e un token di annullamento.

(Ereditato da Stream)
CreateObjRef(Type)

Consente di creare un oggetto che contiene tutte le informazioni rilevanti necessarie per la generazione del proxy utilizzato per effettuare la comunicazione con un oggetto remoto.

(Ereditato da MarshalByRefObject)
CreateWaitHandle()
Obsoleta.
Obsoleta.

Alloca un oggetto WaitHandle.

(Ereditato da Stream)
Dispose()

Rilascia tutte le risorse usate da Stream.

(Ereditato da Stream)
Dispose(Boolean)

Rilascia le risorse non gestite usate da SslStream e, facoltativamente, le risorse gestite.

Dispose(Boolean)

Rilascia le risorse non gestite usate da AuthenticatedStream e, facoltativamente, le risorse gestite.

(Ereditato da AuthenticatedStream)
DisposeAsync()

Consente di liberare in modo asincrono le risorse non gestite e gestite usate da SslStream.

DisposeAsync()

Consente di liberare in modo asincrono le risorse non gestite e gestite usate da AuthenticatedStream.

(Ereditato da AuthenticatedStream)
EndAuthenticateAsClient(IAsyncResult)

Termina un'operazione di autenticazione server asincrona in sospeso avviata con una precedente chiamata del metodo BeginAuthenticateAsClient.

EndAuthenticateAsServer(IAsyncResult)

Termina un'operazione di autenticazione client asincrona in sospeso avviata con una precedente chiamata del metodo BeginAuthenticateAsClient.

EndRead(IAsyncResult)

Termina un'operazione di lettura asincrona avviata con una precedente chiamata del metodo BeginRead(Byte[], Int32, Int32, AsyncCallback, Object).

EndRead(IAsyncResult)

Attende il completamento della lettura asincrona in sospeso. Si consiglia di usare ReadAsync(Byte[], Int32, Int32).

(Ereditato da Stream)
EndWrite(IAsyncResult)

Termina un'operazione di scrittura asincrona avviata con una precedente chiamata del metodo BeginWrite(Byte[], Int32, Int32, AsyncCallback, Object).

EndWrite(IAsyncResult)

Termina un'operazione di scrittura asincrona. Si consiglia di usare WriteAsync(Byte[], Int32, Int32).

(Ereditato da Stream)
Equals(Object)

Determina se l'oggetto specificato è uguale all'oggetto corrente.

(Ereditato da Object)
Finalize()

Rilascia tutte le risorse usate da SslStream.

Flush()

Consente la scrittura dei dati memorizzati nel buffer nel dispositivo sottostante.

FlushAsync()

Cancella in modo asincrono i dati di tutti i buffer del flusso e determina la scrittura dei dati memorizzati nel buffer nel dispositivo sottostante.

(Ereditato da Stream)
FlushAsync(CancellationToken)

Scrive in modo asincrono i dati memorizzati nel buffer nel dispositivo sottostante.

FlushAsync(CancellationToken)

Cancella in modo asincrono i dati di tutti i buffer del flusso, determina la scrittura dei dati memorizzati nel buffer nel dispositivo sottostante e monitora le richieste di annullamento.

(Ereditato da Stream)
GetHashCode()

Funge da funzione hash predefinita.

(Ereditato da Object)
GetLifetimeService()
Obsoleta.

Consente di recuperare l'oggetto servizio di durata corrente per controllare i criteri di durata per l'istanza.

(Ereditato da MarshalByRefObject)
GetType()

Ottiene l'oggetto Type dell'istanza corrente.

(Ereditato da Object)
InitializeLifetimeService()
Obsoleta.

Ottiene un oggetto servizio di durata per controllare i criteri di durata per questa istanza.

(Ereditato da MarshalByRefObject)
MemberwiseClone()

Crea una copia superficiale dell'oggetto Object corrente.

(Ereditato da Object)
MemberwiseClone(Boolean)

Crea una copia dei riferimenti dell'oggetto MarshalByRefObject corrente.

(Ereditato da MarshalByRefObject)
NegotiateClientCertificateAsync(CancellationToken)

Negozia il certificato client nella connessione autenticata.

ObjectInvariant()
Obsoleta.

Fornisce supporto per un oggetto Contract.

(Ereditato da Stream)
Read(Byte[], Int32, Int32)

Legge i dati da questo flusso e li archivia nella matrice specificata.

Read(Span<Byte>)

Quando ne viene eseguito l'override in una classe derivata, legge una sequenza di byte dal flusso corrente e passa alla posizione successiva all'interno del flusso corrente in base al numero di byte letti.

(Ereditato da Stream)
ReadAsync(Byte[], Int32, Int32)

Legge in modo asincrono una sequenza di byte dal flusso corrente e passa alla posizione successiva nel flusso in base al numero di byte letti.

(Ereditato da Stream)
ReadAsync(Byte[], Int32, Int32, CancellationToken)

Legge in modo asincrono i dati da questo flusso e li archivia nell'intervallo specificato di una matrice di byte.

ReadAsync(Byte[], Int32, Int32, CancellationToken)

Legge in modo asincrono una sequenza di byte dal flusso corrente e passa alla posizione successiva all'interno del flusso corrente in base al numero di byte letti e monitora le richieste di annullamento.

(Ereditato da Stream)
ReadAsync(Memory<Byte>, CancellationToken)

Legge in modo asincrono i dati da questo flusso e li archivia nell'intervallo di memoria specificato.

ReadAsync(Memory<Byte>, CancellationToken)

Legge in modo asincrono una sequenza di byte dal flusso corrente e passa alla posizione successiva all'interno del flusso corrente in base al numero di byte letti e monitora le richieste di annullamento.

(Ereditato da Stream)
ReadByte()

Legge un byte da SslStream e sposta in avanti la posizione corrente all'interno del flusso di un byte o restituisce -1 se si trova alla fine del flusso.

ReadByte()

Legge un byte dal flusso e sposta in avanti la posizione corrente all'interno del flusso di un byte o restituisce -1 se si trova alla fine del flusso.

(Ereditato da Stream)
Seek(Int64, SeekOrigin)

Genera un oggetto NotSupportedException.

SetLength(Int64)

Imposta la lunghezza del flusso sottostante.

ShutdownAsync()

Arresta questo oggetto SslStream.

ToString()

Restituisce una stringa che rappresenta l'oggetto corrente.

(Ereditato da Object)
Write(Byte[])

Scrive i dati specificati in questo flusso.

Write(Byte[], Int32, Int32)

Consente di scrivere il numero specificato di Byte nel flusso sottostante, utilizzando il buffer e l'offset specificati.

Write(ReadOnlySpan<Byte>)

Quando ne viene eseguito l'override in una classe derivata, scrive una sequenza di byte nel flusso corrente e passa alla posizione successiva all'interno del flusso corrente in base al numero di byte scritti.

(Ereditato da Stream)
WriteAsync(Byte[], Int32, Int32)

Scrive in modo asincrono una sequenza di byte nel flusso corrente e passa alla posizione successiva nel flusso in base al numero di byte scritti.

(Ereditato da Stream)
WriteAsync(Byte[], Int32, Int32, CancellationToken)

Scrive in modo asincrono i dati nel flusso sottostante dall'intervallo specificato di una matrice di byte.

WriteAsync(Byte[], Int32, Int32, CancellationToken)

Scrive in modo asincrono una sequenza di byte nel flusso corrente e passa alla posizione successiva all'interno del flusso corrente in base al numero di byte scritti e monitora le richieste di annullamento.

(Ereditato da Stream)
WriteAsync(ReadOnlyMemory<Byte>, CancellationToken)

Scrive in modo asincrono i dati nel flusso sottostante da un intervallo di memoria di byte di sola lettura.

WriteAsync(ReadOnlyMemory<Byte>, CancellationToken)

Scrive in modo asincrono una sequenza di byte nel flusso corrente e passa alla posizione successiva all'interno del flusso corrente in base al numero di byte scritti e monitora le richieste di annullamento.

(Ereditato da Stream)
WriteByte(Byte)

Scrive un byte nella posizione corrente del flusso e sposta in avanti di un byte la posizione del flusso.

(Ereditato da Stream)

Metodi di estensione

ConfigureAwait(IAsyncDisposable, Boolean)

Consente di configurare la modalità di esecuzione delle espressioni await per le attività restituite da un elemento disposable asincrono.

Si applica a

Vedi anche