SslStream Classe

Definição

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

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

Exemplos

O exemplo de código seguinte demonstra a criação de uma TcpListener que utiliza a SslStream classe para comunicar com clientes.

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

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

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

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

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

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

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

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

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

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

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

            Try

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

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

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

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

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

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

        Private Shared Function ReadMessage(sslStream As SslStream) As String

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

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

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

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

            Return messageData.ToString()
        End Function

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

Namespace Examples.System.Net

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

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

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

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

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

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

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

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

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

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

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

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

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

            Return messageData.ToString()

        End Function

        Private Shared Sub DisplayUsage()

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

        End Sub

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

            Dim serverCertificateName As String
            Dim machineName As String

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

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

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

            SslTcpClient.RunClient(machineName, serverCertificateName)

            Return 0

        End Function

    End Class

End Namespace

Observações

Os protocolos SSL ajudam a fornecer verificação de confidencialidade e integridade para mensagens transmitidas através de um SslStream. Uma ligação SSL, como a fornecida por SslStream, deve ser usada ao comunicar informações sensíveis entre um cliente e um servidor. A utilização de um SslStream instrumento ajuda a evitar que alguém leia e altere a informação enquanto esta está em trânsito na rede.

Uma SslStream instância transmite dados usando um fluxo que fornece ao criar o SslStream. Quando fornece este fluxo subjacente, tem a opção de especificar se fechar o SslStream fluxo também fecha o fluxo subjacente. Normalmente, a SslStream classe é usada juntamente com as TcpClient classes e TcpListener . O GetStream método oferece uma NetworkStream solução adequada para uso com a SslStream turma.

Após criar um SslStream, o servidor e, opcionalmente, o cliente deve ser autenticado. O servidor deve fornecer um certificado X509 que comprove a sua identidade e pode solicitar ao cliente que também o faça. A autenticação deve ser realizada antes de transmitir informação usando um SslStreamarquivo . Os clientes iniciam a autenticação usando os métodos síncronos AuthenticateAsClient , que bloqueiam até a autenticação ser concluída, ou os métodos assíncronos BeginAuthenticateAsClient , que não bloqueiam a espera que a autenticação seja concluída. Os servidores iniciam a autenticação usando métodos síncronos AuthenticateAsServer ou assíncronos BeginAuthenticateAsServer . Tanto o cliente como o servidor devem iniciar a autenticação.

A autenticação é gerida pelo fornecedor de canal do Fornecedor de Suporte de Segurança (SSPI). O cliente tem a oportunidade de controlar a validação do certificado do servidor, especificando um RemoteCertificateValidationCallback delegado ao criar um SslStream. O servidor também pode controlar a validação fornecendo um RemoteCertificateValidationCallback delegado. O método referenciado pelo delegado inclui o certificado da parte remota e quaisquer erros que o SSPI tenha encontrado durante a validação do certificado. Note que, se o servidor especificar um delegado, o método do delegado é invocado independentemente de o servidor ter solicitado autenticação do cliente. Se o servidor não solicitou autenticação do cliente, o método de delegado do servidor recebe um certificado nulo e um array vazio de erros de certificado.

Se o servidor exigir autenticação do cliente, o cliente deve especificar um ou mais certificados para autenticação. Se o cliente tiver mais do que um certificado, pode fornecer um LocalCertificateSelectionCallback delegado para selecionar o certificado correto para o servidor. Os certificados do cliente devem estar localizados no armazenamento de certificados "Meu" do utilizador atual. A autenticação do cliente via certificados não é suportada para o Ssl2 protocolo (SSL versão 2).

Se a autenticação falhar, recebe um AuthenticationException, e deixa SslStream de ser utilizável. Deves fechar este objeto e remover todas as referências a ele para que possa ser recolhido pelo coletor de lixo.

Quando o processo de autenticação, também conhecido como handshake SSL, tem sucesso, a identidade do servidor (e, opcionalmente, do cliente) é estabelecida e SslStream pode ser usada pelo cliente e pelo servidor para trocar mensagens. Antes de enviar ou receber informação, o cliente e o servidor devem verificar os serviços de segurança e os níveis fornecidos SslStream para determinar se o protocolo, algoritmos e pontos fortes selecionados cumprem os seus requisitos de integridade e confidencialidade. Se as definições atuais não forem suficientes, o jato deve ser fechado. Pode verificar os serviços de segurança prestados pelo SslStream utilizador e IsEncryptedIsSigned as propriedades. A tabela seguinte mostra os elementos que reportam as definições criptográficas usadas para autenticação, encriptação e assinatura de dados.

Elemento Membros
O protocolo de segurança utilizado para autenticar o servidor e, opcionalmente, o cliente. A SslProtocol propriedade e a enumeração associada SslProtocols .
O algoritmo de troca de chaves. A KeyExchangeAlgorithm propriedade e a enumeração associada ExchangeAlgorithmType .
O algoritmo de integridade da mensagem. A HashAlgorithm propriedade e a enumeração associada HashAlgorithmType .
O algoritmo de confidencialidade das mensagens. A CipherAlgorithm propriedade e a enumeração associada CipherAlgorithmType .
As forças dos algoritmos selecionados. As KeyExchangeStrengthpropriedades , HashStrength, e CipherStrength .

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

Se especificaste SslStream que o fluxo subjacente deve ficar aberto, és responsável por fechar esse fluxo quando terminares de o usar.

Note

Se a aplicação que cria o SslStream objeto correr com as credenciais de um utilizador Normal, a aplicação não poderá aceder a certificados instalados na loja local da máquina, a menos que tenha sido explicitamente dada permissão ao utilizador para o fazer.

SslStream assume que um timeout, juntamente com qualquer outro IOException , quando um é lançado do fluxo interior, será tratado como fatal pelo seu chamador. Reutilizar uma SslStream instância após um timeout vai devolver lixo. Um pedido deve CloseSslStream e lançar uma exceção nestes casos.

O .NET Framework 4.6 inclui uma funcionalidade de segurança que bloqueia algoritmos de cifra e hash inseguros para ligações. Aplicações que usam TLS/SSL através de APIs como HttpClient, HttpWebRequest, FTPClient, SmtpClient e SslStream e que visam o .NET Framework 4.6 recebem por defeito o comportamento mais seguro.

Os programadores podem querer optar por não adotar este comportamento para manter a interoperabilidade com os seus serviços SSL3 existentes OU TLS com serviços RC4. Este artigo explica como modificar o seu código para que o novo comportamento fique desativado.

O .NET Framework 4.7 adiciona novas sobrecargas para os métodos que autenticam SslStreams que não especificam uma versão TLS, mas usam a versão TLS definida como padrão do sistema em SCHANNEL. Use estes métodos na sua aplicação como forma de poder modificar posteriormente os predefinidos à medida que as melhores práticas da versão TLS mudam ao longo do tempo, sem necessidade de reconstruir e redistribuir a sua aplicação.

Consulte também as melhores práticas de segurança da camada de transporte (TLS) com o .NET Framework.

Construtores

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

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

SslStream(Stream, Boolean, RemoteCertificateValidationCallback, LocalCertificateSelectionCallback)

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

SslStream(Stream, Boolean, RemoteCertificateValidationCallback)

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

SslStream(Stream, Boolean)

Inicializa uma nova instância da SslStream classe usando o comportamento especificado Stream e de fecho do fluxo.

SslStream(Stream)

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

Propriedades

Name Description
CanRead

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

CanSeek

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

CanTimeout

Recebe um Boolean valor que indica se o fluxo subjacente suporta time-outs.

CanWrite

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

CheckCertRevocationStatus

Recebe um Boolean valor que indica se a lista de revogação de certificados foi verificada durante o processo de validação do certificado.

CipherAlgorithm

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

CipherStrength

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

HashAlgorithm

Obtém o algoritmo usado para gerar códigos de autenticação de mensagens (MACs).

HashStrength

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

InnerStream

Obtém o fluxo usado por isto AuthenticatedStream para enviar e receber dados.

(Herdado de AuthenticatedStream)
IsAuthenticated

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

IsEncrypted

Recebe um Boolean valor que indica se isto SslStream usa encriptação de dados.

IsMutuallyAuthenticated

Recebe um Boolean valor que indica se tanto o servidor como o cliente foram autenticados.

IsServer

Recebe um Boolean valor que indica se o lado local da ligação usada por isto SslStream foi autenticado como servidor.

IsSigned

Recebe um Boolean valor que indica se os dados enviados através deste fluxo estão assinados.

KeyExchangeAlgorithm

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

KeyExchangeStrength

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

LeaveInnerStreamOpen

Obtém se o fluxo usado para AuthenticatedStream enviar e receber dados ficou aberto.

(Herdado de AuthenticatedStream)
Length

Obtém o comprimento do jato subjacente.

LocalCertificate

Obtém o certificado usado para autenticar o endpoint local.

NegotiatedApplicationProtocol

O protocolo de aplicação negociada no aperto de mão TLS.

Position

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

ReadTimeout

Obtém ou define o tempo, expresso em milissegundos, uma operação de leitura bloqueia a espera de dados.

RemoteCertificate

Obtém o certificado usado para autenticar o endpoint remoto.

SslProtocol

Recebe um valor que indica o protocolo de segurança usado para autenticar esta ligação.

TransportContext

Obtém o TransportContext uso para autenticação usando proteção estendida.

WriteTimeout

Obtém ou define o tempo que uma operação de escrita bloqueia à espera de dados.

Métodos

Name Description
AuthenticateAsClient(String, X509CertificateCollection, Boolean)

É chamado pelos clientes para autenticar o servidor e, opcionalmente, o cliente numa ligação cliente-servidor. O processo de autenticação utiliza a coleção de certificados especificada e o protocolo SSL predefinido do sistema.

AuthenticateAsClient(String, X509CertificateCollection, SslProtocols, Boolean)

É chamado pelos clientes para autenticar o servidor e, opcionalmente, o cliente numa ligação cliente-servidor. O processo de autenticação utiliza a coleção de certificados especificada e o protocolo SSL.

AuthenticateAsClient(String)

É chamado pelos clientes para autenticar o servidor e, opcionalmente, o cliente numa ligação cliente-servidor.

AuthenticateAsClientAsync(SslClientAuthenticationOptions, CancellationToken)

Chamada pelos clientes para autenticar o servidor e, opcionalmente, o cliente numa ligação cliente-servidor como uma operação assíncrona. O processo de autenticação utiliza as informações especificadas no saco sslClientAuthenticationOptions de propriedades.

AuthenticateAsClientAsync(String, X509CertificateCollection, Boolean)

Chamada pelos clientes para autenticar o servidor e, opcionalmente, o cliente numa ligação cliente-servidor como uma operação assíncrona. O processo de autenticação utiliza a coleção de certificados especificada e o protocolo SSL predefinido do sistema.

AuthenticateAsClientAsync(String, X509CertificateCollection, SslProtocols, Boolean)

Chamada pelos clientes para autenticar o servidor e, opcionalmente, o cliente numa ligação cliente-servidor como uma operação assíncrona. O processo de autenticação utiliza a coleção de certificados especificada e o protocolo SSL.

AuthenticateAsClientAsync(String)

Chamada pelos clientes para autenticar o servidor e, opcionalmente, o cliente numa ligação cliente-servidor como uma operação assíncrona.

AuthenticateAsServer(X509Certificate, Boolean, Boolean)

Chamado pelos servidores para autenticar o servidor e, opcionalmente, o cliente numa ligação cliente-servidor usando os certificados e requisitos especificados, e utilizando o protocolo de segurança predefinido do sistema.

AuthenticateAsServer(X509Certificate, Boolean, SslProtocols, Boolean)

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

AuthenticateAsServer(X509Certificate)

Chamado pelos servidores para autenticar o servidor e, opcionalmente, o cliente numa ligação cliente-servidor usando o certificado especificado.

AuthenticateAsServerAsync(SslServerAuthenticationOptions, CancellationToken)

Autentica o servidor e, opcionalmente, o cliente numa ligação cliente-servidor como uma operação assíncrona. O processo de autenticação utiliza as informações especificadas no saco sslServerAuthenticationOptions de propriedades.

AuthenticateAsServerAsync(X509Certificate, Boolean, Boolean)

Chamada pelos servidores para autenticar o servidor e, opcionalmente, o cliente numa ligação cliente-servidor usando os certificados, requisitos e protocolo de segurança especificados como uma operação assíncrona.

AuthenticateAsServerAsync(X509Certificate, Boolean, SslProtocols, Boolean)

Chamada pelos servidores para autenticar o servidor e, opcionalmente, o cliente numa ligação cliente-servidor usando os certificados, requisitos e protocolo de segurança especificados como uma operação assíncrona.

AuthenticateAsServerAsync(X509Certificate)

Chamada pelos servidores para autenticar o servidor e, opcionalmente, o cliente numa ligação cliente-servidor usando o certificado especificado como uma operação assíncrona.

BeginAuthenticateAsClient(String, AsyncCallback, Object)

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

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

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

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

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

BeginAuthenticateAsServer(X509Certificate, AsyncCallback, Object)

Chamado pelos servidores para iniciar uma operação assíncrona para autenticar o cliente e, opcionalmente, o servidor numa ligação cliente-servidor.

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

Chamado pelos servidores para iniciar uma operação assíncrona de autenticação do servidor e, opcionalmente, do cliente, usando os certificados e requisitos especificados, bem como o protocolo de segurança predefinido do sistema.

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

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

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

Inicia uma operação de leitura assíncrona que lê dados do fluxo e os armazena no array especificado.

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

Inicia uma operação de escrita assíncrona que escreve Bytes do buffer especificado para o fluxo.

Close()

Fecha o fluxo atual e liberta quaisquer recursos (como sockets e handles de ficheiros) associados ao fluxo atual. Em vez de chamar este método, certifique-se de que o fluxo é devidamente descartado.

(Herdado de Stream)
CopyTo(Stream, Int32)

Lê os bytes do fluxo atual e escreve-os noutro fluxo, usando um tamanho de buffer especificado. As posições de ambos os fluxos são avançadas pelo número de bytes copiados.

(Herdado de Stream)
CopyTo(Stream)

Lê os bytes do fluxo atual e escreve-os noutro fluxo. As posições de ambos os fluxos são avançadas pelo número de bytes copiados.

(Herdado de Stream)
CopyToAsync(Stream, CancellationToken)

Lê assíncronamente os bytes do fluxo atual e escreve-os noutro fluxo, usando um token de cancelamento especificado. As posições de ambos os fluxos são avançadas pelo número de bytes copiados.

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

Lê assíncronamente os bytes do fluxo atual e escreve-os noutro fluxo, usando um tamanho de buffer especificado e um token de cancelamento. As posições de ambos os fluxos são avançadas pelo número de bytes copiados.

(Herdado de Stream)
CopyToAsync(Stream, Int32)

Lê assíncronamente os bytes do fluxo atual e escreve-os noutro fluxo, usando um tamanho de buffer especificado. As posições de ambos os fluxos são avançadas pelo número de bytes copiados.

(Herdado de Stream)
CopyToAsync(Stream)

Lê assíncronamente os bytes do fluxo atual e escreve-os noutro fluxo. As posições de ambos os fluxos são avançadas pelo número de bytes copiados.

(Herdado de Stream)
CreateObjRef(Type)

Cria um objeto que contém toda a informação relevante necessária para gerar um proxy usado para comunicar com um objeto remoto.

(Herdado de MarshalByRefObject)
CreateWaitHandle()
Obsoleto.

Aloca um WaitHandle objeto.

(Herdado de Stream)
Dispose()

Liberta todos os recursos utilizados pelo Stream.

(Herdado de Stream)
Dispose(Boolean)

Liberta os recursos não geridos usados pelo SslStream e opcionalmente liberta os recursos geridos.

DisposeAsync()

De forma assíncrona, liberta os recursos não geridos e geridos usados pelo SslStream.

EndAuthenticateAsClient(IAsyncResult)

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

EndAuthenticateAsServer(IAsyncResult)

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

EndRead(IAsyncResult)

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

EndWrite(IAsyncResult)

Termina uma operação de escrita assíncrona iniciada com uma chamada anterior para BeginWrite(Byte[], Int32, Int32, AsyncCallback, Object).

Equals(Object)

Determina se o objeto especificado é igual ao objeto atual.

(Herdado de Object)
Flush()

Faz com que quaisquer dados em buffer sejam escritos no dispositivo subjacente.

FlushAsync()

Apaga assíncronamente todos os buffers deste fluxo e faz com que quaisquer dados armazenados sejam escritos no dispositivo subjacente.

(Herdado de Stream)
FlushAsync(CancellationToken)

Escreve de forma assíncrona quaisquer dados em buffer no dispositivo subjacente.

FlushAsync(CancellationToken)

Apaga assíncronamente todos os buffers deste fluxo, faz com que quaisquer dados armazenados sejam escritos no dispositivo subjacente e monitoriza os pedidos de cancelamento.

(Herdado de Stream)
GetHashCode()

Serve como função de hash predefinida.

(Herdado de Object)
GetLifetimeService()

Recupera o objeto de serviço de tempo de vida atual que controla a política de vida útil neste caso.

(Herdado de MarshalByRefObject)
GetType()

Obtém o Type da instância atual.

(Herdado de Object)
InitializeLifetimeService()

Obtém-se um objeto de serviço vitalício para controlar a apólice vitalícia neste caso.

(Herdado de MarshalByRefObject)
MemberwiseClone()

Cria uma cópia superficial do atual Object.

(Herdado de Object)
MemberwiseClone(Boolean)

Cria uma cópia superficial do objeto atual MarshalByRefObject .

(Herdado de MarshalByRefObject)
ObjectInvariant()
Obsoleto.

Fornece suporte para um Contract.

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

Lê dados deste fluxo e armazena-os no array especificado.

Read(Span<Byte>)

Quando sobreposto numa classe derivada, lê uma sequência de bytes do fluxo atual e avança a posição dentro do fluxo pelo número de bytes lidos.

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

A leitura assíncrona dados deste fluxo e armazena-os no intervalo especificado de um array de bytes.

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

A leitura assíncrona uma sequência de bytes do fluxo atual, avança a posição dentro do fluxo pelo número de bytes lidos e monitoriza pedidos de cancelamento.

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

A leitura assíncrona uma sequência de bytes do fluxo atual e avança a posição dentro do fluxo pelo número de bytes lidos.

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

A leitura assíncrona os dados deste fluxo e armazena-os na faixa de memória especificada.

ReadByte()

Lê um byte do SslStream e avança a posição dentro do fluxo em um byte, ou devolve -1 se estiver no final do fluxo.

ReadByte()

Lê um byte do fluxo e avança a posição dentro do fluxo em um byte, ou devolve -1 se estiver no final do fluxo.

(Herdado de Stream)
Seek(Int64, SeekOrigin)

Lança um NotSupportedException.

SetLength(Int64)

Define o comprimento do curso de água subjacente.

ShutdownAsync()

Desliga este SSLStream.

ToString()

Devolve uma cadeia que representa o objeto atual.

(Herdado de Object)
Write(Byte[], Int32, Int32)

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

Write(Byte[])

Escreve os dados especificados neste fluxo.

Write(ReadOnlySpan<Byte>)

Quando sobreposto numa classe derivada, escreve uma sequência de bytes no fluxo atual e avança a posição atual dentro desse fluxo pelo número de bytes escritos.

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

Escreve dados de forma assíncrona no fluxo subjacente a partir do intervalo especificado de um array de bytes.

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

Escreve assíncronamente uma sequência de bytes no fluxo atual, avança a posição atual dentro deste fluxo pelo número de bytes escritos e monitoriza pedidos de cancelamento.

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

Escreve assíncronamente uma sequência de bytes no fluxo atual e avança a posição atual dentro desse fluxo pelo número de bytes escritos.

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

Escreve dados de forma assíncrona no fluxo subjacente a partir de um intervalo de bytes de memória de apenas leitura.

WriteByte(Byte)

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

(Herdado de Stream)

Métodos da Extensão

Name Description
ConfigureAwait(IAsyncDisposable, Boolean)

Configura como aguarda nas tarefas devolvidas de um descartável assíncrono será realizada.

Aplica-se a

Ver também