SslStream 类

定义

提供一个用于客户端-服务器通信的流,该流使用安全套接字层 (SSL) 安全协议对服务器和(可选)客户端进行身份验证。

public ref class SslStream : System::Net::Security::AuthenticatedStream
public class SslStream : System.Net.Security.AuthenticatedStream
type SslStream = class
    inherit AuthenticatedStream
type SslStream = class
    inherit AuthenticatedStream
    interface IDisposable
Public Class SslStream
Inherits AuthenticatedStream
继承
继承
实现

示例

下面的代码示例演示如何创建一个 TcpListener 使用该 SslStream 类与客户端通信的类。

#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

下面的代码示例演示如何创建一个 TcpClient 使用该 SslStream 类与服务器通信的类。

#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

注解

SSL 协议有助于提供机密性和完整性检查,以检查使用 as SslStream传输的消息。 在客户端与服务器之间通信敏感信息时,应使用 SSL 连接,例如提供的 SslStreamSSL 连接。 SslStream使用帮助防止任何人在网络上传输时读取和篡改信息。

SslStream实例使用创建SslStream时提供的流传输数据。 提供此基础流时,可以选择指定是否关闭 SslStream 该基础流。 通常,类SslStream与类TcpListener一起使用TcpClient。 该方法 GetStream 提供 NetworkStream 适合与类一起使用 SslStream 的方法。

创建服务器 SslStream和(可选)后,必须对客户端进行身份验证。 服务器必须提供 X509 证书,用于建立其标识证明,并可以请求客户端也这样做。 在使用 . 传输信息 SslStream之前,必须执行身份验证。 客户端使用同步 AuthenticateAsClient 方法(在身份验证完成之前阻止)或异步 BeginAuthenticateAsClient 方法(不会阻止等待身份验证完成)启动身份验证。 服务器使用同步 AuthenticateAsServer 或异步 BeginAuthenticateAsServer 方法启动身份验证。 客户端和服务器都必须启动身份验证。

身份验证由安全支持提供程序 (SSPI) 通道提供程序进行处理。 客户端有机会通过在创建SslStream委托时指定RemoteCertificateValidationCallback委托来控制服务器的证书验证。 服务器还可以通过提供 RemoteCertificateValidationCallback 委托来控制验证。 委托引用的方法包括远程方证书以及验证证书时遇到的 SSPI 的任何错误。 请注意,如果服务器指定委托,则无论服务器是否请求客户端身份验证,都会调用委托的方法。 如果服务器未请求客户端身份验证,则服务器的委托方法会收到 null 证书和空的证书错误数组。

如果服务器需要客户端身份验证,客户端必须指定一个或多个证书进行身份验证。 如果客户端有多个证书,客户端可以提供 LocalCertificateSelectionCallback 委托来为服务器选择正确的证书。 客户端的证书必须位于当前用户的“我的”证书存储中。 (SSL 版本 2) 协议不支持 Ssl2 通过证书进行身份验证。

如果身份验证失败,将收到一个 AuthenticationException,并且 SslStream 不再可用。 应关闭此对象并删除对该对象的所有引用,以便垃圾回收器可以收集该对象。

当身份验证过程(也称为 SSL 握手)成功时,服务器 (标识和(可选)建立客户端) , SslStream 客户端和服务器可以使用客户端和服务器交换消息。 在发送或接收信息之前,客户端和服务器应检查安全 SslStream 服务和级别,以确定选择的协议、算法和强度是否符合其完整性和机密性要求。 如果当前设置不够,则应关闭流。 可以检查使用IsEncryptedIsSigned属性提供SslStream的安全服务。 下表显示了报告用于身份验证、加密和数据签名的加密设置的元素。

元素 成员
用于对服务器进行身份验证以及客户端(可选)的安全协议。 属性 SslProtocol 和关联的 SslProtocols 枚举。
密钥交换算法。 属性 KeyExchangeAlgorithm 和关联的 ExchangeAlgorithmType 枚举。
消息完整性算法。 属性 HashAlgorithm 和关联的 HashAlgorithmType 枚举。
消息保密算法。 属性 CipherAlgorithm 和关联的 CipherAlgorithmType 枚举。
所选算法的优势。 HashStrength属性KeyExchangeStrengthCipherStrength属性。

成功进行身份验证后,可以使用同步 Write 或异步 BeginWrite 方法发送数据。 可以使用同步 Read 或异步 BeginRead 方法接收数据。

如果已指定 SslStream 基础流应保持打开状态,则你负责在使用该流后关闭该流。

备注

如果创建 SslStream 对象的应用程序使用 Normal 用户的凭据运行,则应用程序将无法访问本地计算机存储中安装的证书,除非已向用户显式授予权限才能执行此操作。

SslStream 假定当从内部流引发超时时,其调用方将被视为致命的超时 IOException 。 超时 SslStream 后重用实例将返回垃圾。 应用程序应 Close 在这些 SslStream 情况下引发异常。

.NET Framework 4.6 包括一项新的安全功能,用于阻止连接不安全的密码和哈希算法。 通过 HTTPClient、HttpWebRequest、FTPClient、SmtpClient、SslStream 等 API 使用 TLS/SSL 的应用程序,并在默认情况下以 .NET Framework 4.6 为目标获取更安全的行为。

开发人员可能希望选择退出此行为,以便与其现有的 SSL3 服务或 TLS w/ RC4 服务保持互操作性。 本文 介绍如何修改代码,以便禁用新行为。

.NET Framework 4.7 为不指定 TLS 版本的 SslStreams 的方法添加了新的重载,而是使用在 SCHANNEL 中定义为系统默认值的 TLS 版本。 在应用中使用这些方法作为以后能够修改默认值的方式,因为 TLS 版本在一段时间内的最佳做法更改,而无需重新生成和重新部署应用。

另请参阅传输层安全性 (TLS) 有关.NET Framework的最佳做法

构造函数

SslStream(Stream)

使用指定的 SslStream 初始化 Stream 类的新实例。

SslStream(Stream, Boolean)

使用指定的 SslStream 和流封闭行为初始化 Stream 类的新实例。

SslStream(Stream, Boolean, RemoteCertificateValidationCallback)

使用指定的 SslStream、流关闭行为和证书验证委托初始化 Stream 类的新实例。

SslStream(Stream, Boolean, RemoteCertificateValidationCallback, LocalCertificateSelectionCallback)

使用指定的 SslStream、流关闭行为、证书验证委托和证书选择委托初始化 Stream 类的新实例。

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

使用指定的 SslStream 初始化 Stream 类的新实例。

属性

CanRead

获取一个 Boolean 值,该值指示基础流是否可读。

CanSeek

获取一个 Boolean 值,该值指示基础流是否可查找。

CanTimeout

获取一个 Boolean 值,该值指示基础流是否支持超时。

CanWrite

获取一个 Boolean 值,该值指示基础流是否可写。

CheckCertRevocationStatus

获取一个 Boolean 值,该值指示在证书验证过程中是否检查证书吊销列表。

CipherAlgorithm

获取一个值,该值确定此 SslStream 使用的批量加密算法。

CipherStrength

获取一个值,该值确定此 SslStream 使用的密码算法的强度。

HashAlgorithm

获取用于生成消息身份验证代码 (MAC) 的算法。

HashStrength

获取一个值,该值标识此实例使用的哈希算法的强度。

InnerStream

获取此 AuthenticatedStream 用来发送和接收数据的流。

(继承自 AuthenticatedStream)
IsAuthenticated

获取一个 Boolean 值,该值指示身份验证是否成功。

IsEncrypted

获取一个 Boolean 值,该值指示此 SslStream 是否使用数据加密。

IsMutuallyAuthenticated

获取一个 Boolean 值,该值指示服务器和客户端是否均已进行身份验证。

IsServer

获取一个 Boolean 值,该值指示此 SslStream 使用的连接的本地端是否作为服务器进行了身份验证。

IsSigned

获取一个 Boolean 值,该值指示使用此流发送的数据是否进行签名。

KeyExchangeAlgorithm

获取此 SslStream 使用的密钥交换算法。

KeyExchangeStrength

获取一个值,该值指示此实例使用的密钥交换算法的强度。

LeaveInnerStreamOpen

获取此 AuthenticatedStream 用来发送和接收数据的流是否保持打开。

(继承自 AuthenticatedStream)
Length

获取基础流的长度。

LocalCertificate

获取用于对本地终结点进行身份验证的证书。

NegotiatedApplicationProtocol

TLS 握手中的协商应用程序协议。

NegotiatedCipherSuite

获取此连接的已协商密码套件。

Position

获取或设置基础流中的当前位置。

ReadTimeout

获取或设置读取操作阻止等待数据的时间(以毫秒为单位)。

RemoteCertificate

获取用于对远程终结点进行身份验证的证书。

SslProtocol

获取一个值,该值指示用于对此连接进行身份验证的安全协议。

TargetHostName

获取客户端尝试连接到的服务器的名称。 该名称用于服务器证书验证。 它可以是 DNS 名称,也可以是 IP 地址。

TransportContext

获取用于采用扩展保护的身份验证的 TransportContext

WriteTimeout

获取或设置写操作阻止等待数据的时间。

方法

AuthenticateAsClient(SslClientAuthenticationOptions)

由客户端调用,以对服务器或客户端服务器连接中的客户端(可选)进行身份验证。

AuthenticateAsClient(String)

由客户端调用,以对服务器或客户端服务器连接中的客户端(可选)进行身份验证。

AuthenticateAsClient(String, X509CertificateCollection, Boolean)

由客户端调用,以对服务器或客户端服务器连接中的客户端(可选)进行身份验证。 身份验证过程使用指定的证书集合和系统默认的 SSL 协议。

AuthenticateAsClient(String, X509CertificateCollection, SslProtocols, Boolean)

由客户端调用,以对服务器或客户端服务器连接中的客户端(可选)进行身份验证。 身份验证过程使用指定的证书集合和 SSL 协议。

AuthenticateAsClientAsync(SslClientAuthenticationOptions, CancellationToken)

由客户端调用,以对服务器或客户端服务器连接中的客户端(可选)进行身份验证,此为异步操作。 身份验证过程使用 sslClientAuthenticationOptions 属性包中指定的信息。

AuthenticateAsClientAsync(String)

由客户端调用,以对服务器或客户端服务器连接中的客户端(可选)进行身份验证,此为异步操作。

AuthenticateAsClientAsync(String, X509CertificateCollection, Boolean)

由客户端调用,以对服务器或客户端服务器连接中的客户端(可选)进行身份验证,此为异步操作。 身份验证过程使用指定的证书集合和系统默认的 SSL 协议。

AuthenticateAsClientAsync(String, X509CertificateCollection, SslProtocols, Boolean)

由客户端调用,以对服务器或客户端服务器连接中的客户端(可选)进行身份验证,此为异步操作。 身份验证过程使用指定的证书集合和 SSL 协议。

AuthenticateAsServer(SslServerAuthenticationOptions)

服务器调用此方法,以便使用指定的证书对客户端-服务器连接中的服务器及客户端(可选)进行身份验证。

AuthenticateAsServer(X509Certificate)

服务器调用此方法,以便使用指定的证书对客户端-服务器连接中的服务器及客户端(可选)进行身份验证。

AuthenticateAsServer(X509Certificate, Boolean, Boolean)

由服务器调用,以使用指定的证书、要求和系统默认安全协议在客户端 - 服务器连接中对服务器和客户端(可选)进行身份验证。

AuthenticateAsServer(X509Certificate, Boolean, SslProtocols, Boolean)

由服务器调用,以使用指定的证书、要求和安全协议在客户端 - 服务器连接中对服务器和客户端(可选)进行身份验证。

AuthenticateAsServerAsync(ServerOptionsSelectionCallback, Object, CancellationToken)

服务器调用此方法,对客户端-服务器连接中的服务器及客户端(可选)进行身份验证以作为异步操作。 身份验证过程使用 optionsCallback 返回的信息。

AuthenticateAsServerAsync(SslServerAuthenticationOptions, CancellationToken)

服务器调用此方法,对客户端-服务器连接中的服务器及客户端(可选)进行身份验证以作为异步操作。 身份验证过程使用 sslClientAuthenticationOptions 属性包中指定的信息。

AuthenticateAsServerAsync(X509Certificate)

服务器调用此方法,使用指定的证书对客户端-服务器连接中的服务器及客户端(可选)进行身份验证以作为异步操作。

AuthenticateAsServerAsync(X509Certificate, Boolean, Boolean)

由服务器调用,以通过异步操作的形式使用指定的证书、要求和安全协议对客户端 - 服务器连接中的服务器和客户端(可选)进行身份验证。

AuthenticateAsServerAsync(X509Certificate, Boolean, SslProtocols, Boolean)

由服务器调用,以通过异步操作的形式使用指定的证书、要求和安全协议对客户端 - 服务器连接中的服务器和客户端(可选)进行身份验证。

BeginAuthenticateAsClient(String, AsyncCallback, Object)

客户端调用此方法,以便开始一个异步操作,对服务器及客户端(可选)进行身份验证。

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

由客户端调用,以使用指定的证书和系统默认安全协议开始对服务器和客户端(可选)异步进行身份验证。

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

客户端调用此方法,以便开始一个异步操作,使用指定的证书和安全协议对服务器及客户端(可选)进行身份验证。

BeginAuthenticateAsServer(X509Certificate, AsyncCallback, Object)

服务器调用此方法,以便开始一个异步操作,对客户端-服务器连接中的客户端及服务器(可选)进行身份验证。

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

由服务器调用,以使用指定的证书、要求和系统默认安全协议开始对服务器和客户端(可选)异步进行身份验证。

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

由服务器调用,以使用指定的证书、要求和安全协议开始对服务器和客户端(可选)异步进行身份验证。

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

开始一个异步读操作,此操作读取流中的数据并将其存储在指定的数组中。

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

开始异步读操作。 (请考虑改用 ReadAsync(Byte[], Int32, Int32)。)

(继承自 Stream)
BeginWrite(Byte[], Int32, Int32, AsyncCallback, Object)

开始一个异步写操作,此操作将指定缓冲区中的 Byte 写入到流中。

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

开始异步写操作。 (请考虑改用 WriteAsync(Byte[], Int32, Int32)。)

(继承自 Stream)
Close()

关闭当前流并释放与之关联的所有资源(如套接字和文件句柄)。 不直接调用此方法,而应确保流得以正确释放。

(继承自 Stream)
CopyTo(Stream)

从当前流中读取字节并将其写入到另一流中。

(继承自 Stream)
CopyTo(Stream, Int32)

使用指定的缓冲区大小,从当前流中读取字节并将其写入到另一流中。

(继承自 Stream)
CopyToAsync(Stream)

从当前流中异步读取字节并将其写入到另一个流中。

(继承自 Stream)
CopyToAsync(Stream, CancellationToken)

通过指定的取消令牌,从当前流中异步读取字节并将其写入到另一个流中。

(继承自 Stream)
CopyToAsync(Stream, Int32)

使用指定的缓冲区大小,从当前流中异步读取字节并将其写入到另一流中。

(继承自 Stream)
CopyToAsync(Stream, Int32, CancellationToken)

使用指定的缓冲区大小和取消令牌,从当前流中异步读取字节并将其写入到另一个流中。

(继承自 Stream)
CreateObjRef(Type)

创建一个对象,该对象包含生成用于与远程对象进行通信的代理所需的全部相关信息。

(继承自 MarshalByRefObject)
CreateWaitHandle()
已过时。
已过时。

分配 WaitHandle 对象。

(继承自 Stream)
Dispose()

释放由 Stream 使用的所有资源。

(继承自 Stream)
Dispose(Boolean)

释放由 SslStream 占用的非托管资源,还可以另外再释放托管资源。

Dispose(Boolean)

释放由 AuthenticatedStream 占用的非托管资源,还可以另外再释放托管资源。

(继承自 AuthenticatedStream)
DisposeAsync()

异步释放 SslStream 使用的非托管资源和受管理资源。

DisposeAsync()

异步释放 AuthenticatedStream 使用的非托管资源和受管理资源。

(继承自 AuthenticatedStream)
EndAuthenticateAsClient(IAsyncResult)

结束通过以前调用 BeginAuthenticateAsClient 而启动的、处于挂起状态的异步服务器身份验证操作。

EndAuthenticateAsServer(IAsyncResult)

结束通过以前调用 BeginAuthenticateAsClient 而启动的、处于挂起状态的异步客户端身份验证操作。

EndRead(IAsyncResult)

结束通过以前调用 BeginRead(Byte[], Int32, Int32, AsyncCallback, Object) 而启动的异步读操作。

EndRead(IAsyncResult)

等待挂起的异步读取完成。 (请考虑改用 ReadAsync(Byte[], Int32, Int32)。)

(继承自 Stream)
EndWrite(IAsyncResult)

结束通过以前调用 BeginWrite(Byte[], Int32, Int32, AsyncCallback, Object) 而启动的异步写操作。

EndWrite(IAsyncResult)

结束异步写操作。 (请考虑改用 WriteAsync(Byte[], Int32, Int32)。)

(继承自 Stream)
Equals(Object)

确定指定对象是否等于当前对象。

(继承自 Object)
Finalize()

释放由 SslStream 使用的所有资源。

Flush()

导致所有缓冲数据都要写入基础设备。

FlushAsync()

异步清除此流的所有缓冲区并导致所有缓冲数据都写入基础设备中。

(继承自 Stream)
FlushAsync(CancellationToken)

将所有缓冲数据异步写入基础设备。

FlushAsync(CancellationToken)

异步清理此流的所有缓冲区,导致所有缓冲数据都写入基础设备,并且监控取消请求。

(继承自 Stream)
GetHashCode()

作为默认哈希函数。

(继承自 Object)
GetLifetimeService()
已过时。

检索控制此实例的生存期策略的当前生存期服务对象。

(继承自 MarshalByRefObject)
GetType()

获取当前实例的 Type

(继承自 Object)
InitializeLifetimeService()
已过时。

获取生存期服务对象来控制此实例的生存期策略。

(继承自 MarshalByRefObject)
MemberwiseClone()

创建当前 Object 的浅表副本。

(继承自 Object)
MemberwiseClone(Boolean)

创建当前 MarshalByRefObject 对象的浅表副本。

(继承自 MarshalByRefObject)
NegotiateClientCertificateAsync(CancellationToken)

在经过身份验证的连接上协商客户端证书。

ObjectInvariant()
已过时。

提供对 Contract 的支持。

(继承自 Stream)
Read(Byte[], Int32, Int32)

读取此流中的数据并将其存储在指定的数组中。

Read(Span<Byte>)

当在派生类中重写时,从当前流读取字节序列,并将此流中的位置提升读取的字节数。

(继承自 Stream)
ReadAsync(Byte[], Int32, Int32)

从当前流异步读取字节序列,并将流中的位置提升读取的字节数。

(继承自 Stream)
ReadAsync(Byte[], Int32, Int32, CancellationToken)

从此流中异步读取数据,并将其存储在字节数组的指定范围中。

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

从当前流异步读取字节的序列,将流中的位置提升读取的字节数,并监视取消请求。

(继承自 Stream)
ReadAsync(Memory<Byte>, CancellationToken)

从此流中异步读取数据,并将其存储在指定的内存范围内。

ReadAsync(Memory<Byte>, CancellationToken)

从当前流异步读取字节的序列,将流中的位置提升读取的字节数,并监视取消请求。

(继承自 Stream)
ReadByte()

SslStream 中读取一个字节,并将流内的位置向前提升一个字节,或者如果已到达流结尾,则返回 -1。

ReadByte()

从流中读取一个字节,并将流内的位置向前提升一个字节,或者如果已到达流结尾,则返回 -1。

(继承自 Stream)
Seek(Int64, SeekOrigin)

引发 NotSupportedException

SetLength(Int64)

设置基础流的长度。

ShutdownAsync()

关闭此 SslStream。

ToString()

返回表示当前对象的字符串。

(继承自 Object)
Write(Byte[])

将指定的数据写入此流。

Write(Byte[], Int32, Int32)

使用指定的缓冲区和偏移将指定数目的 Byte 写入基础流。

Write(ReadOnlySpan<Byte>)

当在派生类中重写时,向当前流中写入字节序列,并将此流中的当前位置提升写入的字节数。

(继承自 Stream)
WriteAsync(Byte[], Int32, Int32)

将字节序列异步写入当前流,并将流的当前位置提升写入的字节数。

(继承自 Stream)
WriteAsync(Byte[], Int32, Int32, CancellationToken)

从字节数组的指定范围将数据异步写入基础流。

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

将字节的序列异步写入当前流,将该流中的当前位置向前移动写入的字节数,并监视取消请求。

(继承自 Stream)
WriteAsync(ReadOnlyMemory<Byte>, CancellationToken)

将数据从只读字节内存范围异步写入基础流。

WriteAsync(ReadOnlyMemory<Byte>, CancellationToken)

将字节的序列异步写入当前流,将该流中的当前位置向前移动写入的字节数,并监视取消请求。

(继承自 Stream)
WriteByte(Byte)

将一个字节写入流内的当前位置,并将流内的位置向前提升一个字节。

(继承自 Stream)

扩展方法

ConfigureAwait(IAsyncDisposable, Boolean)

配置如何执行从异步可处置项返回的任务的等待。

适用于

另请参阅