SslStream SslStream SslStream SslStream Class

Definición

Proporciona una transmisión que se utiliza para la comunicación cliente/servidor que utiliza el protocolo de seguridad Capa de sockets seguros (SSL) para autenticar el servidor y, opcionalmente, el cliente.Provides a stream used for client-server communication that uses the Secure Socket Layer (SSL) security protocol to authenticate the server and optionally the client.

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

Ejemplos

En el ejemplo de código siguiente se TcpListener muestra cómo crear SslStream un que usa la clase para comunicarse con los clientes.The following code example demonstrates creating an TcpListener that uses the SslStream class to communicate with clients.

#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

En el ejemplo de código siguiente se TcpClient muestra cómo crear SslStream un que usa la clase para comunicarse con un servidor.The following code example demonstrates creating a TcpClient that uses the SslStream class to communicate with a server.

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

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

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

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

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

            return description;
        }

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

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

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

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

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

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

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

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

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

    return 0;
}

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

namespace Examples.System.Net
{
    public class SslTcpClient 
    {   
        private static Hashtable certificateErrors = new Hashtable();
      
        // The following method is invoked by the RemoteCertificateValidationDelegate.
        public static bool ValidateServerCertificate(
              object sender,
              X509Certificate certificate,
              X509Chain chain,
              SslPolicyErrors sslPolicyErrors)
        {
           if (sslPolicyErrors == SslPolicyErrors.None)
                return true;

            Console.WriteLine("Certificate error: {0}", sslPolicyErrors);
            
            // Do not allow this client to communicate with unauthenticated servers.
            return false;
        }
        public static void RunClient(string machineName, string serverName)  
        {
            // Create a TCP/IP client socket.
            // machineName is the host running the server application.
            TcpClient client = new TcpClient(machineName,443);
            Console.WriteLine("Client connected.");
            // Create an SSL stream that will close the client's stream.
            SslStream sslStream = new SslStream(
                client.GetStream(), 
                false, 
                new RemoteCertificateValidationCallback (ValidateServerCertificate), 
                null
                );
            // The server name must match the name on the server certificate.
            try 
            {
                sslStream.AuthenticateAsClient(serverName);
            } 
            catch (AuthenticationException e)
            {
                Console.WriteLine("Exception: {0}", e.Message);
                if (e.InnerException != null)
                {
                    Console.WriteLine("Inner exception: {0}", e.InnerException.Message);
                }
                Console.WriteLine ("Authentication failed - closing the connection.");
                client.Close();
                return;
            }
            // Encode a test message into a byte array.
            // Signal the end of the message using the "<EOF>".
            byte[] messsage = Encoding.UTF8.GetBytes("Hello from the client.<EOF>");
            // Send hello message to the server. 
            sslStream.Write(messsage);
            sslStream.Flush();
            // Read message from the server.
            string serverMessage = ReadMessage(sslStream);
            Console.WriteLine("Server says: {0}", serverMessage);
            // Close the client connection.
            client.Close();
            Console.WriteLine("Client closed.");
        }
        static string ReadMessage(SslStream sslStream)
        {
            // Read the  message sent by the server.
            // The end of the message is signaled using the
            // "<EOF>" marker.
            byte [] buffer = new byte[2048];
            StringBuilder messageData = new StringBuilder();
            int bytes = -1;
            do
            {
                bytes = sslStream.Read(buffer, 0, buffer.Length);
                        
                // Use Decoder class to convert from bytes to UTF8
                // in case a character spans two buffers.
                Decoder decoder = Encoding.UTF8.GetDecoder();
                char[] chars = new char[decoder.GetCharCount(buffer,0,bytes)];
                decoder.GetChars(buffer, 0, bytes, chars,0);
                messageData.Append (chars);
                // Check for EOF.
                if (messageData.ToString().IndexOf("<EOF>") != -1)
                {
                    break;
                }
            } while (bytes != 0); 
            
            return messageData.ToString();
        }
        private static void DisplayUsage()
        { 
            Console.WriteLine("To start the client specify:");
            Console.WriteLine("clientSync machineName [serverName]");
            Environment.Exit(1);
        }
        public static int Main(string[] args)
        {
            string serverCertificateName = null;
            string machineName = null;
            if (args == null ||args.Length <1 )
            {
                DisplayUsage();
            }
            // User can specify the machine name and server name.
            // Server name must match the name on the server's certificate. 
            machineName = args[0];
            if (args.Length <2 )
            {
                serverCertificateName = machineName;
            }
            else 
            {
                serverCertificateName = args[1];
            }
            SslTcpClient.RunClient (machineName, serverCertificateName);
            return 0;
        }
    }
}
    
Imports System.Collections
Imports System.Net
Imports System.Net.Security
Imports System.Net.Sockets
Imports System.Security.Authentication
Imports System.Text
Imports System.Security.Cryptography.X509Certificates
Imports System.IO

Namespace Examples.System.Net

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

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

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

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

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

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

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

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

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

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

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

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

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

            Return messageData.ToString()

        End Function

        Private Shared Sub DisplayUsage()

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

        End Sub

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

            Dim serverCertificateName As String
            Dim machineName As String

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

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

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

            SslTcpClient.RunClient(machineName, serverCertificateName)

            Return 0

        End Function

    End Class

End Namespace

Comentarios

Los protocolos SSL ayudan a proporcionar confidencialidad y comprobación de integridad para los mensajes SslStreamtransmitidos mediante.SSL protocols help to provide confidentiality and integrity checking for messages transmitted using an SslStream. Se debe usar una conexión SSL, como la SslStreamque proporciona, al comunicar información confidencial entre un cliente y un servidor.An SSL connection, such as that provided by SslStream, should be used when communicating sensitive information between a client and a server. El uso SslStream de un ayuda a evitar que alguien lea y manipule información mientras está en tránsito en la red.Using an SslStream helps to prevent anyone from reading and tampering with information while it is in transit on the network.

Una SslStream instancia de transmite los datos mediante una secuencia que se proporciona al crear SslStreamel.An SslStream instance transmits data using a stream that you supply when creating the SslStream. Al proporcionar esta secuencia subyacente, tiene la opción de especificar si al cerrar SslStream también se cierra la secuencia subyacente.When you supply this underlying stream, you have the option to specify whether closing the SslStream also closes the underlying stream. Normalmente, la SslStream clase se usa con las TcpClient clases TcpListener y.Typically, the SslStream class is used with the TcpClient and TcpListener classes. El GetStream método proporciona un NetworkStream adecuado para su uso con SslStream la clase.The GetStream method provides a NetworkStream suitable for use with the SslStream class.

Después de crear SslStreamun, el servidor y, opcionalmente, el cliente debe estar autenticado.After creating an SslStream, the server and optionally, the client must be authenticated. El servidor debe proporcionar un certificado X509 que establezca la prueba de su identidad y pueda solicitar que el cliente también lo haga.The server must provide an X509 certificate that establishes proof of its identity and can request that the client also do so. La autenticación debe realizarse antes de transmitir información mediante SslStream.Authentication must be performed before transmitting information using an SslStream. Los clientes inician la autenticación con AuthenticateAsClient los métodos sincrónicos, que se bloquean hasta que se completa BeginAuthenticateAsClient la autenticación, o los métodos asincrónicos, que no se bloquean a la espera de que se complete la autenticación.Clients initiate authentication using the synchronous AuthenticateAsClient methods, which block until the authentication completes, or the asynchronous BeginAuthenticateAsClient methods, which do not block waiting for the authentication to complete. Los servidores inician la autenticación mediante AuthenticateAsServer BeginAuthenticateAsServer métodos sincrónicos o asincrónicos.Servers initiate authentication using the synchronous AuthenticateAsServer or asynchronous BeginAuthenticateAsServer methods. Tanto el cliente como el servidor deben iniciar la autenticación.Both client and server must initiate the authentication.

El proveedor de canal del proveedor de compatibilidad para seguridad (SSPI) controla la autenticación.The authentication is handled by the Security Support Provider (SSPI) channel provider. Al cliente se le ofrece la oportunidad de controlar la validación del certificado del servidor mediante la especificación RemoteCertificateValidationCallback de un delegado al SslStreamcrear un.The client is given an opportunity to control validation of the server's certificate by specifying a RemoteCertificateValidationCallback delegate when creating an SslStream. El servidor también puede controlar la validación proporcionando un RemoteCertificateValidationCallback delegado.The server can also control validation by supplying a RemoteCertificateValidationCallback delegate. El método al que hace referencia el delegado incluye el certificado de la entidad remota y los errores SSPI encontrados durante la validación del certificado.The method referenced by the delegate includes the remote party's certificate and any errors SSPI encountered while validating the certificate. 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 del cliente.Note that if the server specifies a delegate, the delegate's method is invoked regardless of whether the server requested client authentication. Si el servidor no solicitó la autenticación del cliente, el método delegado del servidor recibe un certificado nulo y una matriz vacía de errores de certificado.If the server did not request client authentication, the server's delegate method receives a null certificate and an empty array of certificate errors.

Si el servidor requiere autenticación del cliente, el cliente debe especificar uno o varios certificados para la autenticación.If the server requires client authentication, the client must specify one or more certificates for authentication. Si el cliente tiene más de un certificado, el cliente puede proporcionar un LocalCertificateSelectionCallback delegado para seleccionar el certificado correcto para el servidor.If the client has more than one certificate, the client can provide a LocalCertificateSelectionCallback delegate to select the correct certificate for the server. Los certificados del cliente deben encontrarse en el almacén de certificados "My" del usuario actual.The client's certificates must be located in the current user's "My" certificate store. La autenticación de cliente a través de certificados no Ssl2 es compatible con el protocolo (versión 2) de (SSL).Client authentication via certificates is not supported for the Ssl2 (SSL version 2) protocol.

Si se produce un error en la autenticación AuthenticationException, recibirá SslStream una, y ya no se podrá volver a utilizarse.If the authentication fails, you receive a AuthenticationException, and the SslStream is no longer useable. Debe cerrar este objeto y quitar todas las referencias a él para que pueda ser recopilado por el recolector de elementos no utilizados.You should close this object and remove all references to it so that it can be collected by the garbage collector.

Cuando el proceso de autenticación, también conocido como protocolo de enlace SSL, se realiza correctamente, se establece la identidad del servidor (y, opcionalmente, el cliente) SslStream y el cliente y el servidor pueden utilizar para intercambiar mensajes.When the authentication process, also known as the SSL handshake, succeeds, the identity of the server (and optionally, the client) is established and the SslStream can be used by the client and server to exchange messages. Antes de enviar o recibir información, el cliente y el servidor deben comprobar los servicios de seguridad y los SslStream niveles proporcionados por para determinar si el protocolo, los algoritmos y los puntos fuertes seleccionados cumplen sus requisitos de integridad y confidencialidad.Before sending or receiving information, the client and server should check the security services and levels provided by the SslStream to determine whether the protocol, algorithms, and strengths selected meet their requirements for integrity and confidentiality. Si la configuración actual no es suficiente, se debe cerrar la secuencia.If the current settings are not sufficient, the stream should be closed. Puede comprobar los servicios de seguridad proporcionados por SslStream mediante las IsEncrypted propiedades IsSigned y.You can check the security services provided by the SslStream using the IsEncrypted and IsSigned properties. En la tabla siguiente se muestran los elementos que informan de la configuración de cifrado utilizada para la autenticación, el cifrado y la firma de datos.The following table shows the elements that report the cryptographic settings used for authentication, encryption and data signing.

ElementoElement MiembrosMembers
El protocolo de seguridad que se usa para autenticar el servidor y, opcionalmente, el cliente.The security protocol used to authenticate the server and, optionally, the client. La SslProtocol propiedad y la enumeración asociada SslProtocols .The SslProtocol property and the associated SslProtocols enumeration.
Algoritmo de intercambio de claves.The key exchange algorithm. La KeyExchangeAlgorithm propiedad y la enumeración asociada ExchangeAlgorithmType .The KeyExchangeAlgorithm property and the associated ExchangeAlgorithmType enumeration.
Algoritmo de integridad del mensaje.The message integrity algorithm. La HashAlgorithm propiedad y la enumeración asociada HashAlgorithmType .The HashAlgorithm property and the associated HashAlgorithmType enumeration.
Algoritmo de confidencialidad del mensaje.The message confidentiality algorithm. La CipherAlgorithm propiedad y la enumeración asociada CipherAlgorithmType .The CipherAlgorithm property and the associated CipherAlgorithmType enumeration.
Las ventajas de los algoritmos seleccionados.The strengths of the selected algorithms. Las KeyExchangeStrengthpropiedades HashStrength, y CipherStrength .The KeyExchangeStrength, HashStrength, and CipherStrength properties.

Después de una autenticación correcta, puede enviar datos mediante los Write BeginWrite métodos sincrónicos o asincrónicos.After a successful authentication, you can send data using the synchronous Write or asynchronous BeginWrite methods. Puede recibir datos mediante los Read BeginRead métodos sincrónicos o asincrónicos.You can receive data using the synchronous Read or asynchronous BeginRead methods.

Si especificó en el SslStream que se debe dejar abierta la secuencia subyacente, es responsable de cerrar la secuencia cuando haya terminado de usarla.If you specified to the SslStream that the underlying stream should be left open, you are responsible for closing that stream when you are done using it.

Nota

Si la aplicación que crea el SslStream objeto se ejecuta con las credenciales de un usuario normal, la aplicación no podrá tener acceso a los certificados instalados en el almacén de la máquina local a menos que el permiso se haya dado explícitamente al usuario para que lo haga.If the application that creates the SslStream object runs with the credentials of a Normal user, the application will not be able to access certificates installed in the local machine store unless permission has been explicitly given to the user to do so.

SslStreamsupone que un tiempo de espera, junto IOException con otro, cuando se produce una excepción desde el flujo interno se tratará como grave por su llamador.SslStream assumes that a timeout along with any other IOException when one is thrown from the inner stream will be treated as fatal by its caller. Volver a utilizar SslStream una instancia después de un tiempo de espera devolverá un elemento no utilizado.Reusing a SslStream instance after a timeout will return garbage. Una aplicación debe Close SslStream generar y producir una excepción en estos casos.An application should Close the SslStream and throw an exception in these cases.

El .NET Framework 4,6 incluye una nueva característica de seguridad que bloquea los algoritmos hash y de cifrado no seguros para las conexiones.The .NET Framework 4.6 includes a new security feature that blocks insecure cipher and hashing algorithms for connections. Las aplicaciones que usan TLS/SSL a través de API como HttpClient, HttpWebRequest, FTPClient, SmtpClient, SslStream, etc. y que tienen como destino .NET Framework 4,6 obtienen el comportamiento más seguro de forma predeterminada.Applications using TLS/SSL through APIs such as HttpClient, HttpWebRequest, FTPClient, SmtpClient, SslStream, etc. and targeting .NET Framework 4.6 get the more-secure behavior by default.

Los desarrolladores pueden querer dejar de participar en este comportamiento con el fin de mantener la interoperabilidad con sus servicios de SSL3 Services o TLS w/RC4 existentes.Developers may want to opt out of this behavior in order to maintain interoperability with their existing SSL3 services OR TLS w/ RC4 services. En este artículo se explica cómo modificar el código para que el nuevo comportamiento se deshabilite.This article explains how to modify your code so that the new behavior is disabled.

El .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 de TLS definida como valor predeterminado del sistema en Schannel.The .NET Framework 4.7 adds new overloads for the methods that authenticate SslStreams that do not specify a TLS version, but instead use the TLS version defined as the system default in SCHANNEL. Use estos métodos en su aplicación para poder modificar posteriormente los valores predeterminados según los cambios recomendados de la versión de TLS con el tiempo, sin necesidad de volver a compilar e implementar la aplicación.Use these methods in your app as a way to be able to later modify the defaults as TLS version best practice changes over time, without the need to rebuild and redeploy your app.

Consulte también prácticas recomendadas de seguridad de la capa de transporte (TLS) con el .NET Framework.Also see Transport Layer Security (TLS) best practices with the .NET Framework.

Constructores

SslStream(Stream) SslStream(Stream) SslStream(Stream) SslStream(Stream)

Inicializa una nueva instancia de la clase SslStream utilizando la clase Stream especificada.Initializes a new instance of the SslStream class using the specified Stream.

SslStream(Stream, Boolean) SslStream(Stream, Boolean) SslStream(Stream, Boolean) SslStream(Stream, Boolean)

Inicializa una nueva instancia de la clase SslStream utilizando el objeto Stream especificado y el comportamiento de cierre de secuencias.Initializes a new instance of the SslStream class using the specified Stream and stream closure behavior.

SslStream(Stream, Boolean, RemoteCertificateValidationCallback) SslStream(Stream, Boolean, RemoteCertificateValidationCallback) SslStream(Stream, Boolean, RemoteCertificateValidationCallback) SslStream(Stream, Boolean, RemoteCertificateValidationCallback)

Inicializa una nueva instancia de la clase SslStream utilizando el objeto Stream, el comportamiento de cierre de secuencias y el delegado de validación de certificados especificados.Initializes a new instance of the SslStream class using the specified Stream, stream closure behavior and certificate validation delegate.

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

Inicializa una nueva instancia de la clase SslStream utilizando el objeto Stream, el delegado de validación de certificados y el delegado de selección de certificados especificados.Initializes a new instance of the SslStream class using the specified Stream, stream closure behavior, certificate validation delegate and certificate selection delegate.

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

Inicializa una nueva instancia de la clase SslStream usando el objeto Stream especificado.Initializes a new instance of the SslStream class using the specified Stream

Propiedades

CanRead CanRead CanRead CanRead

Obtiene un valor Boolean que indica si se puede leer la secuencia subyacente.Gets a Boolean value that indicates whether the underlying stream is readable.

CanSeek CanSeek CanSeek CanSeek

Obtiene un valor Boolean que indica si se puede buscar en la secuencia subyacente.Gets a Boolean value that indicates whether the underlying stream is seekable.

CanTimeout CanTimeout CanTimeout CanTimeout

Obtiene un valor Boolean que indica si la secuencia subyacente admite tiempos de espera.Gets a Boolean value that indicates whether the underlying stream supports time-outs.

CanWrite CanWrite CanWrite CanWrite

Obtiene un valor Boolean que indica si se puede escribir en la secuencia subyacente.Gets a Boolean value that indicates whether the underlying stream is writable.

CheckCertRevocationStatus CheckCertRevocationStatus CheckCertRevocationStatus CheckCertRevocationStatus

Obtiene un valor Boolean que indica si la lista de revocación de certificados se coteja durante el proceso de validación de certificados.Gets a Boolean value that indicates whether the certificate revocation list is checked during the certificate validation process.

CipherAlgorithm CipherAlgorithm CipherAlgorithm CipherAlgorithm

Obtiene un valor que identifica el algoritmo de cifrado masivo utilizado por esta secuencia SslStream.Gets a value that identifies the bulk encryption algorithm used by this SslStream.

CipherStrength CipherStrength CipherStrength CipherStrength

Obtiene un valor que identifica la intensidad del algoritmo de cifrado utilizado por esta secuencia SslStream.Gets a value that identifies the strength of the cipher algorithm used by this SslStream.

HashAlgorithm HashAlgorithm HashAlgorithm HashAlgorithm

Obtiene el algoritmo utilizado para generar códigos de autenticación de mensajes (MAC).Gets the algorithm used for generating message authentication codes (MACs).

HashStrength HashStrength HashStrength HashStrength

Obtiene un valor que identifica la intensidad del algoritmo de hash utilizado por esta instancia.Gets a value that identifies the strength of the hash algorithm used by this instance.

InnerStream InnerStream InnerStream InnerStream

Obtiene la secuencia utilizado por esta AuthenticatedStream para enviar y recibir datos.Gets the stream used by this AuthenticatedStream for sending and receiving data.

(Inherited from AuthenticatedStream)
IsAuthenticated IsAuthenticated IsAuthenticated IsAuthenticated

Obtiene un valor Boolean que indica si la autenticación se realizó correctamente.Gets a Boolean value that indicates whether authentication was successful.

IsEncrypted IsEncrypted IsEncrypted IsEncrypted

Obtiene un valor Boolean que indica si esta clase SslStream utiliza el cifrado de datos.Gets a Boolean value that indicates whether this SslStream uses data encryption.

IsMutuallyAuthenticated IsMutuallyAuthenticated IsMutuallyAuthenticated IsMutuallyAuthenticated

Obtiene un valor de Boolean que indica si se autenticaron tanto el cliente como el servidor.Gets a Boolean value that indicates whether both server and client have been authenticated.

IsServer IsServer IsServer IsServer

Obtiene un valor Boolean que indica si el lado local de la conexión utilizada por SslStream se autenticó como el servidor.Gets a Boolean value that indicates whether the local side of the connection used by this SslStream was authenticated as the server.

IsSigned IsSigned IsSigned IsSigned

Obtiene un valor Boolean que indica si los datos enviados utilizando esta secuencia tienen signo.Gets a Boolean value that indicates whether the data sent using this stream is signed.

KeyExchangeAlgorithm KeyExchangeAlgorithm KeyExchangeAlgorithm KeyExchangeAlgorithm

Obtiene el algoritmo de intercambio de claves utilizado por esta SslStream.Gets the key exchange algorithm used by this SslStream.

KeyExchangeStrength KeyExchangeStrength KeyExchangeStrength KeyExchangeStrength

Obtiene un valor que identifica la intensidad del algoritmo de intercambio de claves utilizado por esta instancia.Gets a value that identifies the strength of the key exchange algorithm used by this instance.

LeaveInnerStreamOpen LeaveInnerStreamOpen LeaveInnerStreamOpen LeaveInnerStreamOpen

Obtiene si la secuencia utilizada por esta AuthenticatedStream para enviar y recibir datos se ha dejado abierta.Gets whether the stream used by this AuthenticatedStream for sending and receiving data has been left open.

(Inherited from AuthenticatedStream)
Length Length Length Length

Obtiene la longitud de la secuencia subyacente.Gets the length of the underlying stream.

LocalCertificate LocalCertificate LocalCertificate LocalCertificate

Obtiene el certificado utilizado para autenticar el extremo local.Gets the certificate used to authenticate the local endpoint.

NegotiatedApplicationProtocol NegotiatedApplicationProtocol NegotiatedApplicationProtocol NegotiatedApplicationProtocol
NegotiatedCipherSuite NegotiatedCipherSuite NegotiatedCipherSuite NegotiatedCipherSuite

Obtiene el conjunto cifrado que se negoció para esta conexión.Gets the cipher suite which was negotiated for this connection.

Position Position Position Position

Obtiene o establece la posición actual en la secuencia subyacente.Gets or sets the current position in the underlying stream.

ReadTimeout ReadTimeout ReadTimeout ReadTimeout

Obtiene o establece el período de tiempo en milisegundo en el que una operación de lectura se bloquea en espera de los datos.Gets or sets the amount of time, expressed in milliseconds, a read operation blocks waiting for data.

RemoteCertificate RemoteCertificate RemoteCertificate RemoteCertificate

Obtiene el certificado utilizado para autenticar el extremo remoto.Gets the certificate used to authenticate the remote endpoint.

SslProtocol SslProtocol SslProtocol SslProtocol

Obtiene un valor que indica el protocolo de seguridad utilizado para autenticar esta conexión.Gets a value that indicates the security protocol used to authenticate this connection.

TransportContext TransportContext TransportContext TransportContext

Obtiene el objeto TransportContext utilizado para la autenticación utilizando la protección extendida.Gets the TransportContext used for authentication using extended protection.

WriteTimeout WriteTimeout WriteTimeout WriteTimeout

Obtiene o establece el período de tiempo que se bloquea una operación de escritura mientras espera datos.Gets or sets the amount of time a write operation blocks waiting for data.

Métodos

AuthenticateAsClient(String) AuthenticateAsClient(String) AuthenticateAsClient(String) AuthenticateAsClient(String)

Lo llaman los clientes para autenticar el servidor y, de forma opcional, el cliente en una conexión cliente-servidor.Called by clients to authenticate the server and optionally the client in a client-server connection.

AuthenticateAsClient(String, X509CertificateCollection, Boolean) AuthenticateAsClient(String, X509CertificateCollection, Boolean) AuthenticateAsClient(String, X509CertificateCollection, Boolean) AuthenticateAsClient(String, X509CertificateCollection, Boolean)

Lo llaman los clientes para autenticar el servidor y, de forma opcional, el cliente en una conexión cliente-servidor.Called by clients to authenticate the server and optionally the client in a client-server connection. El proceso de autenticación usa la colección de certificados especificada y el protocolo SSL predeterminado del sistema.The authentication process uses the specified certificate collection, and the system default SSL protocol.

AuthenticateAsClient(String, X509CertificateCollection, SslProtocols, Boolean) AuthenticateAsClient(String, X509CertificateCollection, SslProtocols, Boolean) AuthenticateAsClient(String, X509CertificateCollection, SslProtocols, Boolean) AuthenticateAsClient(String, X509CertificateCollection, SslProtocols, Boolean)

Lo llaman los clientes para autenticar el servidor y, de forma opcional, el cliente en una conexión cliente-servidor.Called by clients to authenticate the server and optionally the client in a client-server connection. El proceso de autenticación utiliza la colección de certificados especificada y el protocolo SSL.The authentication process uses the specified certificate collection and SSL protocol.

AuthenticateAsClientAsync(SslClientAuthenticationOptions, CancellationToken) AuthenticateAsClientAsync(SslClientAuthenticationOptions, CancellationToken) AuthenticateAsClientAsync(SslClientAuthenticationOptions, CancellationToken) AuthenticateAsClientAsync(SslClientAuthenticationOptions, CancellationToken)
AuthenticateAsClientAsync(String) AuthenticateAsClientAsync(String) AuthenticateAsClientAsync(String) AuthenticateAsClientAsync(String)

Lo llaman los clientes para autenticar el servidor y, de forma opcional, el cliente en una conexión cliente-servidor como operación asincrónica.Called by clients to authenticate the server and optionally the client in a client-server connection as an asynchronous operation.

AuthenticateAsClientAsync(String, X509CertificateCollection, Boolean) AuthenticateAsClientAsync(String, X509CertificateCollection, Boolean) AuthenticateAsClientAsync(String, X509CertificateCollection, Boolean) AuthenticateAsClientAsync(String, X509CertificateCollection, Boolean)

Lo llaman los clientes para autenticar el servidor y, de forma opcional, el cliente en una conexión cliente-servidor como operación asincrónica.Called by clients to authenticate the server and optionally the client in a client-server connection as an asynchronous operation. El proceso de autenticación usa la colección de certificados especificada y el protocolo SSL predeterminado del sistema.The authentication process uses the specified certificate collection and the system default SSL protocol.

AuthenticateAsClientAsync(String, X509CertificateCollection, SslProtocols, Boolean) AuthenticateAsClientAsync(String, X509CertificateCollection, SslProtocols, Boolean) AuthenticateAsClientAsync(String, X509CertificateCollection, SslProtocols, Boolean) AuthenticateAsClientAsync(String, X509CertificateCollection, SslProtocols, Boolean)

Lo llaman los clientes para autenticar el servidor y, de forma opcional, el cliente en una conexión cliente-servidor como operación asincrónica.Called by clients to authenticate the server and optionally the client in a client-server connection as an asynchronous operation. El proceso de autenticación utiliza la colección de certificados especificada y el protocolo SSL.The authentication process uses the specified certificate collection and SSL protocol.

AuthenticateAsServer(X509Certificate) AuthenticateAsServer(X509Certificate) AuthenticateAsServer(X509Certificate) AuthenticateAsServer(X509Certificate)

Lo llaman los servidores para autenticar el servidor, y opcionalmente el cliente, en una conexión cliente-servidor utilizando el certificado especificado.Called by servers to authenticate the server and optionally the client in a client-server connection using the specified certificate.

AuthenticateAsServer(X509Certificate, Boolean, Boolean) AuthenticateAsServer(X509Certificate, Boolean, Boolean) AuthenticateAsServer(X509Certificate, Boolean, Boolean) AuthenticateAsServer(X509Certificate, Boolean, Boolean)

Los llaman los servidores para autenticar el servidor y, opcionalmente, el cliente en una conexión cliente/servidor mediante los certificados y requisitos especificados, además del protocolo de seguridad predeterminado del sistema.Called by servers to authenticate the server and optionally the client in a client-server connection using the specified certificates and requirements, and using the system default security protocol.

AuthenticateAsServer(X509Certificate, Boolean, SslProtocols, Boolean) AuthenticateAsServer(X509Certificate, Boolean, SslProtocols, Boolean) AuthenticateAsServer(X509Certificate, Boolean, SslProtocols, Boolean) AuthenticateAsServer(X509Certificate, Boolean, SslProtocols, Boolean)

Los llaman los servidores para autenticar el servidor y, opcionalmente, el cliente en una conexión cliente/servidor mediante los certificados, los requisitos y el protocolo de seguridad.Called by servers to authenticate the server and optionally the client in a client-server connection using the specified certificates, requirements and security protocol.

AuthenticateAsServerAsync(SslServerAuthenticationOptions, CancellationToken) AuthenticateAsServerAsync(SslServerAuthenticationOptions, CancellationToken) AuthenticateAsServerAsync(SslServerAuthenticationOptions, CancellationToken) AuthenticateAsServerAsync(SslServerAuthenticationOptions, CancellationToken)
AuthenticateAsServerAsync(X509Certificate) AuthenticateAsServerAsync(X509Certificate) AuthenticateAsServerAsync(X509Certificate) AuthenticateAsServerAsync(X509Certificate)

Lo llaman los servidores para autenticar el servidor, y opcionalmente el cliente, en una conexión cliente-servidor utilizando el certificado especificado como una operación asincrónica.Called by servers to authenticate the server and optionally the client in a client-server connection using the specified certificate as an asynchronous operation.

AuthenticateAsServerAsync(X509Certificate, Boolean, Boolean) AuthenticateAsServerAsync(X509Certificate, Boolean, Boolean) AuthenticateAsServerAsync(X509Certificate, Boolean, Boolean) AuthenticateAsServerAsync(X509Certificate, Boolean, Boolean)

Los llaman los servidores para autenticar el servidor y, opcionalmente, el cliente en una conexión cliente/servidor mediante los certificados, los requisitos y el protocolo de seguridad especificados como una operación asincrónica.Called by servers to authenticate the server and optionally the client in a client-server connection using the specified certificates, requirements and security protocol as an asynchronous operation.

AuthenticateAsServerAsync(X509Certificate, Boolean, SslProtocols, Boolean) AuthenticateAsServerAsync(X509Certificate, Boolean, SslProtocols, Boolean) AuthenticateAsServerAsync(X509Certificate, Boolean, SslProtocols, Boolean) AuthenticateAsServerAsync(X509Certificate, Boolean, SslProtocols, Boolean)

Los llaman los servidores para autenticar el servidor y, opcionalmente, el cliente en una conexión cliente/servidor mediante los certificados, los requisitos y el protocolo de seguridad especificados como una operación asincrónica.Called by servers to authenticate the server and optionally the client in a client-server connection using the specified certificates, requirements and security protocol as an asynchronous operation.

BeginAuthenticateAsClient(String, AsyncCallback, Object) BeginAuthenticateAsClient(String, AsyncCallback, Object) BeginAuthenticateAsClient(String, AsyncCallback, Object) BeginAuthenticateAsClient(String, AsyncCallback, Object)

Lo llaman clientes para empezar una operación asincrónica con el fin de autenticar el servidor y opcionalmente el cliente.Called by clients to begin an asynchronous operation to authenticate the server and optionally the client.

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

Los llaman los servidores para comenzar una operación asincrónica con el fin de autenticar el servidor y, opcionalmente, el cliente mediante los certificados especificados y el protocolo de seguridad predeterminado del sistema.Called by clients to begin an asynchronous operation to authenticate the server and optionally the client using the specified certificates and the system default security protocol.

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

Lo llaman los clientes para empezar una operación asincrónica con el fin de autenticar el servidor y, opcionalmente el cliente, mediante los certificados, los requisitos y el protocolo de seguridad especificados.Called by clients to begin an asynchronous operation to authenticate the server and optionally the client using the specified certificates and security protocol.

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

Lo llaman los servidores para comenzar una operación asincrónica con el fin de autenticar el cliente, y opcionalmente el servidor, en una conexión cliente-servidor.Called by servers to begin an asynchronous operation to authenticate the client and optionally the server in a client-server connection.

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

Los llaman los servidores para comenzar una operación asincrónica con el fin de autenticar el servidor y, opcionalmente, el cliente mediante los certificados y requisitos especificados, además del protocolo de seguridad predeterminado del sistema.Called by servers to begin an asynchronous operation to authenticate the server and optionally the client using the specified certificates and requirements, and the system default security protocol.

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

Los llaman los servidores para comenzar una operación asincrónica con el fin de autenticar el servidor y, opcionalmente, el cliente mediante los certificados, requisitos y protocolo de seguridad especificados.Called by servers to begin an asynchronous operation to authenticate the server and optionally the client using the specified certificates, requirements and security protocol.

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

Inicia una operación de lectura asincrónica que lee los datos de la secuencia y los almacena en la matriz especificada.Begins an asynchronous read operation that reads data from the stream and stores it in the specified array.

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

Inicia una operación de escritura asincrónica que escribe Bytes desde el búfer especificado en la secuencia.Begins an asynchronous write operation that writes Bytes from the specified buffer to the stream.

Close() Close() Close() Close()

Cierra la secuencia actual y libera todos los recursos (como sockets e identificadores de archivo) asociados a esta.Closes the current stream and releases any resources (such as sockets and file handles) associated with the current stream. En lugar de llamar a este método, asegúrese de que la secuencia se desecha correctamente.Instead of calling this method, ensure that the stream is properly disposed.

(Inherited from Stream)
CopyTo(Stream) CopyTo(Stream) CopyTo(Stream) CopyTo(Stream)

Lee los bytes de la secuencia actual y los escribe en otra secuencia de destino.Reads the bytes from the current stream and writes them to another stream.

(Inherited from Stream)
CopyTo(Stream, Int32) CopyTo(Stream, Int32) CopyTo(Stream, Int32) CopyTo(Stream, Int32)

Lee todos los bytes de la secuencia actual y los escribe en otra secuencia, usando el tamaño de búfer especificado.Reads the bytes from the current stream and writes them to another stream, using a specified buffer size.

(Inherited from Stream)
CopyToAsync(Stream) CopyToAsync(Stream) CopyToAsync(Stream) CopyToAsync(Stream)

Lee asincrónicamente los bytes de la secuencia actual y los escribe en otra secuencia.Asynchronously reads the bytes from the current stream and writes them to another stream.

(Inherited from Stream)
CopyToAsync(Stream, CancellationToken) CopyToAsync(Stream, CancellationToken) CopyToAsync(Stream, CancellationToken) CopyToAsync(Stream, CancellationToken)

Lee de forma asincrónica los bytes de la secuencia actual y los escribe en otra secuencia mediante un token de cancelación especificado.Asynchronously reads the bytes from the current stream and writes them to another stream, using a specified cancellation token.

(Inherited from Stream)
CopyToAsync(Stream, Int32) CopyToAsync(Stream, Int32) CopyToAsync(Stream, Int32) CopyToAsync(Stream, Int32)

Lee asincrónicamente los bytes de la secuencia actual y los escribe en otra secuencia, usando el tamaño de búfer especificado.Asynchronously reads the bytes from the current stream and writes them to another stream, using a specified buffer size.

(Inherited from Stream)
CopyToAsync(Stream, Int32, CancellationToken) CopyToAsync(Stream, Int32, CancellationToken) CopyToAsync(Stream, Int32, CancellationToken) CopyToAsync(Stream, Int32, CancellationToken)

Lee asincrónicamente los bytes de la secuencia actual y los escribe en otra secuencia, utilizando el tamaño de búfer y el token de cancelación especificados.Asynchronously reads the bytes from the current stream and writes them to another stream, using a specified buffer size and cancellation token.

(Inherited from Stream)
CreateObjRef(Type) CreateObjRef(Type) CreateObjRef(Type) CreateObjRef(Type)

Crea un objeto que contiene toda la información relevante necesaria para generar un proxy utilizado para comunicarse con un objeto remoto.Creates an object that contains all the relevant information required to generate a proxy used to communicate with a remote object.

(Inherited from MarshalByRefObject)
CreateWaitHandle() CreateWaitHandle() CreateWaitHandle() CreateWaitHandle()

Asigna un objeto WaitHandle.Allocates a WaitHandle object.

(Inherited from Stream)
Dispose() Dispose() Dispose() Dispose()

Libera todos los recursos que usa Stream.Releases all resources used by the Stream.

(Inherited from Stream)
Dispose(Boolean) Dispose(Boolean) Dispose(Boolean) Dispose(Boolean)

Libera los recursos no administrados que usa SslStream y, de forma opcional, libera los recursos administrados.Releases the unmanaged resources used by the SslStream and optionally releases the managed resources.

DisposeAsync() DisposeAsync() DisposeAsync() DisposeAsync()

Libera de forma asincrónica los recursos administrados y no administrados que usa SslStream.Asynchronously releases the unmanaged and managed resources used by the SslStream.

EndAuthenticateAsClient(IAsyncResult) EndAuthenticateAsClient(IAsyncResult) EndAuthenticateAsClient(IAsyncResult) EndAuthenticateAsClient(IAsyncResult)

Finaliza una operación de autenticación de servidor asincrónica iniciada con una llamada previa a BeginAuthenticateAsClient.Ends a pending asynchronous server authentication operation started with a previous call to BeginAuthenticateAsClient.

EndAuthenticateAsServer(IAsyncResult) EndAuthenticateAsServer(IAsyncResult) EndAuthenticateAsServer(IAsyncResult) EndAuthenticateAsServer(IAsyncResult)

Finaliza una operación de autenticación de cliente asincrónica iniciada con una llamada previa a BeginAuthenticateAsClient.Ends a pending asynchronous client authentication operation started with a previous call to BeginAuthenticateAsClient.

EndRead(IAsyncResult) EndRead(IAsyncResult) EndRead(IAsyncResult) EndRead(IAsyncResult)

Finaliza una operación de lectura asincrónica iniciada con una llamada previa a BeginRead(Byte[], Int32, Int32, AsyncCallback, Object).Ends an asynchronous read operation started with a previous call to BeginRead(Byte[], Int32, Int32, AsyncCallback, Object).

EndWrite(IAsyncResult) EndWrite(IAsyncResult) EndWrite(IAsyncResult) EndWrite(IAsyncResult)

Finaliza una operación de escritura asincrónica iniciada con una llamada previa a BeginWrite(Byte[], Int32, Int32, AsyncCallback, Object).Ends an asynchronous write operation started with a previous call to BeginWrite(Byte[], Int32, Int32, AsyncCallback, Object).

Equals(Object) Equals(Object) Equals(Object) Equals(Object)

Determina si el objeto especificado es igual al objeto actual.Determines whether the specified object is equal to the current object.

(Inherited from Object)
Flush() Flush() Flush() Flush()

Provoca la escritura de los datos almacenados en el búfer del dispositivo subyacente.Causes any buffered data to be written to the underlying device.

FlushAsync() FlushAsync() FlushAsync() FlushAsync()

Borra asincrónicamente todos los búferes de esta secuencia y hace que los datos almacenados en búfer se escriban en el dispositivo subyacente.Asynchronously clears all buffers for this stream and causes any buffered data to be written to the underlying device.

(Inherited from Stream)
FlushAsync(CancellationToken) FlushAsync(CancellationToken) FlushAsync(CancellationToken) FlushAsync(CancellationToken)
GetHashCode() GetHashCode() GetHashCode() GetHashCode()

Sirve como la función hash predeterminada.Serves as the default hash function.

(Inherited from Object)
GetLifetimeService() GetLifetimeService() GetLifetimeService() GetLifetimeService()

Recupera el objeto de servicio de duración actual que controla la directiva de duración de esta instancia.Retrieves the current lifetime service object that controls the lifetime policy for this instance.

(Inherited from MarshalByRefObject)
GetType() GetType() GetType() GetType()

Obtiene el Type de la instancia actual.Gets the Type of the current instance.

(Inherited from Object)
InitializeLifetimeService() InitializeLifetimeService() InitializeLifetimeService() InitializeLifetimeService()

Obtiene un objeto de servicio de duración para controlar la directiva de duración de esta instancia.Obtains a lifetime service object to control the lifetime policy for this instance.

(Inherited from MarshalByRefObject)
MemberwiseClone() MemberwiseClone() MemberwiseClone() MemberwiseClone()

Crea una copia superficial del objeto Object actual.Creates a shallow copy of the current Object.

(Inherited from Object)
MemberwiseClone(Boolean) MemberwiseClone(Boolean) MemberwiseClone(Boolean) MemberwiseClone(Boolean)

Crea una copia superficial del objeto MarshalByRefObject actual.Creates a shallow copy of the current MarshalByRefObject object.

(Inherited from MarshalByRefObject)
ObjectInvariant() ObjectInvariant() ObjectInvariant() ObjectInvariant()

Proporciona compatibilidad con una clase Contract.Provides support for a Contract.

(Inherited from Stream)
Read(Byte[], Int32, Int32) Read(Byte[], Int32, Int32) Read(Byte[], Int32, Int32) Read(Byte[], Int32, Int32)

Lee datos de esta secuencia y los almacena en la matriz especificada.Reads data from this stream and stores it in the specified array.

Read(Span<Byte>) Read(Span<Byte>) Read(Span<Byte>) Read(Span<Byte>)

Cuando se reemplaza en una clase derivada, se lee una secuencia de bytes en la secuencia actual y se hace avanzar la posición dentro de la secuencia el número de bytes leídos.When overridden in a derived class, reads a sequence of bytes from the current stream and advances the position within the stream by the number of bytes read.

(Inherited from Stream)
ReadAsync(Byte[], Int32, Int32) ReadAsync(Byte[], Int32, Int32) ReadAsync(Byte[], Int32, Int32) ReadAsync(Byte[], Int32, Int32)

Lee asincrónicamente una secuencia de bytes de la secuencia actual y avanza la posición en esta secuencia según el número de bytes leídos.Asynchronously reads a sequence of bytes from the current stream and advances the position within the stream by the number of bytes read.

(Inherited from Stream)
ReadAsync(Byte[], Int32, Int32, CancellationToken) ReadAsync(Byte[], Int32, Int32, CancellationToken) ReadAsync(Byte[], Int32, Int32, CancellationToken) ReadAsync(Byte[], Int32, Int32, CancellationToken)

Lee de forma asincrónica los datos de esta secuencia y los almacena en el rango especificado de una matriz de bytes.Asynchronously reads data from this stream and stores it in the specified range of a byte array.

ReadAsync(Memory<Byte>, CancellationToken) ReadAsync(Memory<Byte>, CancellationToken) ReadAsync(Memory<Byte>, CancellationToken) ReadAsync(Memory<Byte>, CancellationToken)

Lee de forma asincrónica los datos de esta secuencia y los almacena en el rango de memoria especificado.Asynchronously reads data from this stream and stores it in the specified memory range.

ReadByte() ReadByte() ReadByte() ReadByte()

Lee un byte de SslStream y hace avanzar la posición de la secuencia en un byte, o devuelve -1 si está al final de la secuencia.Reads a byte from the SslStream and advances the position within the stream by one byte, or returns -1 if at the end of the stream.

Seek(Int64, SeekOrigin) Seek(Int64, SeekOrigin) Seek(Int64, SeekOrigin) Seek(Int64, SeekOrigin)

Produce una excepción NotSupportedException.Throws a NotSupportedException.

SetLength(Int64) SetLength(Int64) SetLength(Int64) SetLength(Int64)

Establece la longitud de la secuencia subyacente.Sets the length of the underlying stream.

ShutdownAsync() ShutdownAsync() ShutdownAsync() ShutdownAsync()

Cierra esta clase SslStream.Shuts down this SslStream.

ToString() ToString() ToString() ToString()

Devuelve una cadena que representa el objeto actual.Returns a string that represents the current object.

(Inherited from Object)
Write(Byte[]) Write(Byte[]) Write(Byte[]) Write(Byte[])

Escribe los datos especificados en esta secuencia.Writes the specified data to this stream.

Write(Byte[], Int32, Int32) Write(Byte[], Int32, Int32) Write(Byte[], Int32, Int32) Write(Byte[], Int32, Int32)

Escriba el número especificado de Bytes en la secuencia subyacente mediante el búfer y el desplazamiento especificados.Write the specified number of Bytes to the underlying stream using the specified buffer and offset.

Write(ReadOnlySpan<Byte>) Write(ReadOnlySpan<Byte>) Write(ReadOnlySpan<Byte>) Write(ReadOnlySpan<Byte>)

Cuando se reemplaza en una clase derivada, se escribe una secuencia de bytes en la secuencia actual y se hace avanzar la posición actual dentro de la secuencia el número de bytes escritos.When overridden in a derived class, writes a sequence of bytes to the current stream and advances the current position within this stream by the number of bytes written.

(Inherited from Stream)
WriteAsync(Byte[], Int32, Int32) WriteAsync(Byte[], Int32, Int32) WriteAsync(Byte[], Int32, Int32) WriteAsync(Byte[], Int32, Int32)

Escribe asincrónicamente una secuencia de bytes en la secuencia actual y avanza la posición actual en esta secuencia según el número de bytes escritos.Asynchronously writes a sequence of bytes to the current stream and advances the current position within this stream by the number of bytes written.

(Inherited from Stream)
WriteAsync(Byte[], Int32, Int32, CancellationToken) WriteAsync(Byte[], Int32, Int32, CancellationToken) WriteAsync(Byte[], Int32, Int32, CancellationToken) WriteAsync(Byte[], Int32, Int32, CancellationToken)

Escribe de forma asincrónica datos en la secuencia subyacente desde el rango especificado de una matriz de bytes.Asynchronously writes data to the underlying stream from the specified range of a byte array.

WriteAsync(ReadOnlyMemory<Byte>, CancellationToken) WriteAsync(ReadOnlyMemory<Byte>, CancellationToken) WriteAsync(ReadOnlyMemory<Byte>, CancellationToken) WriteAsync(ReadOnlyMemory<Byte>, CancellationToken)

Escribe de forma asincrónica datos en la secuencia subyacente desde un rango de memoria de bytes de solo lectura.Asynchronously writes data to the underlying stream from a read-only byte memory range.

WriteByte(Byte) WriteByte(Byte) WriteByte(Byte) WriteByte(Byte)

Escribe un byte a la posición actual en la secuencia y avanza la posición de la secuencia en un byte.Writes a byte to the current position in the stream and advances the position within the stream by one byte.

(Inherited from Stream)

Implementaciones de interfaz explícitas

IDisposable.Dispose() IDisposable.Dispose() IDisposable.Dispose() IDisposable.Dispose()

Libera todos los recursos que usa Stream.Releases all resources used by the Stream.

(Inherited from Stream)

Se aplica a

Consulte también: