SslStream Classe

Definição

Fornece um fluxo usado para comunicação cliente-servidor que usa o protocolo de segurança SSL (Secure Socket Layer) para autenticar o servidor e, opcionalmente, o cliente.

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
Herança
Herança
Implementações

Exemplos

O exemplo de código a seguir demonstra a criação de um TcpListener que usa a SslStream classe para se comunicar com os clientes.

#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

O exemplo de código a seguir demonstra a criação de um TcpClient que usa a SslStream classe para se comunicar com um servidor.

#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

Comentários

Os protocolos SSL ajudam a fornecer confidencialidade e verificação de integridade para mensagens transmitidas usando um SslStream. Uma conexão SSL, como a fornecida por SslStream, deve ser usada ao comunicar informações confidenciais entre um cliente e um servidor. O uso de uma SslStream ajuda a impedir que qualquer pessoa leia e tampe informações enquanto estiver em trânsito na rede.

Uma SslStream instância transmite dados usando um fluxo que você fornece ao criar o SslStream. Ao fornecer esse fluxo subjacente, você tem a opção de especificar se o SslStream fechamento também fecha o fluxo subjacente. Normalmente, a SslStream classe é usada com as classes e TcpListener as TcpClient classes. O GetStream método fornece um NetworkStream uso adequado com a SslStream classe.

Depois de criar um SslStreamservidor e, opcionalmente, o cliente deve ser autenticado. O servidor deve fornecer um certificado X509 que estabelece a prova de sua identidade e pode solicitar que o cliente também o faça. A autenticação deve ser executada antes de transmitir informações usando um SslStream. Os clientes iniciam a autenticação usando os métodos AuthenticateAsClient síncronos, que bloqueiam até que a autenticação seja concluída ou os métodos assíncronos BeginAuthenticateAsClient , que não bloqueiam a espera da conclusão da autenticação. Os servidores iniciam a autenticação usando os métodos AuthenticateAsServer síncronos ou assíncronos BeginAuthenticateAsServer . O cliente e o servidor devem iniciar a autenticação.

A autenticação é tratada pelo provedor de canal SSPI (Provedor de Suporte à Segurança). O cliente tem a oportunidade de controlar a validação do certificado do servidor especificando um RemoteCertificateValidationCallback delegado ao criar um SslStream. O servidor também pode controlar a validação fornecendo um RemoteCertificateValidationCallback delegado. O método referenciado pelo delegado inclui o certificado da parte remota e quaisquer erros que a SSPI encontrou ao validar o certificado. Observe que, se o servidor especificar um delegado, o método do delegado será invocado independentemente de a autenticação do cliente solicitada pelo servidor. Se o servidor não solicitou a autenticação do cliente, o método delegado do servidor receberá um certificado nulo e uma matriz vazia de erros de certificado.

Se o servidor exigir a autenticação do cliente, o cliente deverá especificar um ou mais certificados para autenticação. Se o cliente tiver mais de um certificado, o cliente poderá fornecer um LocalCertificateSelectionCallback delegado para selecionar o certificado correto para o servidor. Os certificados do cliente devem estar localizados no repositório de certificados "Meu" do usuário atual. A autenticação do cliente por meio de certificados não tem suporte para o Ssl2 protocolo (SSL versão 2).

Se a autenticação falhar, você receberá um AuthenticationExceptione o SslStream não poderá mais ser usado. Você deve fechar esse objeto e remover todas as referências a ele para que ele possa ser coletado pelo coletor de lixo.

Quando o processo de autenticação, também conhecido como handshake SSL, é bem-sucedido, a identidade do servidor (e, opcionalmente, o cliente) é estabelecida e pode SslStream ser usada pelo cliente e pelo servidor para trocar mensagens. Antes de enviar ou receber informações, o cliente e o servidor devem verificar os serviços de segurança e os SslStream níveis fornecidos pelo para determinar se o protocolo, os algoritmos e os pontos fortes selecionados atendem aos requisitos de integridade e confidencialidade. Se as configurações atuais não forem suficientes, o fluxo deverá ser fechado. Você pode verificar os serviços de segurança fornecidos pelo SslStream uso das propriedades e IsSigned do IsEncrypted uso. A tabela a seguir mostra os elementos que relatam as configurações criptográficas usadas para autenticação, criptografia e assinatura de dados.

Elemento Membros
O protocolo de segurança usado para autenticar o servidor e, opcionalmente, o cliente. A SslProtocol propriedade e a enumeração associada SslProtocols .
O algoritmo de troca de chaves. A KeyExchangeAlgorithm propriedade e a enumeração associada ExchangeAlgorithmType .
O algoritmo de integridade da mensagem. A HashAlgorithm propriedade e a enumeração associada HashAlgorithmType .
O algoritmo de confidencialidade da mensagem. A CipherAlgorithm propriedade e a enumeração associada CipherAlgorithmType .
Os pontos fortes dos algoritmos selecionados. O KeyExchangeStrength, HashStrengthe CipherStrength as propriedades.

Após uma autenticação bem-sucedida, você pode enviar dados usando os métodos Write síncronos ou assíncronos BeginWrite . Você pode receber dados usando os métodos Read síncronos ou assíncronos BeginRead .

Se você especificou que o SslStream fluxo subjacente deve ser deixado aberto, você será responsável por fechar esse fluxo quando terminar de usá-lo.

Observação

Se o aplicativo que cria o SslStream objeto for executado com as credenciais de um usuário Normal, o aplicativo não poderá acessar certificados instalados no repositório de máquinas local, a menos que a permissão tenha sido explicitamente dada ao usuário para fazer isso.

SslStream pressupõe que um tempo limite junto com qualquer outro IOException quando um for lançado do fluxo interno será tratado como fatal por seu chamador. Reutilização de uma SslStream instância após um tempo limite retornará o lixo. Um aplicativo deve Close e SslStream gerar uma exceção nesses casos.

O .NET Framework 4.6 inclui um novo recurso de segurança que bloqueia algoritmos de codificação e hash inseguros para conexões. Os aplicativos que usam TLS/SSL por meio de APIs como HttpClient, HttpWebRequest, FTPClient, SmtpClient, SslStream etc. e direcionamento .NET Framework 4.6 obtêm o comportamento mais seguro por padrão.

Os desenvolvedores podem querer recusar esse comportamento para manter a interoperabilidade com seus serviços SSL3 ou TLS w/ RC4 existentes. Este artigo explica como modificar seu código para que o novo comportamento seja desabilitado.

O .NET Framework 4.7 adiciona novas sobrecargas para os métodos que autenticam o SslStreams que não especificam uma versão TLS, mas usam a versão TLS definida como o padrão do sistema no SCHANNEL. Use esses métodos em seu aplicativo como uma maneira de modificar os padrões posteriormente, pois as melhores práticas de versão do TLS mudam ao longo do tempo, sem a necessidade de recompilar e reimplantar seu aplicativo.

Consulte também as práticas recomendadas de TLS (Transport Layer Security) com o .NET Framework.

Construtores

SslStream(Stream)

Inicializa uma nova instância da classe SslStream usando o Stream especificado.

SslStream(Stream, Boolean)

Inicializa uma nova instância da classe SslStream usando o Stream e o comportamento de fechamento de fluxo especificados.

SslStream(Stream, Boolean, RemoteCertificateValidationCallback)

Inicializa uma nova instância da classe SslStream usando o Stream especificado, o comportamento de fechamento de fluxo e o delegado de validação de certificado.

SslStream(Stream, Boolean, RemoteCertificateValidationCallback, LocalCertificateSelectionCallback)

Inicializa uma nova instância da classe SslStream usando o Stream especificado, o comportamento de fechamento de fluxo, o delegado de validação de certificado e o delegado de seleção de certificado.

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

Inicializa uma nova instância da classe SslStream usando o Stream especificado.

Propriedades

CanRead

Obtém um valor Boolean que indica se o fluxo subjacente é legível.

CanSeek

Obtém um valor Boolean que indica se o fluxo subjacente é pesquisável.

CanTimeout

Obtém um valor Boolean que indica se o fluxo subjacente dá suporte a tempos limite.

CanWrite

Obtém um valor Boolean que indica se o fluxo subjacente é gravável.

CheckCertRevocationStatus

Obtém um valor Boolean que indica se a lista de certificados revogados é verificada durante o processo de validação de certificado.

CipherAlgorithm

Obtém um valor que identifica o algoritmo de criptografia em massa usado por este SslStream.

CipherStrength

Obtém um valor que identifica a força do algoritmo de criptografia usado por esse SslStream.

HashAlgorithm

Obtém o algoritmo usado para gerar MACs (Message Authentication Codes).

HashStrength

Obtém um valor que identifica a força do algoritmo de hash usado por essa instância.

InnerStream

Obtém o fluxo usado por este AuthenticatedStream para envio e recebimento de dados.

(Herdado de AuthenticatedStream)
IsAuthenticated

Obtém um valor Boolean que indica se a autenticação foi bem-sucedida.

IsEncrypted

Obtém um valor Boolean que indica se esse SslStream usa criptografia de dados.

IsMutuallyAuthenticated

Obtém um valor Boolean que indica se o servidor e o cliente foram autenticados.

IsServer

Obtém um valor Boolean que indica se o lado local da conexão usada por esse SslStream foi autenticado como o servidor.

IsSigned

Obtém um valor Boolean que indica se os dados enviados usando esse fluxo são assinados.

KeyExchangeAlgorithm

Obtém o algoritmo de troca de chaves usado por este SslStream.

KeyExchangeStrength

Obtém um valor que identifica a força do algoritmo de troca de chaves usado por essa instância.

LeaveInnerStreamOpen

Obtém a indicação de se o fluxo usado por este AuthenticatedStream para envio e recebimento de dados foi deixado aberto.

(Herdado de AuthenticatedStream)
Length

Obtém o comprimento do fluxo subjacente.

LocalCertificate

Obtém o certificado usado para autenticar o ponto de extremidade local.

NegotiatedApplicationProtocol

O protocolo de aplicativo negociado no handshake do TLS.

NegotiatedCipherSuite

Obtém o conjunto de criptografias que foi negociado para esta conexão.

Position

Obtém ou define a posição atual no fluxo subjacente.

ReadTimeout

Obtém ou define a quantidade de tempo, expressa em milissegundos, que uma operação de leitura é bloqueada aguardando dados.

RemoteCertificate

Obtém o certificado usado para autenticar o ponto de extremidade remoto.

SslProtocol

Obtém um valor que indica o protocolo de segurança usado para autenticar esta conexão.

TargetHostName

Obtém o nome do servidor ao qual o cliente está tentando se conectar. Esse nome é usado para validação do certificado do servidor. Ele pode ser um nome DNS ou um endereço IP.

TransportContext

Obtém o TransportContext usado para autenticação utilizando a proteção estendida.

WriteTimeout

Obtém ou define a quantidade de tempo pela qual uma operação de gravação fica bloqueada aguardando dados.

Métodos

AuthenticateAsClient(SslClientAuthenticationOptions)

Chamado por clientes para autenticar o servidor e, como opção, o cliente em uma conexão de cliente-servidor.

AuthenticateAsClient(String)

Chamado por clientes para autenticar o servidor e, como opção, o cliente em uma conexão de cliente-servidor.

AuthenticateAsClient(String, X509CertificateCollection, Boolean)

Chamado por clientes para autenticar o servidor e, como opção, o cliente em uma conexão de cliente-servidor. O processo de autenticação usa o protocolo SSL padrão do sistema e a coleção de certificado especificados.

AuthenticateAsClient(String, X509CertificateCollection, SslProtocols, Boolean)

Chamado por clientes para autenticar o servidor e, como opção, o cliente em uma conexão de cliente-servidor. O processo de autenticação usa o protocolo SSL e coleção de certificado especificados.

AuthenticateAsClientAsync(SslClientAuthenticationOptions, CancellationToken)

Chamado por clientes para autenticar o servidor e, como opção, o cliente em uma conexão de cliente-servidor como uma operação assíncrona. O processo de autenticação usa as informações especificadas no recipiente de propriedades sslClientAuthenticationOptions.

AuthenticateAsClientAsync(String)

Chamado por clientes para autenticar o servidor e, como opção, o cliente em uma conexão de cliente-servidor como uma operação assíncrona.

AuthenticateAsClientAsync(String, X509CertificateCollection, Boolean)

Chamado por clientes para autenticar o servidor e, como opção, o cliente em uma conexão de cliente-servidor como uma operação assíncrona. O processo de autenticação usa o protocolo SSL padrão do sistema e a coleção de certificado especificados.

AuthenticateAsClientAsync(String, X509CertificateCollection, SslProtocols, Boolean)

Chamado por clientes para autenticar o servidor e, como opção, o cliente em uma conexão de cliente-servidor como uma operação assíncrona. O processo de autenticação usa o protocolo SSL e coleção de certificado especificados.

AuthenticateAsServer(SslServerAuthenticationOptions)

Chamada pelos servidores para autenticar o servidor e, opcionalmente, o cliente em uma conexão cliente-servidor usando o certificado especificado.

AuthenticateAsServer(X509Certificate)

Chamada pelos servidores para autenticar o servidor e, opcionalmente, o cliente em uma conexão cliente-servidor usando o certificado especificado.

AuthenticateAsServer(X509Certificate, Boolean, Boolean)

Chamado pelos servidores para autenticar o servidor e, opcionalmente, o cliente em uma conexão cliente-servidor usando os certificados e requisitos especificados e o protocolo de segurança padrão.

AuthenticateAsServer(X509Certificate, Boolean, SslProtocols, Boolean)

Chamado pelos servidores para autenticar o servidor e, opcionalmente, o cliente em uma conexão cliente-servidor usando os certificados especificados, requisitos e o protocolo de segurança.

AuthenticateAsServerAsync(ServerOptionsSelectionCallback, Object, CancellationToken)

Chamado por servidores para autenticar o servidor e, opcionalmente, o cliente em uma conexão cliente-servidor como uma operação assíncrona. O processo de autenticação usa informações retornadas por optionsCallback.

AuthenticateAsServerAsync(SslServerAuthenticationOptions, CancellationToken)

Chamado por servidores para autenticar o servidor e, opcionalmente, o cliente em uma conexão cliente-servidor como uma operação assíncrona. O processo de autenticação usa as informações especificadas no recipiente de propriedades sslClientAuthenticationOptions.

AuthenticateAsServerAsync(X509Certificate)

Chamado pelos servidores para autenticar o servidor e, opcionalmente, o cliente em uma conexão cliente-servidor usando o certificado especificado como uma operação assíncrona.

AuthenticateAsServerAsync(X509Certificate, Boolean, Boolean)

Chamado pelos servidores para autenticar o servidor e, opcionalmente, o cliente em uma conexão cliente-servidor usando os certificados especificados, requisitos e o protocolo de segurança como uma operação síncrona.

AuthenticateAsServerAsync(X509Certificate, Boolean, SslProtocols, Boolean)

Chamado pelos servidores para autenticar o servidor e, opcionalmente, o cliente em uma conexão cliente-servidor usando os certificados especificados, requisitos e o protocolo de segurança como uma operação síncrona.

BeginAuthenticateAsClient(String, AsyncCallback, Object)

Chamado por clientes para iniciar uma operação assíncrona para autenticar o servidor e, opcionalmente, o cliente.

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

Chamado por clientes para iniciar uma operação assíncrona para autenticar o servidor e, opcionalmente, o cliente usando os certificados especificados e o protocolo de segurança do sistema padrão.

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

Chamado por clientes para iniciar uma operação assíncrona para autenticar o servidor e, opcionalmente, o cliente usando o protocolo de segurança e certificados especificados.

BeginAuthenticateAsServer(X509Certificate, AsyncCallback, Object)

Chamado por servidores para iniciar uma operação assíncrona para autenticar o cliente e, opcionalmente, o servidor em uma conexão cliente-servidor.

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

Chamado por servidores para iniciar uma operação assíncrona para autenticar o servidor e, opcionalmente, o cliente usando os certificados e requisitos especificados, e o protocolo de segurança do sistema padrão.

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

Chamado por servidores para iniciar uma operação assíncrona para autenticar o servidor e, opcionalmente, o cliente usando os certificados, requisitos e protocolo de segurança especificados.

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

Inicia uma operação de leitura assíncrona que lê os dados do fluxo e os armazena na matriz especificada.

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

Inicia uma operação de leitura assíncrona. (Considere o uso de ReadAsync(Byte[], Int32, Int32) em seu lugar.)

(Herdado de Stream)
BeginWrite(Byte[], Int32, Int32, AsyncCallback, Object)

Inicia uma operação de gravação assíncrona que grava Bytes do buffer especificado no fluxo.

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

Inicia uma operação de gravação assíncrona. (Considere o uso de WriteAsync(Byte[], Int32, Int32) em seu lugar.)

(Herdado de Stream)
Close()

Fecha o fluxo atual e libera todos os recursos (como soquetes e identificadores de arquivos) associados ao fluxo atual. Em vez de chamar esse método, verifique se o fluxo é descartado corretamente.

(Herdado de Stream)
CopyTo(Stream)

Lê os bytes do fluxo atual e os grava em outro fluxo.

(Herdado de Stream)
CopyTo(Stream, Int32)

Lê os bytes do fluxo atual e os grava em outro fluxo usando um tamanho do buffer especificado.

(Herdado de Stream)
CopyToAsync(Stream)

Lê de forma assíncrona os bytes do fluxo atual e os grava em outro fluxo.

(Herdado de Stream)
CopyToAsync(Stream, CancellationToken)

Lê de forma assíncrona os bytes do fluxo atual e os grava em outro fluxo usando um token de cancelamento especificado.

(Herdado de Stream)
CopyToAsync(Stream, Int32)

Lê de maneira assíncrona os bytes do fluxo atual e os grava em outro fluxo usando um tamanho do buffer especificado.

(Herdado de Stream)
CopyToAsync(Stream, Int32, CancellationToken)

Lê de forma assíncrona os bytes do fluxo atual e os grava em outro fluxo usando um tamanho do buffer especificado e um token de cancelamento.

(Herdado de Stream)
CreateObjRef(Type)

Cria um objeto que contém todas as informações relevantes necessárias para gerar um proxy usado para se comunicar com um objeto remoto.

(Herdado de MarshalByRefObject)
CreateWaitHandle()
Obsoleto.
Obsoleto.

Aloca um objeto WaitHandle.

(Herdado de Stream)
Dispose()

Libera todos os recursos usados pelo Stream.

(Herdado de Stream)
Dispose(Boolean)

Libera os recursos não gerenciados usados pelo SslStream e opcionalmente libera os recursos gerenciados.

Dispose(Boolean)

Libera os recursos não gerenciados usados pelo AuthenticatedStream e opcionalmente libera os recursos gerenciados.

(Herdado de AuthenticatedStream)
DisposeAsync()

Libera de forma assíncrona os recursos gerenciados e não gerenciados usados pelo SslStream.

DisposeAsync()

Libera de forma assíncrona os recursos gerenciados e não gerenciados usados pelo AuthenticatedStream.

(Herdado de AuthenticatedStream)
EndAuthenticateAsClient(IAsyncResult)

Encerra uma operação assíncrona de autenticação de servidor pendente iniciada com uma chamada anterior para BeginAuthenticateAsClient.

EndAuthenticateAsServer(IAsyncResult)

Encerra uma operação assíncrona de autenticação de cliente pendente iniciada com uma chamada anterior para BeginAuthenticateAsClient.

EndRead(IAsyncResult)

Encerra uma operação de leitura assíncrona iniciada em uma chamada anterior a BeginRead(Byte[], Int32, Int32, AsyncCallback, Object).

EndRead(IAsyncResult)

Espera a leitura assíncrona pendente ser concluída. (Considere o uso de ReadAsync(Byte[], Int32, Int32) em seu lugar.)

(Herdado de Stream)
EndWrite(IAsyncResult)

Encerra uma operação de gravação assíncrona iniciada em uma chamada anterior a BeginWrite(Byte[], Int32, Int32, AsyncCallback, Object).

EndWrite(IAsyncResult)

Encerra uma operação de gravação assíncrona. (Considere o uso de WriteAsync(Byte[], Int32, Int32) em seu lugar.)

(Herdado de Stream)
Equals(Object)

Determina se o objeto especificado é igual ao objeto atual.

(Herdado de Object)
Finalize()

Libera todos os recursos usados pelo SslStream.

Flush()

Faz com que os dados armazenados em buffer sejam gravados no dispositivo subjacente.

FlushAsync()

Limpa de forma assíncrona todos os buffers nesse fluxo e faz com que os dados armazenados em buffer sejam gravados no dispositivo subjacente.

(Herdado de Stream)
FlushAsync(CancellationToken)

Grava de modo assíncrono todos os dados armazenados em buffer no dispositivo subjacente.

FlushAsync(CancellationToken)

Limpa todos os buffers nesse fluxo de forma assíncrona, faz com que os dados armazenados em buffer sejam gravados no dispositivo subjacente e monitora as solicitações de cancelamento.

(Herdado de Stream)
GetHashCode()

Serve como a função de hash padrão.

(Herdado de Object)
GetLifetimeService()
Obsoleto.

Recupera o objeto de serviço de tempo de vida atual que controla a política de ciclo de vida para esta instância.

(Herdado de MarshalByRefObject)
GetType()

Obtém o Type da instância atual.

(Herdado de Object)
InitializeLifetimeService()
Obsoleto.

Obtém um objeto de serviço de tempo de vida para controlar a política de tempo de vida para essa instância.

(Herdado de MarshalByRefObject)
MemberwiseClone()

Cria uma cópia superficial do Object atual.

(Herdado de Object)
MemberwiseClone(Boolean)

Cria uma cópia superficial do objeto MarshalByRefObject atual.

(Herdado de MarshalByRefObject)
NegotiateClientCertificateAsync(CancellationToken)

Negocia o certificado do cliente na conexão autenticada.

ObjectInvariant()
Obsoleto.

Oferece suporte a um Contract.

(Herdado de Stream)
Read(Byte[], Int32, Int32)

Lê os dados desse fluxo e o armazena na matriz especificada.

Read(Span<Byte>)

Quando for substituído em uma classe derivada, lê uma sequência de bytes do fluxo atual e avança a posição dentro do fluxo até o número de bytes lidos.

(Herdado de Stream)
ReadAsync(Byte[], Int32, Int32)

Lê uma sequência de bytes do fluxo atual de forma assíncrona e avança a posição no fluxo até o número de bytes lidos.

(Herdado de Stream)
ReadAsync(Byte[], Int32, Int32, CancellationToken)

Lê de forma assíncrona os dados desse fluxo e armazena-os no intervalo especificado de uma matriz de bytes.

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

Lê de forma assíncrona uma sequência de bytes do fluxo atual, avança a posição no fluxo até o número de bytes lidos e monitora as solicitações de cancelamento.

(Herdado de Stream)
ReadAsync(Memory<Byte>, CancellationToken)

Lê de forma assíncrona os dados desse fluxo e armazena-os no intervalo de memória especificado.

ReadAsync(Memory<Byte>, CancellationToken)

Lê de forma assíncrona uma sequência de bytes do fluxo atual, avança a posição no fluxo até o número de bytes lidos e monitora as solicitações de cancelamento.

(Herdado de Stream)
ReadByte()

Lê um byte do SslStream e avança a posição no fluxo em um byte ou retorna -1 caso esteja no final do fluxo.

ReadByte()

Lê um byte do fluxo e avança a posição no fluxo em um byte ou retorna -1 caso esteja no final do fluxo.

(Herdado de Stream)
Seek(Int64, SeekOrigin)

Gera uma NotSupportedException.

SetLength(Int64)

Define o comprimento do fluxo subjacente.

ShutdownAsync()

Desliga este SslStream.

ToString()

Retorna uma cadeia de caracteres que representa o objeto atual.

(Herdado de Object)
Write(Byte[])

Grava os dados especificados nesse fluxo.

Write(Byte[], Int32, Int32)

Grave o número especificado de Bytes no fluxo subjacente usando o buffer e o deslocamento especificados.

Write(ReadOnlySpan<Byte>)

Quando for substituído em uma classe derivada, grava uma sequência de bytes no fluxo atual e avança a posição atual dentro desse fluxo até o número de bytes gravados.

(Herdado de Stream)
WriteAsync(Byte[], Int32, Int32)

Grava assincronamente uma sequência de bytes no fluxo atual e avança a posição atual dentro desse fluxo no número de bytes gravados.

(Herdado de Stream)
WriteAsync(Byte[], Int32, Int32, CancellationToken)

Grava de forma assíncrona os dados compactados no fluxo subjacente do intervalo especificado de uma matriz de bytes.

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

Grava uma sequência de bytes no fluxo atual assincronamente, avança a posição atual dentro desse fluxo pelo número de bytes gravados e monitora as solicitações de cancelamento.

(Herdado de Stream)
WriteAsync(ReadOnlyMemory<Byte>, CancellationToken)

Grava de forma assíncrona os dados no fluxo subjacente de um intervalo de memória de bytes somente leitura.

WriteAsync(ReadOnlyMemory<Byte>, CancellationToken)

Grava uma sequência de bytes no fluxo atual assincronamente, avança a posição atual dentro desse fluxo pelo número de bytes gravados e monitora as solicitações de cancelamento.

(Herdado de Stream)
WriteByte(Byte)

Grava um byte na posição atual no fluxo e avança a posição dentro no fluxo em um byte.

(Herdado de Stream)

Métodos de Extensão

ConfigureAwait(IAsyncDisposable, Boolean)

Configura como as esperas nas tarefas retornadas de um descartável assíncrono são realizadas.

Aplica-se a

Confira também