SslStream Construtores

Definição

Inicializa uma nova instância da classe SslStream.

Sobrecargas

SslStream(Stream)

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

SslStream(Stream, Boolean)

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

SslStream(Stream, Boolean, RemoteCertificateValidationCallback)

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

SslStream(Stream, Boolean, RemoteCertificateValidationCallback, LocalCertificateSelectionCallback)

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

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

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

Comentários

Para impedir que o SslStream feche o fluxo que você fornece, use o SslStream construtor .

SslStream(Stream)

Origem:
SslStream.cs
Origem:
SslStream.cs
Origem:
SslStream.cs

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

public:
 SslStream(System::IO::Stream ^ innerStream);
public SslStream (System.IO.Stream innerStream);
new System.Net.Security.SslStream : System.IO.Stream -> System.Net.Security.SslStream
Public Sub New (innerStream As Stream)

Parâmetros

innerStream
Stream

Um objeto Stream usado pelo SslStream para enviar e receber dados.

Exceções

innerStream não é legível.

- ou -

innerStream não é gravável.

innerStream é null.

- ou -

innerStream é igual a Null.

Comentários

Se um valor não for especificado no arquivo de configuração para encryptionpolicy, o EncryptionPolicy padrão EncryptionPolicy.RequireEncryption será para a SslStream instância construída.

O uso da codificação Null é necessário quando a política de criptografia é definida EncryptionPolicy.NoEncryptioncomo .

Aplica-se a

SslStream(Stream, Boolean)

Origem:
SslStream.cs
Origem:
SslStream.cs
Origem:
SslStream.cs

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

public:
 SslStream(System::IO::Stream ^ innerStream, bool leaveInnerStreamOpen);
public SslStream (System.IO.Stream innerStream, bool leaveInnerStreamOpen);
new System.Net.Security.SslStream : System.IO.Stream * bool -> System.Net.Security.SslStream
Public Sub New (innerStream As Stream, leaveInnerStreamOpen As Boolean)

Parâmetros

innerStream
Stream

Um objeto Stream usado pelo SslStream para enviar e receber dados.

leaveInnerStreamOpen
Boolean

Um valor booliano que indica o comportamento de fechamento do objeto Stream usado pelo SslStream para enviar e receber dados. Esse parâmetro indica se o fluxo interno foi deixado aberto.

Exceções

innerStream não é legível.

- ou -

innerStream não é gravável.

innerStream é null.

- ou -

innerStream é igual a Null.

Exemplos

O exemplo de código a seguir demonstra como chamar esse construtor.

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 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();
    }
}
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

Comentários

Quando você especifica true para o leaveStreamOpen parâmetro , fechar o SslStream não tem efeito no innerStream fluxo; você deve fechar innerStream explicitamente quando não precisar mais dele.

Se um valor não for especificado no arquivo de configuração para encryptionpolicy, o EncryptionPolicy padrão EncryptionPolicy.RequireEncryption será para a SslStream instância construída.

O uso da codificação Null é necessário quando a política de criptografia é definida EncryptionPolicy.NoEncryptioncomo .

Aplica-se a

SslStream(Stream, Boolean, RemoteCertificateValidationCallback)

Origem:
SslStream.cs
Origem:
SslStream.cs
Origem:
SslStream.cs

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

public:
 SslStream(System::IO::Stream ^ innerStream, bool leaveInnerStreamOpen, System::Net::Security::RemoteCertificateValidationCallback ^ userCertificateValidationCallback);
public SslStream (System.IO.Stream innerStream, bool leaveInnerStreamOpen, System.Net.Security.RemoteCertificateValidationCallback? userCertificateValidationCallback);
public SslStream (System.IO.Stream innerStream, bool leaveInnerStreamOpen, System.Net.Security.RemoteCertificateValidationCallback userCertificateValidationCallback);
new System.Net.Security.SslStream : System.IO.Stream * bool * System.Net.Security.RemoteCertificateValidationCallback -> System.Net.Security.SslStream
Public Sub New (innerStream As Stream, leaveInnerStreamOpen As Boolean, userCertificateValidationCallback As RemoteCertificateValidationCallback)

Parâmetros

innerStream
Stream

Um objeto Stream usado pelo SslStream para enviar e receber dados.

leaveInnerStreamOpen
Boolean

Um valor booliano que indica o comportamento de fechamento do objeto Stream usado pelo SslStream para enviar e receber dados. Esse parâmetro indica se o fluxo interno foi deixado aberto.

userCertificateValidationCallback
RemoteCertificateValidationCallback

Um delegado RemoteCertificateValidationCallback responsável por validar o certificado fornecido pela parte remota.

Exceções

innerStream não é legível.

- ou -

innerStream não é gravável.

innerStream é null.

- ou -

innerStream é igual a Null.

Exemplos

O exemplo de código a seguir cria um SslStream e inicia a parte do cliente da autenticação.

// 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;
}
// 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;
}
' 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

Comentários

Quando você especifica true para o leaveStreamOpen parâmetro , fechar o SslStream não tem efeito no innerStream fluxo; você deve fechar innerStream explicitamente quando não precisar mais dele.

O userCertificateValidationCallback argumento do delegado contém quaisquer códigos de erro do certificateErrors Windows retornados pela SSPI (Interface do Provedor de Suporte de Segurança) do canal. O valor retornado do método invocado pelo delegado determina se a userCertificateValidationCallback autenticação é bem-sucedida.

O protocolo de segurança e os algoritmos criptográficos já estão selecionados quando o userCertificateValidationCallback método do delegado é invocado. Você pode usar o método para determinar se os algoritmos criptográficos selecionados e os pontos fortes são suficientes para seu aplicativo. Caso contrário, o método deve retornar false para impedir que o SslStream seja criado.

Se um valor não for especificado no arquivo de configuração para encryptionpolicy, o EncryptionPolicy padrão EncryptionPolicy.RequireEncryption será para a SslStream instância construída.

O uso da codificação Null é necessário quando a política de criptografia é definida EncryptionPolicy.NoEncryptioncomo .

Observação

O .NET armazena em cache sessões SSL à medida que são criadas e tenta reutilizar uma sessão armazenada em cache para solicitações subsequentes, se possível. Ao tentar reutilizar uma sessão SSL, o Framework usa o primeiro elemento do fornecido durante a X509Certificate2Collection autenticação (se houver) ou tenta reutilizar uma sessão anônima se a coleção de certificados estiver vazia.

Observação

Não há suporte para certificados de cliente no protocolo SSL versão 2.

Aplica-se a

SslStream(Stream, Boolean, RemoteCertificateValidationCallback, LocalCertificateSelectionCallback)

Origem:
SslStream.cs
Origem:
SslStream.cs
Origem:
SslStream.cs

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

public:
 SslStream(System::IO::Stream ^ innerStream, bool leaveInnerStreamOpen, System::Net::Security::RemoteCertificateValidationCallback ^ userCertificateValidationCallback, System::Net::Security::LocalCertificateSelectionCallback ^ userCertificateSelectionCallback);
public SslStream (System.IO.Stream innerStream, bool leaveInnerStreamOpen, System.Net.Security.RemoteCertificateValidationCallback? userCertificateValidationCallback, System.Net.Security.LocalCertificateSelectionCallback? userCertificateSelectionCallback);
public SslStream (System.IO.Stream innerStream, bool leaveInnerStreamOpen, System.Net.Security.RemoteCertificateValidationCallback userCertificateValidationCallback, System.Net.Security.LocalCertificateSelectionCallback userCertificateSelectionCallback);
new System.Net.Security.SslStream : System.IO.Stream * bool * System.Net.Security.RemoteCertificateValidationCallback * System.Net.Security.LocalCertificateSelectionCallback -> System.Net.Security.SslStream
Public Sub New (innerStream As Stream, leaveInnerStreamOpen As Boolean, userCertificateValidationCallback As RemoteCertificateValidationCallback, userCertificateSelectionCallback As LocalCertificateSelectionCallback)

Parâmetros

innerStream
Stream

Um objeto Stream usado pelo SslStream para enviar e receber dados.

leaveInnerStreamOpen
Boolean

Um valor booliano que indica o comportamento de fechamento do objeto Stream usado pelo SslStream para enviar e receber dados. Esse parâmetro indica se o fluxo interno foi deixado aberto.

userCertificateValidationCallback
RemoteCertificateValidationCallback

Um delegado RemoteCertificateValidationCallback responsável por validar o certificado fornecido pela parte remota.

userCertificateSelectionCallback
LocalCertificateSelectionCallback

Um delegado de LocalCertificateSelectionCallback responsável por selecionar o certificado usado para autenticação.

Exceções

innerStream não é legível.

- ou -

innerStream não é gravável.

innerStream é null.

- ou -

innerStream é igual a Null.

Exemplos

O exemplo de código a seguir demonstra como chamar esse construtor. Este exemplo faz parte de um exemplo maior fornecido para a SslStream classe .

// Server name must match the host name and the name on the host's certificate. 
serverName = args[ 1 ];

// Create a TCP/IP client socket.
TcpClient^ client = gcnew TcpClient( serverName,5000 );
Console::WriteLine( L"Client connected." );

// Create an SSL stream that will close the client's stream.
SslStream^ sslStream = gcnew SslStream( 
    client->GetStream(),
    false,
    gcnew RemoteCertificateValidationCallback( ValidateServerCertificate ),
    gcnew LocalCertificateSelectionCallback( SelectLocalCertificate ) );
// Server name must match the host name and the name on the host's certificate.
serverName = args[0];
// Create a TCP/IP client socket.
TcpClient client = new TcpClient(serverName,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),
    new LocalCertificateSelectionCallback(SelectLocalCertificate)
    );
' Server name must match the host name and the name on the host's certificate. 
serverName = args(0)
' Create a TCP/IP client socket.
Dim client As New TcpClient(serverName, 5000)
Console.WriteLine("Client connected.")
' Create an SSL stream that will close the client's stream.
Dim sslStream As New SslStream(
    client.GetStream(), False, 
    New RemoteCertificateValidationCallback(AddressOf ValidateServerCertificate), 
    New LocalCertificateSelectionCallback(AddressOf SelectLocalCertificate))

Comentários

Quando você especifica true para o leaveStreamOpen parâmetro , fechar o SslStream não tem efeito no innerStream fluxo; você deve fechar innerStream explicitamente quando não precisar mais dele.

O userCertificateValidationCallback argumento do delegado contém quaisquer códigos de erro do certificateErrors Windows retornados pela SSPI (Interface do Provedor de Suporte de Segurança) do canal. O valor retornado do método invocado pelo delegado determina se a userCertificateValidationCallback autenticação é bem-sucedida.

O protocolo de segurança e os algoritmos criptográficos já estão selecionados quando o userCertificateValidationCallback método do delegado é invocado. Você pode usar o método para determinar se os algoritmos criptográficos selecionados e os pontos fortes são suficientes para seu aplicativo. Caso contrário, o método deve retornar false para impedir que o SslStream seja criado.

O userCertificateSelectionCallback delegado é útil quando seu aplicativo tem vários certificados e deve escolher dinamicamente um certificado. Os certificados no repositório "MY" são passados para o método invocado pelo delegado.

Se um valor não for especificado no arquivo de configuração para encryptionpolicy, o EncryptionPolicy padrão EncryptionPolicy.RequireEncryption será para a SslStream instância construída.

O uso da codificação Null é necessário quando a política de criptografia é definida EncryptionPolicy.NoEncryptioncomo .

Observação

O .NET armazena em cache sessões SSL à medida que são criadas e tenta reutilizar uma sessão armazenada em cache para solicitações subsequentes, se possível. Ao tentar reutilizar uma sessão SSL, o Framework usa o primeiro elemento do fornecido durante a X509Certificate2Collection autenticação (se houver) ou tenta reutilizar uma sessão anônima se a coleção de certificados estiver vazia.

Aplica-se a

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

Origem:
SslStream.IO.cs
Origem:
SslStream.cs
Origem:
SslStream.cs

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

public:
 SslStream(System::IO::Stream ^ innerStream, bool leaveInnerStreamOpen, System::Net::Security::RemoteCertificateValidationCallback ^ userCertificateValidationCallback, System::Net::Security::LocalCertificateSelectionCallback ^ userCertificateSelectionCallback, System::Net::Security::EncryptionPolicy encryptionPolicy);
public SslStream (System.IO.Stream innerStream, bool leaveInnerStreamOpen, System.Net.Security.RemoteCertificateValidationCallback? userCertificateValidationCallback, System.Net.Security.LocalCertificateSelectionCallback? userCertificateSelectionCallback, System.Net.Security.EncryptionPolicy encryptionPolicy);
public SslStream (System.IO.Stream innerStream, bool leaveInnerStreamOpen, System.Net.Security.RemoteCertificateValidationCallback userCertificateValidationCallback, System.Net.Security.LocalCertificateSelectionCallback userCertificateSelectionCallback, System.Net.Security.EncryptionPolicy encryptionPolicy);
new System.Net.Security.SslStream : System.IO.Stream * bool * System.Net.Security.RemoteCertificateValidationCallback * System.Net.Security.LocalCertificateSelectionCallback * System.Net.Security.EncryptionPolicy -> System.Net.Security.SslStream
Public Sub New (innerStream As Stream, leaveInnerStreamOpen As Boolean, userCertificateValidationCallback As RemoteCertificateValidationCallback, userCertificateSelectionCallback As LocalCertificateSelectionCallback, encryptionPolicy As EncryptionPolicy)

Parâmetros

innerStream
Stream

Um objeto Stream usado pelo SslStream para enviar e receber dados.

leaveInnerStreamOpen
Boolean

Um valor booliano que indica o comportamento de fechamento do objeto Stream usado pelo SslStream para enviar e receber dados. Esse parâmetro indica se o fluxo interno foi deixado aberto.

userCertificateValidationCallback
RemoteCertificateValidationCallback

Um delegado RemoteCertificateValidationCallback responsável por validar o certificado fornecido pela parte remota.

userCertificateSelectionCallback
LocalCertificateSelectionCallback

Um delegado de LocalCertificateSelectionCallback responsável por selecionar o certificado usado para autenticação.

encryptionPolicy
EncryptionPolicy

O EncryptionPolicy a ser usado.

Exceções

innerStream não é legível.

- ou -

innerStream não é gravável.

- ou -

encryptionPolicy não é válido.

innerStream é null.

- ou -

innerStream é igual a Null.

Comentários

O uso da criptografia Null é necessário quando o encryptionPolicy parâmetro é definido EncryptionPolicy.NoEncryptioncomo .

Aplica-se a