Compartir a través de


SslStream Clase

Definición

Proporciona una secuencia que se usa para la comunicación de cliente-servidor que usa el protocolo de seguridad capa de sockets seguros (SSL) para autenticar el servidor y, opcionalmente, el cliente.

public ref class SslStream : System::Net::Security::AuthenticatedStream
public class SslStream : System.Net.Security.AuthenticatedStream
type SslStream = class
    inherit AuthenticatedStream
Public Class SslStream
Inherits AuthenticatedStream
Herencia
Herencia

Ejemplos

En el ejemplo de código siguiente se muestra cómo crear un TcpListener que usa la clase SslStream para comunicarse con los 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,5000 );
      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 );
      Console::WriteLine( L"Is mutually authenticated: {0}", stream->IsMutuallyAuthenticated );
   }


   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, 5000);
            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);
            Console.WriteLine("Is mutually authenticated: {0}", stream.IsMutuallyAuthenticated);
         }
         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, 5000)
            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)
            Console.WriteLine("Is mutually authenticated: {0}", stream.IsMutuallyAuthenticated)
        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

En el ejemplo de código siguiente se muestra cómo crear un TcpClient que usa la clase SslStream para comunicarse con un 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, 5000);
            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,5000);
            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, 5000)
            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

Comentarios

Los protocolos SSL ayudan a proporcionar confidencialidad e integridad para comprobar los mensajes transmitidos mediante un SslStream. Se debe usar una conexión SSL, como la proporcionada por SslStream, al comunicar información confidencial entre un cliente y un servidor. El uso de una SslStream ayuda a evitar que cualquier usuario lea y manipule la información mientras está en tránsito en la red.

Una instancia de SslStream transmite datos mediante una secuencia que se proporciona al crear el SslStream. Al proporcionar esta secuencia subyacente, tiene la opción de especificar si el cierre de la SslStream también cierra la secuencia subyacente. Normalmente, la clase SslStream se usa con las clases TcpClient y TcpListener. El método GetStream proporciona una NetworkStream adecuada para su uso con la clase SslStream.

Después de crear un SslStream, el servidor y, opcionalmente, el cliente debe autenticarse. El servidor debe proporcionar un certificado X509 que establezca la prueba de su identidad y pueda solicitar que el cliente también lo haga. La autenticación debe realizarse antes de transmitir información mediante un SslStream. Los clientes inician la autenticación mediante los métodos de AuthenticateAsClient sincrónicos, que bloquean hasta que se completa la autenticación o los métodos de BeginAuthenticateAsClient asincrónicos, que no bloquean la espera de que se complete la autenticación. Los servidores inician la autenticación mediante los métodos de AuthenticateAsServer sincrónicos o asincrónicos BeginAuthenticateAsServer. Tanto el cliente como el servidor deben iniciar la autenticación.

El proveedor de canales del proveedor de soporte técnico de seguridad (SSPI) controla la autenticación. El cliente tiene la oportunidad de controlar la validación del certificado del servidor especificando un delegado de RemoteCertificateValidationCallback al crear un SslStream. El servidor también puede controlar la validación proporcionando un delegado RemoteCertificateValidationCallback. El método al que hace referencia el delegado incluye el certificado de la entidad remota y los errores SSPI detectados al validar el certificado. Tenga en cuenta que si el servidor especifica un delegado, se invoca el método del delegado independientemente de si el servidor solicitó la autenticación de cliente. Si el servidor no solicitó la autenticación de cliente, el método delegado del servidor recibe un certificado NULO y una matriz vacía de errores de certificado.

Si el servidor requiere autenticación de cliente, el cliente debe especificar uno o varios certificados para la autenticación. Si el cliente tiene más de un certificado, el cliente puede proporcionar un delegado LocalCertificateSelectionCallback para seleccionar el certificado correcto para el servidor. Los certificados del cliente deben encontrarse en el almacén de certificados "My" del usuario actual. No se admite la autenticación de cliente a través de certificados para el protocolo Ssl2 (versión 2 de SSL).

Si se produce un error en la autenticación, recibirá un AuthenticationExceptiony el SslStream ya no se puede usar. Debe cerrar este objeto y quitar todas las referencias a él para que el recolector de elementos no utilizados pueda recopilarlo.

Cuando el proceso de autenticación, también conocido como protocolo de enlace SSL, se realiza correctamente, la identidad del servidor (y, opcionalmente, el cliente) se establece y el cliente y el cliente y el servidor pueden usar el SslStream para intercambiar mensajes. Antes de enviar o recibir información, el cliente y el servidor deben comprobar los servicios y niveles de seguridad proporcionados por el SslStream para determinar si el protocolo, los algoritmos y los puntos fuertes seleccionados cumplen sus requisitos de integridad y confidencialidad. Si la configuración actual no es suficiente, se debe cerrar la secuencia. Puede comprobar los servicios de seguridad proporcionados por el SslStream mediante las propiedades IsEncrypted y IsSigned. En la tabla siguiente se muestran los elementos que informan de la configuración criptográfica usada para la autenticación, el cifrado y la firma de datos.

Elemento Miembros
Protocolo de seguridad que se usa para autenticar el servidor y, opcionalmente, el cliente. La propiedad SslProtocol y la enumeración SslProtocols asociada.
Algoritmo de intercambio de claves. La propiedad KeyExchangeAlgorithm y la enumeración ExchangeAlgorithmType asociada.
Algoritmo de integridad del mensaje. La propiedad HashAlgorithm y la enumeración HashAlgorithmType asociada.
Algoritmo de confidencialidad del mensaje. La propiedad CipherAlgorithm y la enumeración CipherAlgorithmType asociada.
Puntos fuertes de los algoritmos seleccionados. Las propiedades KeyExchangeStrength, HashStrengthy CipherStrength.

Después de una autenticación correcta, puede enviar datos mediante los métodos de Write sincrónicos o asincrónicos BeginWrite. Puede recibir datos mediante los métodos de Read sincrónicos o asincrónicos BeginRead.

Si especificó en el SslStream que se debe dejar abierta la secuencia subyacente, es responsable de cerrar esa secuencia cuando haya terminado de usarla.

Nota

Si la aplicación que crea el objeto SslStream se ejecuta con las credenciales de un usuario Normal, la aplicación no podrá acceder a los certificados instalados en el almacén de máquinas locales a menos que se haya concedido permiso explícitamente al usuario para hacerlo.

SslStream supone que un tiempo de espera junto con cualquier otro IOException cuando se inicia uno desde la secuencia interna se tratará como irrecuperable por su llamador. La reutilización de una instancia de SslStream después de un tiempo de espera devolverá elementos no utilizados. Una aplicación debe Close el SslStream e iniciar una excepción en estos casos.

.NET Framework 4.6 incluye una nueva característica de seguridad que bloquea los algoritmos de cifrado y hash no seguros para las conexiones. Las aplicaciones que usan TLS/SSL a través de API como HttpClient, HttpWebRequest, FTPClient, SmtpClient, SslStream, etcetera. y el destino de .NET Framework 4.6 obtienen el comportamiento más seguro de forma predeterminada.

Es posible que los desarrolladores quieran no participar en este comportamiento para mantener la interoperabilidad con sus servicios SSL3 existentes O TLS w/ RC4. Este artículo explica cómo modificar el código para que el nuevo comportamiento esté deshabilitado.

.NET Framework 4.7 agrega nuevas sobrecargas para los métodos que autentican SslStreams que no especifican una versión de TLS, sino que usan la versión tls definida como valor predeterminado del sistema en SCHANNEL. Use estos métodos en la aplicación como una manera de poder modificar posteriormente los valores predeterminados a medida que cambia el procedimiento recomendado de la versión de TLS a lo largo del tiempo, sin necesidad de volver a compilar y volver a implementar la aplicación.

Consulte también procedimientos recomendados de seguridad de la capa de transporte (TLS) con .NET Framework.

Constructores

SslStream(Stream)

Inicializa una nueva instancia de la clase SslStream mediante el Streamespecificado.

SslStream(Stream, Boolean)

Inicializa una nueva instancia de la clase SslStream mediante el comportamiento de cierre de flujo y Stream especificados.

SslStream(Stream, Boolean, RemoteCertificateValidationCallback)

Inicializa una nueva instancia de la clase SslStream mediante el Streamespecificado, el comportamiento de cierre de flujos y el delegado de validación de certificados.

SslStream(Stream, Boolean, RemoteCertificateValidationCallback, LocalCertificateSelectionCallback)

Inicializa una nueva instancia de la clase SslStream mediante el Streamespecificado, el comportamiento de cierre de flujos, el delegado de validación de certificados y el delegado de selección de certificados especificados.

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

Inicializa una nueva instancia de la clase SslStream mediante el Streamespecificado.

Propiedades

CanRead

Obtiene un Boolean valor que indica si la secuencia subyacente es legible.

CanSeek

Obtiene un valor Boolean que indica si se puede buscar la secuencia subyacente.

CanTimeout

Obtiene un valor Boolean que indica si la secuencia subyacente admite tiempos de espera.

CanWrite

Obtiene un valor de Boolean que indica si la secuencia subyacente se puede escribir.

CheckCertRevocationStatus

Obtiene un valor de Boolean que indica si la lista de revocación de certificados se comprueba durante el proceso de validación de certificados.

CipherAlgorithm

Obtiene un valor que identifica el algoritmo de cifrado masivo usado por este SslStream.

CipherStrength

Obtiene un valor que identifica la intensidad del algoritmo de cifrado utilizado por este SslStream.

HashAlgorithm

Obtiene el algoritmo utilizado para generar códigos de autenticación de mensajes (MAC).

HashStrength

Obtiene un valor que identifica la intensidad del algoritmo hash utilizado por esta instancia.

InnerStream

Obtiene la secuencia usada por este AuthenticatedStream para enviar y recibir datos.

(Heredado de AuthenticatedStream)
IsAuthenticated

Obtiene un valor de Boolean que indica si la autenticación se realizó correctamente.

IsEncrypted

Obtiene un valor Boolean que indica si este SslStream usa el cifrado de datos.

IsMutuallyAuthenticated

Obtiene un valor de Boolean que indica si se han autenticado tanto el servidor como el cliente.

IsServer

Obtiene un Boolean valor que indica si el lado local de la conexión utilizada por este SslStream se autenticó como servidor.

IsSigned

Obtiene un valor de Boolean que indica si los datos enviados mediante esta secuencia están firmados.

KeyExchangeAlgorithm

Obtiene el algoritmo de intercambio de claves usado por este SslStream.

KeyExchangeStrength

Obtiene un valor que identifica la intensidad del algoritmo de intercambio de claves utilizado por esta instancia.

LeaveInnerStreamOpen

Obtiene si la secuencia usada por este AuthenticatedStream para enviar y recibir datos se ha dejado abierta.

(Heredado de AuthenticatedStream)
Length

Obtiene la longitud de la secuencia subyacente.

LocalCertificate

Obtiene el certificado usado para autenticar el punto de conexión local.

NegotiatedApplicationProtocol

Protocolo de aplicación negociado en el protocolo de enlace TLS.

NegotiatedCipherSuite

Obtiene el conjunto de cifrado que se negoció para esta conexión.

Position

Obtiene o establece la posición actual en la secuencia subyacente.

ReadTimeout

Obtiene o establece la cantidad de tiempo, expresada en milisegundos, que bloquea una operación de lectura en espera de datos.

RemoteCertificate

Obtiene el certificado usado para autenticar el punto de conexión remoto.

SslProtocol

Obtiene un valor que indica el protocolo de seguridad usado para autenticar esta conexión.

TargetHostName

Obtiene el nombre del servidor al que el cliente intenta conectarse. Ese nombre se usa para la validación de certificados de servidor. Puede ser un nombre DNS o una dirección IP.

TransportContext

Obtiene el TransportContext usado para la autenticación mediante la protección ampliada.

WriteTimeout

Obtiene o establece la cantidad de tiempo que una operación de escritura bloquea la espera de datos.

Métodos

AuthenticateAsClient(SslClientAuthenticationOptions)

Llamado por los clientes para autenticar el servidor y, opcionalmente, el cliente en una conexión de cliente-servidor.

AuthenticateAsClient(String)

Llamado por los clientes para autenticar el servidor y, opcionalmente, el cliente en una conexión de cliente-servidor.

AuthenticateAsClient(String, X509CertificateCollection, Boolean)

Llamado por los clientes para autenticar el servidor y, opcionalmente, el cliente en una conexión de cliente-servidor. El proceso de autenticación usa la colección de certificados especificada y el protocolo SSL predeterminado del sistema.

AuthenticateAsClient(String, X509CertificateCollection, SslProtocols, Boolean)

Llamado por los clientes para autenticar el servidor y, opcionalmente, el cliente en una conexión de cliente-servidor. El proceso de autenticación usa la colección de certificados y el protocolo SSL especificados.

AuthenticateAsClientAsync(SslClientAuthenticationOptions, CancellationToken)

Llamado por los clientes para autenticar el servidor y, opcionalmente, el cliente en una conexión cliente-servidor como una operación asincrónica. El proceso de autenticación usa información especificada en el contenedor de propiedades sslClientAuthenticationOptions.

AuthenticateAsClientAsync(String)

Llamado por los clientes para autenticar el servidor y, opcionalmente, el cliente en una conexión cliente-servidor como una operación asincrónica.

AuthenticateAsClientAsync(String, X509CertificateCollection, Boolean)

Llamado por los clientes para autenticar el servidor y, opcionalmente, el cliente en una conexión cliente-servidor como una operación asincrónica. El proceso de autenticación usa la colección de certificados especificada y el protocolo SSL predeterminado del sistema.

AuthenticateAsClientAsync(String, X509CertificateCollection, SslProtocols, Boolean)

Llamado por los clientes para autenticar el servidor y, opcionalmente, el cliente en una conexión cliente-servidor como una operación asincrónica. El proceso de autenticación usa la colección de certificados y el protocolo SSL especificados.

AuthenticateAsServer(SslServerAuthenticationOptions)

Llamado por los servidores para autenticar el servidor y, opcionalmente, el cliente en una conexión de cliente-servidor mediante el certificado especificado.

AuthenticateAsServer(X509Certificate)

Llamado por los servidores para autenticar el servidor y, opcionalmente, el cliente en una conexión de cliente-servidor mediante el certificado especificado.

AuthenticateAsServer(X509Certificate, Boolean, Boolean)

Llamado por los servidores para autenticar el servidor y, opcionalmente, el cliente en una conexión de cliente-servidor mediante los certificados y requisitos especificados, y mediante el protocolo de seguridad predeterminado del sistema.

AuthenticateAsServer(X509Certificate, Boolean, SslProtocols, Boolean)

Llamado por los servidores para autenticar el servidor y, opcionalmente, el cliente en una conexión cliente-servidor mediante los certificados, requisitos y protocolo de seguridad especificados.

AuthenticateAsServerAsync(ServerOptionsSelectionCallback, Object, CancellationToken)

Llamado por los servidores para autenticar el servidor y, opcionalmente, el cliente en una conexión cliente-servidor como una operación asincrónica. El proceso de autenticación usa información devuelta por optionsCallback.

AuthenticateAsServerAsync(SslServerAuthenticationOptions, CancellationToken)

Llamado por los servidores para autenticar el servidor y, opcionalmente, el cliente en una conexión cliente-servidor como una operación asincrónica. El proceso de autenticación usa información especificada en el contenedor de propiedades sslClientAuthenticationOptions.

AuthenticateAsServerAsync(X509Certificate)

Llamado por los servidores para autenticar el servidor y, opcionalmente, el cliente en una conexión cliente-servidor mediante el certificado especificado como una operación asincrónica.

AuthenticateAsServerAsync(X509Certificate, Boolean, Boolean)

Llamado por los servidores para autenticar el servidor y, opcionalmente, el cliente en una conexión de cliente-servidor mediante los certificados, requisitos y protocolo de seguridad especificados como una operación asincrónica.

AuthenticateAsServerAsync(X509Certificate, Boolean, SslProtocols, Boolean)

Llamado por los servidores para autenticar el servidor y, opcionalmente, el cliente en una conexión de cliente-servidor mediante los certificados, requisitos y protocolo de seguridad especificados como una operación asincrónica.

BeginAuthenticateAsClient(String, AsyncCallback, Object)

Llamado por los clientes para iniciar una operación asincrónica para autenticar el servidor y, opcionalmente, el cliente.

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

Llamado por los clientes para iniciar una operación asincrónica para autenticar el servidor y, opcionalmente, el cliente con los certificados especificados y el protocolo de seguridad predeterminado del sistema.

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

Llamado por los clientes para iniciar una operación asincrónica para autenticar el servidor y, opcionalmente, el cliente mediante los certificados y el protocolo de seguridad especificados.

BeginAuthenticateAsServer(X509Certificate, AsyncCallback, Object)

Llamado por los servidores para iniciar una operación asincrónica para autenticar al cliente y, opcionalmente, el servidor en una conexión de cliente-servidor.

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

Llamado por los servidores para iniciar una operación asincrónica para autenticar el servidor y, opcionalmente, el cliente con los certificados y requisitos especificados, y el protocolo de seguridad predeterminado del sistema.

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

Llamado por los servidores para iniciar una operación asincrónica para autenticar el servidor y, opcionalmente, el cliente mediante los certificados, requisitos y protocolo de seguridad especificados.

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

Inicia una operación de lectura asincrónica que lee datos de la secuencia y los almacena en la matriz especificada.

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

Inicia una operación de lectura asincrónica. (Considere la posibilidad de usar ReadAsync(Byte[], Int32, Int32) en su lugar).

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

Comienza una operación de escritura asincrónica que escribe Bytes del búfer especificado en la secuencia.

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

Comienza una operación de escritura asincrónica. (Considere la posibilidad de usar WriteAsync(Byte[], Int32, Int32) en su lugar).

(Heredado de Stream)
Close()

Cierra la secuencia actual y libera los recursos (como sockets y identificadores de archivo) asociados a la secuencia actual. En lugar de llamar a este método, asegúrese de que la secuencia se elimina correctamente.

(Heredado de Stream)
CopyTo(Stream)

Lee los bytes de la secuencia actual y los escribe en otra secuencia. Ambas posiciones de secuencias están avanzadas por el número de bytes copiados.

(Heredado de Stream)
CopyTo(Stream, Int32)

Lee los bytes de la secuencia actual y los escribe en otra secuencia mediante un tamaño de búfer especificado. Ambas posiciones de secuencias están avanzadas por el número de bytes copiados.

(Heredado de Stream)
CopyToAsync(Stream)

Lee asincrónicamente los bytes de la secuencia actual y los escribe en otra secuencia. Ambas posiciones de secuencias están avanzadas por el número de bytes copiados.

(Heredado de Stream)
CopyToAsync(Stream, CancellationToken)

Lee asincrónicamente los bytes de la secuencia actual y los escribe en otra secuencia, mediante un token de cancelación especificado. Ambas posiciones de secuencias están avanzadas por el número de bytes copiados.

(Heredado de Stream)
CopyToAsync(Stream, Int32)

Lee de forma asincrónica los bytes de la secuencia actual y los escribe en otra secuencia mediante un tamaño de búfer especificado. Ambas posiciones de secuencias están avanzadas por el número de bytes copiados.

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

Lee asincrónicamente los bytes de la secuencia actual y los escribe en otra secuencia, mediante un tamaño de búfer y un token de cancelación especificados. Ambas posiciones de secuencias están avanzadas por el número de bytes copiados.

(Heredado de Stream)
CreateObjRef(Type)

Crea un objeto que contiene toda la información pertinente necesaria para generar un proxy usado para comunicarse con un objeto remoto.

(Heredado de MarshalByRefObject)
CreateWaitHandle()
Obsoletos.
Obsoletos.
Obsoletos.

Asigna un objeto WaitHandle.

(Heredado de Stream)
Dispose()

Libera todos los recursos usados por el Stream.

(Heredado de Stream)
Dispose(Boolean)

Libera los recursos no administrados usados por el SslStream y, opcionalmente, libera los recursos administrados.

Dispose(Boolean)

Libera los recursos no administrados usados por el AuthenticatedStream y, opcionalmente, libera los recursos administrados.

(Heredado de AuthenticatedStream)
DisposeAsync()

Libera de forma asincrónica los recursos no administrados y administrados usados por el SslStream.

DisposeAsync()

Libera de forma asincrónica los recursos no administrados y administrados usados por el AuthenticatedStream.

(Heredado de AuthenticatedStream)
EndAuthenticateAsClient(IAsyncResult)

Finaliza una operación de autenticación de servidor asincrónica pendiente iniciada con una llamada anterior a BeginAuthenticateAsClient.

EndAuthenticateAsServer(IAsyncResult)

Finaliza una operación de autenticación de cliente asincrónica pendiente iniciada con una llamada anterior a BeginAuthenticateAsClient.

EndRead(IAsyncResult)

Finaliza una operación de lectura asincrónica iniciada con una llamada anterior a BeginRead(Byte[], Int32, Int32, AsyncCallback, Object).

EndRead(IAsyncResult)

Espera a que se complete la lectura asincrónica pendiente. (Considere la posibilidad de usar ReadAsync(Byte[], Int32, Int32) en su lugar).

(Heredado de Stream)
EndWrite(IAsyncResult)

Finaliza una operación de escritura asincrónica iniciada con una llamada anterior a BeginWrite(Byte[], Int32, Int32, AsyncCallback, Object).

EndWrite(IAsyncResult)

Finaliza una operación de escritura asincrónica. (Considere la posibilidad de usar WriteAsync(Byte[], Int32, Int32) en su lugar).

(Heredado de Stream)
Equals(Object)

Determina si el objeto especificado es igual al objeto actual.

(Heredado de Object)
Finalize()

Libera todos los recursos usados por el SslStream.

Flush()

Hace que los datos almacenados en búfer se escriban en el dispositivo subyacente.

FlushAsync()

Borra de forma asincrónica todos los búferes de esta secuencia y hace que los datos almacenados en búfer se escriban en el dispositivo subyacente.

(Heredado de Stream)
FlushAsync(CancellationToken)

Escribe de forma asincrónica los datos almacenados en búfer en el dispositivo subyacente.

FlushAsync(CancellationToken)

Borra de forma asincrónica todos los búferes de esta secuencia, hace que los datos almacenados en búfer se escriban en el dispositivo subyacente y supervisa las solicitudes de cancelación.

(Heredado de Stream)
GetHashCode()

Actúa como función hash predeterminada.

(Heredado de Object)
GetLifetimeService()
Obsoletos.

Recupera el objeto de servicio de duración actual que controla la directiva de duración de esta instancia.

(Heredado de MarshalByRefObject)
GetType()

Obtiene el Type de la instancia actual.

(Heredado de Object)
InitializeLifetimeService()
Obsoletos.

Obtiene un objeto de servicio de duración para controlar la directiva de duración de esta instancia.

(Heredado de MarshalByRefObject)
MemberwiseClone()

Crea una copia superficial del Objectactual.

(Heredado de Object)
MemberwiseClone(Boolean)

Crea una copia superficial del objeto MarshalByRefObject actual.

(Heredado de MarshalByRefObject)
NegotiateClientCertificateAsync(CancellationToken)

Negocia el certificado de cliente en la conexión autenticada.

ObjectInvariant()
Obsoletos.

Proporciona compatibilidad con un Contract.

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

Lee los datos de esta secuencia y los almacena en la matriz especificada.

Read(Span<Byte>)

Cuando se reemplaza en una clase derivada, lee una secuencia de bytes de la secuencia actual y avanza la posición dentro de la secuencia por el número de bytes leídos.

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

Lee de forma asincrónica una secuencia de bytes de la secuencia actual y avanza la posición dentro de la secuencia por el número de bytes leídos.

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

Lee de forma asincrónica los datos de esta secuencia y los almacena en el intervalo especificado de una matriz de bytes.

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

Lee de forma asincrónica una secuencia de bytes de la secuencia actual, avanza la posición dentro de la secuencia por el número de bytes leídos y supervisa las solicitudes de cancelación.

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

Lee de forma asincrónica los datos de esta secuencia y los almacena en el intervalo de memoria especificado.

ReadAsync(Memory<Byte>, CancellationToken)

Lee de forma asincrónica una secuencia de bytes de la secuencia actual, avanza la posición dentro de la secuencia por el número de bytes leídos y supervisa las solicitudes de cancelación.

(Heredado de Stream)
ReadAtLeast(Span<Byte>, Int32, Boolean)

Lee al menos un número mínimo de bytes de la secuencia actual y avanza la posición dentro de la secuencia por el número de bytes leídos.

(Heredado de Stream)
ReadAtLeastAsync(Memory<Byte>, Int32, Boolean, CancellationToken)

Lee de forma asincrónica al menos un número mínimo de bytes de la secuencia actual, avanza la posición dentro de la secuencia por el número de bytes leídos y supervisa las solicitudes de cancelación.

(Heredado de Stream)
ReadByte()

Lee un byte del SslStream y avanza la posición dentro de la secuencia por un byte, o devuelve -1 si está al final de la secuencia.

ReadByte()

Lee un byte de la secuencia y avanza la posición dentro de la secuencia por un byte, o devuelve -1 si está al final de la secuencia.

(Heredado de Stream)
ReadExactly(Byte[], Int32, Int32)

Lee count número de bytes de la secuencia actual y avanza la posición dentro de la secuencia.

(Heredado de Stream)
ReadExactly(Span<Byte>)

Lee bytes de la secuencia actual y avanza la posición dentro de la secuencia hasta que se rellena el buffer.

(Heredado de Stream)
ReadExactlyAsync(Byte[], Int32, Int32, CancellationToken)

Lee de forma asincrónica count número de bytes de la secuencia actual, avanza la posición dentro de la secuencia y supervisa las solicitudes de cancelación.

(Heredado de Stream)
ReadExactlyAsync(Memory<Byte>, CancellationToken)

Lee de forma asincrónica bytes de la secuencia actual, avanza la posición dentro de la secuencia hasta que se rellena el buffer y supervisa las solicitudes de cancelación.

(Heredado de Stream)
Seek(Int64, SeekOrigin)

Produce un NotSupportedException.

SetLength(Int64)

Establece la longitud de la secuencia subyacente.

ShutdownAsync()

Cierra este SslStream.

ToString()

Devuelve una cadena que representa el objeto actual.

(Heredado de Object)
Write(Byte[])

Escribe los datos especificados en esta secuencia.

Write(Byte[], Int32, Int32)

Escriba el número especificado de Bytes en la secuencia subyacente mediante el búfer y el desplazamiento especificados.

Write(ReadOnlySpan<Byte>)

Cuando se reemplaza en una clase derivada, escribe una secuencia de bytes en la secuencia actual y avanza la posición actual dentro de esta secuencia por el número de bytes escritos.

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

Escribe de forma asincrónica una secuencia de bytes en la secuencia actual y avanza la posición actual dentro de esta secuencia por el número de bytes escritos.

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

Escribe datos de forma asincrónica en la secuencia subyacente desde el intervalo especificado de una matriz de bytes.

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

Escribe de forma asincrónica una secuencia de bytes en la secuencia actual, avanza la posición actual dentro de esta secuencia por el número de bytes escritos y supervisa las solicitudes de cancelación.

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

Escribe datos de forma asincrónica en la secuencia subyacente desde un intervalo de memoria de bytes de solo lectura.

WriteAsync(ReadOnlyMemory<Byte>, CancellationToken)

Escribe de forma asincrónica una secuencia de bytes en la secuencia actual, avanza la posición actual dentro de esta secuencia por el número de bytes escritos y supervisa las solicitudes de cancelación.

(Heredado de Stream)
WriteByte(Byte)

Escribe un byte en la posición actual de la secuencia y avanza la posición dentro de la secuencia por un byte.

(Heredado de Stream)

Métodos de extensión

CopyToAsync(Stream, PipeWriter, CancellationToken)

Lee asincrónicamente los bytes de la Stream y los escribe en el PipeWriterespecificado mediante un token de cancelación.

ConfigureAwait(IAsyncDisposable, Boolean)

Configura cómo se realizarán las esperas en las tareas devueltas desde un descartable asincrónico.

Se aplica a

Consulte también