SslStream 類別

定義

提供用於用戶端與伺服器通訊的資料流,其會使用安全通訊端層 (SSL) 安全性通訊協定來驗證伺服器及用戶端 (選擇性)。Provides a stream used for client-server communication that uses the Secure Socket Layer (SSL) security protocol to authenticate the server and optionally the client.

public ref class SslStream : System::Net::Security::AuthenticatedStream
public class SslStream : System.Net.Security.AuthenticatedStream
type SslStream = class
    inherit AuthenticatedStream
type SslStream = class
    inherit AuthenticatedStream
    interface IDisposable
Public Class SslStream
Inherits AuthenticatedStream
繼承
繼承
實作

範例

下列程式碼範例將示範如何建立 TcpListener 使用 SslStream 類別與用戶端進行通訊的。The following code example demonstrates creating an TcpListener that uses the SslStream class to communicate with clients.

#using <System.dll>

using namespace System;
using namespace System::Collections;
using namespace System::Net;
using namespace System::Net::Sockets;
using namespace System::Net::Security;
using namespace System::Security::Authentication;
using namespace System::Text;
using namespace System::Security::Cryptography::X509Certificates;
using namespace System::IO;
public ref class SslTcpServer sealed
{
private:
   static X509Certificate^ serverCertificate = nullptr;

public:

   // The certificate parameter specifies the name of the file 
   // containing the machine certificate.
   static void RunServer( String^ certificate )
   {
      serverCertificate = X509Certificate::CreateFromCertFile( certificate );
      
      // Create a TCP/IP (IPv4) socket and listen for incoming connections.
      TcpListener^ listener = gcnew TcpListener( IPAddress::Any,8080 );
      listener->Start();
      
      while (true) 
      {
         Console::WriteLine( L"Waiting for a client to connect..." );
         
         // Application blocks while waiting for an incoming connection.
         // Type CNTL-C to terminate the server.
         TcpClient^ client = listener->AcceptTcpClient();
         ProcessClient( client );

      }
   }


   static void ProcessClient( TcpClient^ client )
   {
      
      // A client has connected. Create the 
      // SslStream using the client's network stream.
      SslStream^ sslStream = gcnew SslStream( client->GetStream(),false );
      
      // Authenticate the server but don't require the client to authenticate.
      try
      {
         sslStream->AuthenticateAsServer( serverCertificate, false, true );
         // false == no client cert required; true == check cert revocation.
         
         // Display the properties and settings for the authenticated stream.
         DisplaySecurityLevel( sslStream );
         DisplaySecurityServices( sslStream );
         DisplayCertificateInformation( sslStream );
         DisplayStreamProperties( sslStream );
         
         // Set timeouts for the read and write to 5 seconds.
         sslStream->ReadTimeout = 5000;
         sslStream->WriteTimeout = 5000;
         
         // Read a message from the client.   
         Console::WriteLine( L"Waiting for client message..." );
         String^ messageData = ReadMessage( sslStream );
         Console::WriteLine( L"Received: {0}", messageData );
         
         // Write a message to the client.
         array<Byte>^message = Encoding::UTF8->GetBytes( L"Hello from the server.<EOF>" );
         Console::WriteLine( L"Sending hello message." );
         sslStream->Write( message );
      }
      catch ( AuthenticationException^ e ) 
      {
         Console::WriteLine( L"Exception: {0}", e->Message );
         if ( e->InnerException != nullptr )
         {
            Console::WriteLine( L"Inner exception: {0}", e->InnerException->Message );
         }
         Console::WriteLine( L"Authentication failed - closing the connection." );
         sslStream->Close();
         client->Close();
         return;
      }
      finally
      {
         
         // The client stream will be closed with the sslStream
         // because we specified this behavior when creating
         // the sslStream.
         sslStream->Close();
         client->Close();
      }

   }


   static String^ ReadMessage( SslStream^ sslStream )
   {
      
      // Read the  message sent by the client.
      // The client signals the end of the message using the
      // "<EOF>" marker.
      array<Byte>^buffer = gcnew array<Byte>(2048);
      StringBuilder^ messageData = gcnew StringBuilder;
      int bytes = -1;
      do
      {
         
         // Read the client's test message.
         bytes = sslStream->Read( buffer, 0, buffer->Length );
         
         // Use Decoder class to convert from bytes to UTF8
         // in case a character spans two buffers.
         Decoder^ decoder = Encoding::UTF8->GetDecoder();
         array<Char>^chars = gcnew array<Char>(decoder->GetCharCount( buffer, 0, bytes ));
         decoder->GetChars( buffer, 0, bytes, chars, 0 );
         messageData->Append( chars );
         
         // Check for EOF or an empty message.
         if ( messageData->ToString()->IndexOf( L"<EOF>" ) != -1 )
         {
            break;
         }
      }
      while ( bytes != 0 );

      return messageData->ToString();
   }


   static void DisplaySecurityLevel( SslStream^ stream )
   {
      Console::WriteLine( L"Cipher: {0} strength {1}", stream->CipherAlgorithm, stream->CipherStrength );
      Console::WriteLine( L"Hash: {0} strength {1}", stream->HashAlgorithm, stream->HashStrength );
      Console::WriteLine( L"Key exchange: {0} strength {1}", stream->KeyExchangeAlgorithm, stream->KeyExchangeStrength );
      Console::WriteLine( L"Protocol: {0}", stream->SslProtocol );
   }


   static void DisplaySecurityServices( SslStream^ stream )
   {
      Console::WriteLine( L"Is authenticated: {0} as server? {1}", stream->IsAuthenticated, stream->IsServer );
      Console::WriteLine( L"IsSigned: {0}", stream->IsSigned );
      Console::WriteLine( L"Is Encrypted: {0}", stream->IsEncrypted );
   }


   static void DisplayStreamProperties( SslStream^ stream )
   {
      Console::WriteLine( L"Can read: {0}, write {1}", stream->CanRead, stream->CanWrite );
      Console::WriteLine( L"Can timeout: {0}", stream->CanTimeout );
   }


   static void DisplayCertificateInformation( SslStream^ stream )
   {
      Console::WriteLine( L"Certificate revocation list checked: {0}", stream->CheckCertRevocationStatus );
      X509Certificate^ localCertificate = stream->LocalCertificate;
      if ( stream->LocalCertificate != nullptr )
      {
         Console::WriteLine( L"Local cert was issued to {0} and is valid from {1} until {2}.", 
             localCertificate->Subject, 
             localCertificate->GetEffectiveDateString(), 
             localCertificate->GetExpirationDateString() );
      }
      else
      {
         Console::WriteLine( L"Local certificate is null." );
      }

      X509Certificate^ remoteCertificate = stream->RemoteCertificate;
      if ( stream->RemoteCertificate != nullptr )
      {
         Console::WriteLine( L"Remote cert was issued to {0} and is valid from {1} until {2}.", 
            remoteCertificate->Subject, 
            remoteCertificate->GetEffectiveDateString(), 
            remoteCertificate->GetExpirationDateString() );
      }
      else
      {
         Console::WriteLine( L"Remote certificate is null." );
      }
   }


private:

   static void DisplayUsage()
   {
      Console::WriteLine( L"To start the server specify:" );
      Console::WriteLine( L"serverSync certificateFile.cer" );
      Environment::Exit( 1 );
   }

public:
   int RunServerASync()
   {
      array<String^>^args = Environment::GetCommandLineArgs();
      String^ certificate = nullptr;
      if ( args == nullptr || args->Length < 2 )
      {
         DisplayUsage();
      }

      certificate = args[ 1 ];
      SslTcpServer::RunServer( certificate );
      return 0;
   }

};

int main(){
    SslTcpServer^ sts = gcnew SslTcpServer();
    sts->RunServerASync();
}
using System;
using System.Collections;
using System.Net;
using System.Net.Sockets;
using System.Net.Security;
using System.Security.Authentication;
using System.Text;
using System.Security.Cryptography.X509Certificates;
using System.IO;

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

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

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

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

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

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

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

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

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

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

            Try

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

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

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

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

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

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

        Private Shared Function ReadMessage(sslStream As SslStream) As String

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

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

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

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

            Return messageData.ToString()
        End Function

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

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

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

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

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

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

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

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

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

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

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

下列程式碼範例將示範如何建立 TcpClient 使用 SslStream 類別來與伺服器通訊的。The following code example demonstrates creating a TcpClient that uses the SslStream class to communicate with a server.

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

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

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

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

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

            return description;
        }

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

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

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

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

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

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

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

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

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

    return 0;
}

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

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

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

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

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

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

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

Imports System.Collections
Imports System.Net
Imports System.Net.Security
Imports System.Net.Sockets
Imports System.Security.Authentication
Imports System.Text
Imports System.Security.Cryptography.X509Certificates
Imports System.IO

Namespace Examples.System.Net

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

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

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

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

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

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

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

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

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

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

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

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

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

            Return messageData.ToString()

        End Function

        Private Shared Sub DisplayUsage()

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

        End Sub

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

            Dim serverCertificateName As String
            Dim machineName As String

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

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

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

            SslTcpClient.RunClient(machineName, serverCertificateName)

            Return 0

        End Function

    End Class

End Namespace

備註

SSL 通訊協定有助於為使用傳送的訊息提供機密性和完整性檢查 SslStreamSSL protocols help to provide confidentiality and integrity checking for messages transmitted using an SslStream. SslStream在用戶端與伺服器之間通訊機密資訊時,應使用 SSL 連線(例如提供的連接)。An SSL connection, such as that provided by SslStream, should be used when communicating sensitive information between a client and a server. 使用 SslStream 有助於防止任何人在網路上傳輸時讀取和篡改資訊。Using an SslStream helps to prevent anyone from reading and tampering with information while it is in transit on the network.

SslStream實例會使用您在建立時提供的資料流程來傳輸資料 SslStreamAn SslStream instance transmits data using a stream that you supply when creating the SslStream. 當您提供此基礎資料流程時,您可以選擇是否要關閉 SslStream 基礎資料流程。When you supply this underlying stream, you have the option to specify whether closing the SslStream also closes the underlying stream. 一般情況下, SslStream 類別會與 TcpClient 和類別搭配使用 TcpListenerTypically, the SslStream class is used with the TcpClient and TcpListener classes. GetStream方法會提供 NetworkStream 適合用於類別的 SslStreamThe GetStream method provides a NetworkStream suitable for use with the SslStream class.

建立之後 SslStream ,就必須驗證服務器,而且用戶端(選擇性)必須經過驗證。After creating an SslStream, the server and optionally, the client must be authenticated. 伺服器必須提供建立其身分識別證明的 X509 憑證,並且可以要求用戶端也這麼做。The server must provide an X509 certificate that establishes proof of its identity and can request that the client also do so. 使用傳送資訊之前,必須先執行驗證 SslStreamAuthentication must be performed before transmitting information using an SslStream. 用戶端會使用同步 AuthenticateAsClient 方法來起始驗證,這會封鎖直到驗證完成為止,或非同步 BeginAuthenticateAsClient 方法,而不會封鎖等候驗證完成。Clients initiate authentication using the synchronous AuthenticateAsClient methods, which block until the authentication completes, or the asynchronous BeginAuthenticateAsClient methods, which do not block waiting for the authentication to complete. 伺服器會使用同步 AuthenticateAsServer 或非同步方法來起始驗證 BeginAuthenticateAsServerServers initiate authentication using the synchronous AuthenticateAsServer or asynchronous BeginAuthenticateAsServer methods. 用戶端和伺服器都必須起始驗證。Both client and server must initiate the authentication.

驗證是由 (SSPI) 通道提供者的安全性支援提供者所處理。The authentication is handled by the Security Support Provider (SSPI) channel provider. 用戶端有機會在建立時,藉由指定委派來控制伺服器的憑證驗證 RemoteCertificateValidationCallback SslStreamThe client is given an opportunity to control validation of the server's certificate by specifying a RemoteCertificateValidationCallback delegate when creating an SslStream. 伺服器也可以藉由提供委派來控制驗證 RemoteCertificateValidationCallbackThe server can also control validation by supplying a RemoteCertificateValidationCallback delegate. 委派所參考的方法包括遠端方的憑證,以及在驗證憑證時發現的任何錯誤。The method referenced by the delegate includes the remote party's certificate and any errors SSPI encountered while validating the certificate. 請注意,如果伺服器指定委派,不論伺服器是否要求用戶端驗證,都會叫用委派的方法。Note that if the server specifies a delegate, the delegate's method is invoked regardless of whether the server requested client authentication. 如果伺服器未要求用戶端驗證,伺服器的委派方法會收到 null 憑證和憑證錯誤的空陣列。If the server did not request client authentication, the server's delegate method receives a null certificate and an empty array of certificate errors.

如果伺服器需要用戶端驗證,則用戶端必須指定一或多個憑證以進行驗證。If the server requires client authentication, the client must specify one or more certificates for authentication. 如果用戶端有一個以上的憑證,用戶端可以提供 LocalCertificateSelectionCallback 委派來選取伺服器的正確憑證。If the client has more than one certificate, the client can provide a LocalCertificateSelectionCallback delegate to select the correct certificate for the server. 用戶端的憑證必須位於目前使用者的「我的」憑證存放區中。The client's certificates must be located in the current user's "My" certificate store. Ssl2 (SSL 第2版) 通訊協定不支援透過憑證進行用戶端驗證。Client authentication via certificates is not supported for the Ssl2 (SSL version 2) protocol.

如果驗證失敗,您會收到 AuthenticationException ,且已不再 SslStream 可用。If the authentication fails, you receive a AuthenticationException, and the SslStream is no longer useable. 您應該關閉這個物件,並移除對它的所有參考,讓垃圾收集行程可以收集它。You should close this object and remove all references to it so that it can be collected by the garbage collector.

當驗證程式(也稱為 SSL 交握)成功時,伺服器的身分識別 (,並選擇性地建立用戶端) ,而且 SslStream 用戶端和伺服器可以使用來交換訊息。When the authentication process, also known as the SSL handshake, succeeds, the identity of the server (and optionally, the client) is established and the SslStream can be used by the client and server to exchange messages. 在傳送或接收資訊之前,用戶端和伺服器應該檢查所提供的安全性服務和層級, SslStream 以判斷選取的通訊協定、演算法和強度是否符合其完整性和機密性的需求。Before sending or receiving information, the client and server should check the security services and levels provided by the SslStream to determine whether the protocol, algorithms, and strengths selected meet their requirements for integrity and confidentiality. 如果目前的設定不足,則應該關閉資料流程。If the current settings are not sufficient, the stream should be closed. 您可以 SslStream 使用和屬性檢查所提供的安全性服務 IsEncrypted IsSignedYou can check the security services provided by the SslStream using the IsEncrypted and IsSigned properties. 下表顯示的元素會報告用於驗證、加密和資料簽署的密碼編譯設定。The following table shows the elements that report the cryptographic settings used for authentication, encryption and data signing.

項目Element 成員Members
用來驗證服務器和用戶端(選擇性)的安全性通訊協定。The security protocol used to authenticate the server and, optionally, the client. SslProtocol屬性和相關聯的 SslProtocols 列舉。The SslProtocol property and the associated SslProtocols enumeration.
金鑰交換演算法。The key exchange algorithm. KeyExchangeAlgorithm屬性和相關聯的 ExchangeAlgorithmType 列舉。The KeyExchangeAlgorithm property and the associated ExchangeAlgorithmType enumeration.
訊息完整性演算法。The message integrity algorithm. HashAlgorithm屬性和相關聯的 HashAlgorithmType 列舉。The HashAlgorithm property and the associated HashAlgorithmType enumeration.
訊息機密性演算法。The message confidentiality algorithm. CipherAlgorithm屬性和相關聯的 CipherAlgorithmType 列舉。The CipherAlgorithm property and the associated CipherAlgorithmType enumeration.
所選演算法的強度。The strengths of the selected algorithms. KeyExchangeStrengthHashStrengthCipherStrength 屬性。The KeyExchangeStrength, HashStrength, and CipherStrength properties.

成功驗證之後,您就可以使用同步 Write 或非同步方法來傳送資料 BeginWriteAfter a successful authentication, you can send data using the synchronous Write or asynchronous BeginWrite methods. 您可以使用同步 Read 或非同步方法來接收資料 BeginReadYou can receive data using the synchronous Read or asynchronous BeginRead methods.

如果您指定要 SslStream 讓基礎資料流程保持開啟,您必須負責在使用完畢之後關閉該資料流程。If you specified to the SslStream that the underlying stream should be left open, you are responsible for closing that stream when you are done using it.

注意

如果建立物件的應用程式是 SslStream 以一般使用者的認證來執行,除非使用者明確指定許可權,否則應用程式將無法存取本機電腦存放區中安裝的憑證。If the application that creates the SslStream object runs with the credentials of a Normal user, the application will not be able to access certificates installed in the local machine store unless permission has been explicitly given to the user to do so.

SslStream 假設從內部資料流程擲回某個超時時間和任何其他時間,將會被 IOException 其呼叫端視為嚴重。SslStream assumes that a timeout along with any other IOException when one is thrown from the inner stream will be treated as fatal by its caller. SslStream在 timeout 之後重複使用實例將會傳回垃圾。Reusing a SslStream instance after a timeout will return garbage. 應用程式應該 CloseSslStream 在這些情況下擲回例外狀況。An application should Close the SslStream and throw an exception in these cases.

.NET Framework 4.6 包含新的安全性功能,可封鎖連接不安全的加密和雜湊演算法。The .NET Framework 4.6 includes a new security feature that blocks insecure cipher and hashing algorithms for connections. 透過 HttpClient、HttpWebRequest、FTPClient、System.net.mail.smtpclient、SslStream 等 Api 使用 TLS/SSL 的應用程式,以及以 .NET Framework 4.6 為目標的應用程式,預設會取得更安全的行為。Applications using TLS/SSL through APIs such as HttpClient, HttpWebRequest, FTPClient, SmtpClient, SslStream, etc. and targeting .NET Framework 4.6 get the more-secure behavior by default.

開發人員可能會想要選擇不使用這種行為,以便維持與現有 SSL3 服務或 TLS (含 RC4 服務)的互通性。Developers may want to opt out of this behavior in order to maintain interoperability with their existing SSL3 services OR TLS w/ RC4 services. 本文說明如何 修改您的程式碼,以停用新的行為。This article explains how to modify your code so that the new behavior is disabled.

.NET Framework 4.7 新增方法的新多載,這些方法會驗證未指定 TLS 版本的 SslStreams,但改為使用定義為 SCHANNEL中系統預設值的 TLS 版本。The .NET Framework 4.7 adds new overloads for the methods that authenticate SslStreams that do not specify a TLS version, but instead use the TLS version defined as the system default in SCHANNEL. 在您的應用程式中使用這些方法,可讓您在稍後修改預設值,因為 TLS 版本的最佳作法會隨著時間變更,而不需要重建和重新部署您的應用程式。Use these methods in your app as a way to be able to later modify the defaults as TLS version best practice changes over time, without the need to rebuild and redeploy your app.

另請參閱 傳輸層安全性 (TLS) 使用 .NET Framework 的最佳做法Also see Transport Layer Security (TLS) best practices with the .NET Framework.

建構函式

SslStream(Stream)

使用指定的 SslStream,初始化 Stream 類別的新執行個體。Initializes a new instance of the SslStream class using the specified Stream.

SslStream(Stream, Boolean)

使用指定的 SslStream 和資料流結束行為,初始化 Stream 類別的新執行個體。Initializes a new instance of the SslStream class using the specified Stream and stream closure behavior.

SslStream(Stream, Boolean, RemoteCertificateValidationCallback)

使用指定的 SslStream、資料流結束行為以及憑證驗證委派,初始化 Stream 類別的新執行個體。Initializes a new instance of the SslStream class using the specified Stream, stream closure behavior and certificate validation delegate.

SslStream(Stream, Boolean, RemoteCertificateValidationCallback, LocalCertificateSelectionCallback)

使用指定的 SslStream、資料流結束行為、憑證驗證委派及憑證選取委派,初始化 Stream 類別的新執行個體。Initializes a new instance of the SslStream class using the specified Stream, stream closure behavior, certificate validation delegate and certificate selection delegate.

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

使用指定的 SslStream 來初始化 Stream 類別的新執行個體。Initializes a new instance of the SslStream class using the specified Stream

屬性

CanRead

取得 Boolean 值,指示基礎資料流是否可讀取。Gets a Boolean value that indicates whether the underlying stream is readable.

CanSeek

取得 Boolean 值,指示基礎資料流是否可搜尋。Gets a Boolean value that indicates whether the underlying stream is seekable.

CanTimeout

取得 Boolean 值,指示基礎資料流是否支援逾時。Gets a Boolean value that indicates whether the underlying stream supports time-outs.

CanWrite

取得 Boolean 值,指示基礎資料流是否可寫入。Gets a Boolean value that indicates whether the underlying stream is writable.

CheckCertRevocationStatus

取得 Boolean 值,指出在憑證驗證處理期間是否檢查憑證撤銷清單。Gets a Boolean value that indicates whether the certificate revocation list is checked during the certificate validation process.

CipherAlgorithm

取得值,識別這個 SslStream 所用的大量加密演算法。Gets a value that identifies the bulk encryption algorithm used by this SslStream.

CipherStrength

取得值,識別這個 SslStream 所用之加密演算法的強度。Gets a value that identifies the strength of the cipher algorithm used by this SslStream.

HashAlgorithm

取得用於產生訊息驗證碼 (MAC) 的演算法。Gets the algorithm used for generating message authentication codes (MACs).

HashStrength

取得值,識別這個執行個體所用之雜湊演算法的強度。Gets a value that identifies the strength of the hash algorithm used by this instance.

InnerStream

取得這個 AuthenticatedStream 用來傳送和接收資料的資料流。Gets the stream used by this AuthenticatedStream for sending and receiving data.

(繼承來源 AuthenticatedStream)
IsAuthenticated

取得 Boolean 值,指示驗證是否成功。Gets a Boolean value that indicates whether authentication was successful.

IsEncrypted

取得 Boolean 值,指示這個 SslStream 是否使用資料加密。Gets a Boolean value that indicates whether this SslStream uses data encryption.

IsMutuallyAuthenticated

取得 Boolean 值,指示伺服器和用戶端是否都已驗證。Gets a Boolean value that indicates whether both server and client have been authenticated.

IsServer

取得 Boolean 值,指示這個 SslStream 使用之連接的本機端是否以伺服器的身分驗證。Gets a Boolean value that indicates whether the local side of the connection used by this SslStream was authenticated as the server.

IsSigned

取得 Boolean 值,指示使用此資料流傳送的資料是否簽章。Gets a Boolean value that indicates whether the data sent using this stream is signed.

KeyExchangeAlgorithm

取得這個 SslStream 所用的金鑰交換演算法。Gets the key exchange algorithm used by this SslStream.

KeyExchangeStrength

取得值,識別這個執行個體所用之金鑰交換演算法的強度。Gets a value that identifies the strength of the key exchange algorithm used by this instance.

LeaveInnerStreamOpen

取得這個 AuthenticatedStream 用來傳送和接收資料的資料流是否保持開啟狀態。Gets whether the stream used by this AuthenticatedStream for sending and receiving data has been left open.

(繼承來源 AuthenticatedStream)
Length

取得基礎資料流的長度。Gets the length of the underlying stream.

LocalCertificate

取得用於驗證本機端點的憑證。Gets the certificate used to authenticate the local endpoint.

NegotiatedApplicationProtocol

TLS 信號交換中交涉的應用程式通訊協定。The negotiated application protocol in TLS handshake.

NegotiatedCipherSuite

取得用於交涉此連線的加密套件。Gets the cipher suite which was negotiated for this connection.

Position

取得或設定基礎資料流中目前的位置。Gets or sets the current position in the underlying stream.

ReadTimeout

取得或設定讀取作業禁止等待資料的時間量 (以毫秒表示)。Gets or sets the amount of time, expressed in milliseconds, a read operation blocks waiting for data.

RemoteCertificate

取得用於驗證遠端端點的憑證。Gets the certificate used to authenticate the remote endpoint.

SslProtocol

取得值,指示用於驗證此連接的安全性通訊協定。Gets a value that indicates the security protocol used to authenticate this connection.

TargetHostName

取得用戶端嘗試連接的伺服器名稱。Gets the name of the server the client is trying to connect to. 用於伺服器憑證驗證的名稱。That name is used for server certificate validation. 可為 DNS 名稱或 IP 位址。It can be a DNS name or an IP address.

TransportContext

取得在使用延伸保護時用來驗證的 TransportContextGets the TransportContext used for authentication using extended protection.

WriteTimeout

取得或設定寫入作業封鎖等待資料的時間長度。Gets or sets the amount of time a write operation blocks waiting for data.

方法

AuthenticateAsClient(SslClientAuthenticationOptions)

已由用戶端呼叫來在用戶端與伺服器連線中驗證伺服器和用戶端 (選擇性)。Called by clients to authenticate the server and optionally the client in a client-server connection.

AuthenticateAsClient(String)

已由用戶端呼叫來在用戶端與伺服器連線中驗證伺服器和用戶端 (選擇性)。Called by clients to authenticate the server and optionally the client in a client-server connection.

AuthenticateAsClient(String, X509CertificateCollection, Boolean)

已由用戶端呼叫來在用戶端與伺服器連線中驗證伺服器和用戶端 (選擇性)。Called by clients to authenticate the server and optionally the client in a client-server connection. 驗證程序會使用指定的憑證集合物件和系統預設的 SSL 通訊協定。The authentication process uses the specified certificate collection, and the system default SSL protocol.

AuthenticateAsClient(String, X509CertificateCollection, SslProtocols, Boolean)

已由用戶端呼叫來在用戶端與伺服器連線中驗證伺服器和用戶端 (選擇性)。Called by clients to authenticate the server and optionally the client in a client-server connection. 驗證處理序使用指定的憑證集合和 SSL 通訊協定。The authentication process uses the specified certificate collection and SSL protocol.

AuthenticateAsClientAsync(SslClientAuthenticationOptions, CancellationToken)

已由用戶端呼叫,以非同步作業方式在用戶端與伺服器連線中驗證伺服器和用戶端 (選擇性)。Called by clients to authenticate the server and optionally the client in a client-server connection as an asynchronous operation. 驗證程序會使用 sslClientAuthenticationOptions 屬性包中所指定的資訊。The authentication process uses information specified in the sslClientAuthenticationOptions property bag.

AuthenticateAsClientAsync(String)

已由用戶端呼叫,以非同步作業方式在用戶端與伺服器連線中驗證伺服器和用戶端 (選擇性)。Called by clients to authenticate the server and optionally the client in a client-server connection as an asynchronous operation.

AuthenticateAsClientAsync(String, X509CertificateCollection, Boolean)

已由用戶端呼叫,以非同步作業方式在用戶端與伺服器連線中驗證伺服器和用戶端 (選擇性)。Called by clients to authenticate the server and optionally the client in a client-server connection as an asynchronous operation. 驗證程序會使用指定的憑證集合物件和系統預設的 SSL 通訊協定。The authentication process uses the specified certificate collection and the system default SSL protocol.

AuthenticateAsClientAsync(String, X509CertificateCollection, SslProtocols, Boolean)

已由用戶端呼叫,以非同步作業方式在用戶端與伺服器連線中驗證伺服器和用戶端 (選擇性)。Called by clients to authenticate the server and optionally the client in a client-server connection as an asynchronous operation. 驗證處理序使用指定的憑證集合和 SSL 通訊協定。The authentication process uses the specified certificate collection and SSL protocol.

AuthenticateAsServer(SslServerAuthenticationOptions)

由伺服器呼叫,以使用指定的憑證來驗證用戶端與伺服器連接中的伺服器及 (選擇性地驗證) 用戶端。Called by servers to authenticate the server and optionally the client in a client-server connection using the specified certificate.

AuthenticateAsServer(X509Certificate)

由伺服器呼叫,以使用指定的憑證來驗證用戶端與伺服器連接中的伺服器及 (選擇性地驗證) 用戶端。Called by servers to authenticate the server and optionally the client in a client-server connection using the specified certificate.

AuthenticateAsServer(X509Certificate, Boolean, Boolean)

已由伺服器呼叫,使用指定的憑證和需求,以及使用系統預設安全性通訊協定,來驗證用戶端與伺服器連線中的伺服器和用戶端 (選擇性)。Called by servers to authenticate the server and optionally the client in a client-server connection using the specified certificates and requirements, and using the system default security protocol.

AuthenticateAsServer(X509Certificate, Boolean, SslProtocols, Boolean)

已由伺服器呼叫,使用指定的憑證、需求及安全性通訊協定,來驗證伺服器和用戶端伺服器連線中的用戶端 (選擇性)。Called by servers to authenticate the server and optionally the client in a client-server connection using the specified certificates, requirements and security protocol.

AuthenticateAsServerAsync(ServerOptionsSelectionCallback, Object, CancellationToken)

由伺服器呼叫做為非同步作業,以驗證用戶端與伺服器連接中的伺服器,並選擇性地驗證用戶端。Called by servers to authenticate the server and optionally the client in a client-server connection as an asynchronous operation. 驗證程序會使用 optionsCallback 傳回的資訊。The authentication process uses information returned by optionsCallback.

AuthenticateAsServerAsync(SslServerAuthenticationOptions, CancellationToken)

由伺服器呼叫做為非同步作業,以驗證用戶端與伺服器連接中的伺服器,並選擇性地驗證用戶端。Called by servers to authenticate the server and optionally the client in a client-server connection as an asynchronous operation. 驗證程序會使用 sslClientAuthenticationOptions 屬性包中所指定的資訊。The authentication process uses information specified in the sslClientAuthenticationOptions property bag.

AuthenticateAsServerAsync(X509Certificate)

由伺服器呼叫做為非同步作業,以使用指定的憑證來驗證用戶端與伺服器連接中的伺服器,並選擇性地驗證用戶端。Called by servers to authenticate the server and optionally the client in a client-server connection using the specified certificate as an asynchronous operation.

AuthenticateAsServerAsync(X509Certificate, Boolean, Boolean)

已由伺服器呼叫,使用指定的憑證、需求及安全性通訊協定做為非同步作業,來驗證伺服器和用戶端伺服器連線中的用戶端 (選擇性)。Called by servers to authenticate the server and optionally the client in a client-server connection using the specified certificates, requirements and security protocol as an asynchronous operation.

AuthenticateAsServerAsync(X509Certificate, Boolean, SslProtocols, Boolean)

已由伺服器呼叫,使用指定的憑證、需求及安全性通訊協定做為非同步作業,來驗證伺服器和用戶端伺服器連線中的用戶端 (選擇性)。Called by servers to authenticate the server and optionally the client in a client-server connection using the specified certificates, requirements and security protocol as an asynchronous operation.

BeginAuthenticateAsClient(String, AsyncCallback, Object)

由用戶端呼叫以開始非同步作業,驗證伺服器及 (選擇性地驗證) 用戶端。Called by clients to begin an asynchronous operation to authenticate the server and optionally the client.

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

已由用戶端呼叫來開始非同步作業,以使用指定的憑證和系統預設安全性通訊協定來驗證伺服器和用戶端 (選擇性)。Called by clients to begin an asynchronous operation to authenticate the server and optionally the client using the specified certificates and the system default security protocol.

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

由用戶端呼叫以開始非同步作業,使用指定的憑證和安全性通訊協定來驗證伺服器及 (選擇性地驗證) 用戶端。Called by clients to begin an asynchronous operation to authenticate the server and optionally the client using the specified certificates and security protocol.

BeginAuthenticateAsServer(X509Certificate, AsyncCallback, Object)

由伺服器呼叫以開始非同步作業,驗證用戶端與伺服器連接中的用戶端及 (選擇性地驗證) 伺服器。Called by servers to begin an asynchronous operation to authenticate the client and optionally the server in a client-server connection.

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

已由伺服器呼叫來開始非同步作業,以使用指定的憑證、需求及系統預設安全性通訊協定來驗證伺服器和用戶端 (選擇性)。Called by servers to begin an asynchronous operation to authenticate the server and optionally the client using the specified certificates and requirements, and the system default security protocol.

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

已由伺服器呼叫來開始非同步作業,以使用指定的憑證、需求及安全性通訊協定來驗證伺服器和用戶端 (選擇性)。Called by servers to begin an asynchronous operation to authenticate the server and optionally the client using the specified certificates, requirements and security protocol.

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

開始非同步讀取作業,這個作業會從資料流中讀取資料並將其儲存於指定的陣列中。Begins an asynchronous read operation that reads data from the stream and stores it in the specified array.

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

開始非同步的讀取作業。Begins an asynchronous read operation. (請考慮用 ReadAsync(Byte[], Int32, Int32) 替代。)(Consider using ReadAsync(Byte[], Int32, Int32) instead.)

(繼承來源 Stream)
BeginWrite(Byte[], Int32, Int32, AsyncCallback, Object)

開始非同步寫入作業,此作業會從指定的緩衝區寫入 Byte 至資料流。Begins an asynchronous write operation that writes Bytes from the specified buffer to the stream.

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

開始非同步的寫入作業。Begins an asynchronous write operation. (請考慮用 WriteAsync(Byte[], Int32, Int32) 替代。)(Consider using WriteAsync(Byte[], Int32, Int32) instead.)

(繼承來源 Stream)
Close()

關閉目前資料流和釋放與目前資料流相關聯的任何資源 (例如通訊端和檔案控制代碼)。Closes the current stream and releases any resources (such as sockets and file handles) associated with the current stream. 請確定正確地處置資料流,而非呼叫這個方法。Instead of calling this method, ensure that the stream is properly disposed.

(繼承來源 Stream)
CopyTo(Stream)

從目前資料流讀取位元組,並將其寫入另一個資料流中。Reads the bytes from the current stream and writes them to another stream.

(繼承來源 Stream)
CopyTo(Stream, Int32)

使用指定的緩衝區大小,從目前資料流讀取所有位元組,並將其寫入另一個資料流中。Reads the bytes from the current stream and writes them to another stream, using a specified buffer size.

(繼承來源 Stream)
CopyToAsync(Stream)

以非同步的方式從目前資料流讀取所有位元組,並將其寫入另一個資料流中。Asynchronously reads the bytes from the current stream and writes them to another stream.

(繼承來源 Stream)
CopyToAsync(Stream, CancellationToken)

使用指定的取消權杖,以非同步的方式從目前資料流讀取位元組,並將其寫入另一個資料流。Asynchronously reads the bytes from the current stream and writes them to another stream, using a specified cancellation token.

(繼承來源 Stream)
CopyToAsync(Stream, Int32)

使用指定的緩衝區大小,以非同步的方式從目前資料流讀取所有位元組,並將其寫入另一個資料流中。Asynchronously reads the bytes from the current stream and writes them to another stream, using a specified buffer size.

(繼承來源 Stream)
CopyToAsync(Stream, Int32, CancellationToken)

使用指定的緩衝區大小和取消語彙基元,以非同步的方式從目前資料流讀取位元組,並將其寫入另一個資料流。Asynchronously reads the bytes from the current stream and writes them to another stream, using a specified buffer size and cancellation token.

(繼承來源 Stream)
CreateObjRef(Type)

建立包含所有相關資訊的物件,這些資訊是產生用來與遠端物件通訊的所需 Proxy。Creates an object that contains all the relevant information required to generate a proxy used to communicate with a remote object.

(繼承來源 MarshalByRefObject)
CreateWaitHandle()
已過時。

配置 WaitHandle 物件。Allocates a WaitHandle object.

(繼承來源 Stream)
Dispose()

釋放 Stream 所使用的所有資源。Releases all resources used by the Stream.

(繼承來源 Stream)
Dispose(Boolean)

釋放 SslStream 所使用的 Unmanaged 資源,並選擇性地釋放 Managed 資源。Releases the unmanaged resources used by the SslStream and optionally releases the managed resources.

Dispose(Boolean)

釋放 AuthenticatedStream 所使用的 Unmanaged 資源,並選擇性地釋放 Managed 資源。Releases the unmanaged resources used by the AuthenticatedStream and optionally releases the managed resources.

(繼承來源 AuthenticatedStream)
DisposeAsync()

以非同步方式釋放 SslStream 使用的非受控與受控資源。Asynchronously releases the unmanaged and managed resources used by the SslStream.

DisposeAsync()

以非同步方式釋放 AuthenticatedStream 使用的非受控與受控資源。Asynchronously releases the unmanaged and managed resources used by the AuthenticatedStream.

(繼承來源 AuthenticatedStream)
EndAuthenticateAsClient(IAsyncResult)

結束由先前呼叫 BeginAuthenticateAsClient 所開始的暫止非同步伺服器驗證作業。Ends a pending asynchronous server authentication operation started with a previous call to BeginAuthenticateAsClient.

EndAuthenticateAsServer(IAsyncResult)

結束由先前呼叫 BeginAuthenticateAsClient 所開始的暫止非同步用戶端驗證作業。Ends a pending asynchronous client authentication operation started with a previous call to BeginAuthenticateAsClient.

EndRead(IAsyncResult)

結束由先前呼叫 BeginRead(Byte[], Int32, Int32, AsyncCallback, Object) 所開始的非同步讀取作業。Ends an asynchronous read operation started with a previous call to BeginRead(Byte[], Int32, Int32, AsyncCallback, Object).

EndRead(IAsyncResult)

等候暫止的非同步讀取完成。Waits for the pending asynchronous read to complete. (請考慮用 ReadAsync(Byte[], Int32, Int32) 替代。)(Consider using ReadAsync(Byte[], Int32, Int32) instead.)

(繼承來源 Stream)
EndWrite(IAsyncResult)

結束由先前呼叫 BeginWrite(Byte[], Int32, Int32, AsyncCallback, Object) 所開始的非同步寫入作業。Ends an asynchronous write operation started with a previous call to BeginWrite(Byte[], Int32, Int32, AsyncCallback, Object).

EndWrite(IAsyncResult)

結束非同步的寫入作業。Ends an asynchronous write operation. (請考慮用 WriteAsync(Byte[], Int32, Int32) 替代。)(Consider using WriteAsync(Byte[], Int32, Int32) instead.)

(繼承來源 Stream)
Equals(Object)

判斷指定的物件是否等於目前的物件。Determines whether the specified object is equal to the current object.

(繼承來源 Object)
Finalize()

釋放 SslStream 所使用的所有資源。Releases all resources used by the SslStream.

Flush()

造成任何緩衝資料都將寫入基礎裝置。Causes any buffered data to be written to the underlying device.

FlushAsync()

以非同步的方式清除這個資料流的所有緩衝區,並造成所有緩衝資料都寫入基礎裝置。Asynchronously clears all buffers for this stream and causes any buffered data to be written to the underlying device.

(繼承來源 Stream)
FlushAsync(CancellationToken)

將任何緩衝資料以非同步方式寫入底層裝置。Asynchronously writes any buffered data to the underlying device.

FlushAsync(CancellationToken)

以非同步的方式清除這個資料流的所有緩衝區,造成所有緩衝資料都寫入基礎裝置,並且監視取消要求。Asynchronously clears all buffers for this stream, causes any buffered data to be written to the underlying device, and monitors cancellation requests.

(繼承來源 Stream)
GetHashCode()

做為預設雜湊函式。Serves as the default hash function.

(繼承來源 Object)
GetLifetimeService()

擷取控制這個執行個體存留期 (Lifetime) 原則的目前存留期服務物件。Retrieves the current lifetime service object that controls the lifetime policy for this instance.

(繼承來源 MarshalByRefObject)
GetType()

取得目前執行個體的 TypeGets the Type of the current instance.

(繼承來源 Object)
InitializeLifetimeService()

取得存留期服務物件,以控制這個執行個體的存留期原則。Obtains a lifetime service object to control the lifetime policy for this instance.

(繼承來源 MarshalByRefObject)
MemberwiseClone()

建立目前 Object 的淺層複製。Creates a shallow copy of the current Object.

(繼承來源 Object)
MemberwiseClone(Boolean)

建立目前 MarshalByRefObject 物件的淺層複本。Creates a shallow copy of the current MarshalByRefObject object.

(繼承來源 MarshalByRefObject)
ObjectInvariant()
已過時。

提供 Contract 的支援。Provides support for a Contract.

(繼承來源 Stream)
Read(Byte[], Int32, Int32)

從這個資料流中讀取資料並將其儲存於指定的陣列中。Reads data from this stream and stores it in the specified array.

Read(Span<Byte>)

當在衍生類別中覆寫時,自目前資料流讀取一連串的位元組,並依所讀取的位元組數目進階資料流中的位置。When overridden in a derived class, reads a sequence of bytes from the current stream and advances the position within the stream by the number of bytes read.

(繼承來源 Stream)
ReadAsync(Byte[], Int32, Int32)

以非同步的方式從目前的資料流讀取位元組序列,並依讀取的位元組數將資料流中的位置往前移。Asynchronously reads a sequence of bytes from the current stream and advances the position within the stream by the number of bytes read.

(繼承來源 Stream)
ReadAsync(Byte[], Int32, Int32, CancellationToken)

以非同步方式從這個資料流中讀取資料,並將其儲存在指定的位元組陣列範圍中。Asynchronously reads data from this stream and stores it in the specified range of a byte array.

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

以非同步的方式從目前資料流讀取一連串的位元組、依所讀取的位元組數目進階資料流中的位置,以及監視取消要求。Asynchronously reads a sequence of bytes from the current stream, advances the position within the stream by the number of bytes read, and monitors cancellation requests.

(繼承來源 Stream)
ReadAsync(Memory<Byte>, CancellationToken)

以非同步方式從這個資料流中讀取資料,並將其儲存於指定的記憶體範圍中。Asynchronously reads data from this stream and stores it in the specified memory range.

ReadAsync(Memory<Byte>, CancellationToken)

以非同步的方式從目前資料流讀取一連串的位元組、依所讀取的位元組數目進階資料流中的位置,以及監視取消要求。Asynchronously reads a sequence of bytes from the current stream, advances the position within the stream by the number of bytes read, and monitors cancellation requests.

(繼承來源 Stream)
ReadByte()

SslStream 讀取一個位元組,並將資料流的位置推進一個位元組;如果在資料流末端,則傳回 -1。Reads a byte from the SslStream and advances the position within the stream by one byte, or returns -1 if at the end of the stream.

ReadByte()

從資料流讀取一個位元組,並將資料流的位置推進一個位元組;如果在資料流末端,則傳回 -1。Reads a byte from the stream and advances the position within the stream by one byte, or returns -1 if at the end of the stream.

(繼承來源 Stream)
Seek(Int64, SeekOrigin)

擲回 NotSupportedExceptionThrows a NotSupportedException.

SetLength(Int64)

設定基礎資料流的長度。Sets the length of the underlying stream.

ShutdownAsync()

關閉這個 SslStream。Shuts down this SslStream.

ToString()

傳回代表目前物件的字串。Returns a string that represents the current object.

(繼承來源 Object)
Write(Byte[])

寫入指定的資料至此資料流。Writes the specified data to this stream.

Write(Byte[], Int32, Int32)

使用指定的緩衝區和位移,將指定數目的 Byte 寫入至基礎資料流。Write the specified number of Bytes to the underlying stream using the specified buffer and offset.

Write(ReadOnlySpan<Byte>)

在衍生類別中覆寫時,將一連串的位元組寫入目前的資料流,並且由這個資料流中目前的位置前移寫入的位元組數目。When overridden in a derived class, writes a sequence of bytes to the current stream and advances the current position within this stream by the number of bytes written.

(繼承來源 Stream)
WriteAsync(Byte[], Int32, Int32)

以非同步的方式將位元組序列寫入至目前的資料流,並依寫入的位元組數將資料流中目前的位置往前移。Asynchronously writes a sequence of bytes to the current stream and advances the current position within this stream by the number of bytes written.

(繼承來源 Stream)
WriteAsync(Byte[], Int32, Int32, CancellationToken)

以非同步方式,將資料從指定的位元組陣列範圍寫入基礎資料流。Asynchronously writes data to the underlying stream from the specified range of a byte array.

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

以非同步的方式將一連串的位元組寫入目前的資料流,由這個資料流中目前的位置前移寫入的位元組數目,並且監視取消要求。Asynchronously writes a sequence of bytes to the current stream, advances the current position within this stream by the number of bytes written, and monitors cancellation requests.

(繼承來源 Stream)
WriteAsync(ReadOnlyMemory<Byte>, CancellationToken)

以非同步方式,從唯讀位元組記憶體範圍將資料寫入基礎資料流。Asynchronously writes data to the underlying stream from a read-only byte memory range.

WriteAsync(ReadOnlyMemory<Byte>, CancellationToken)

以非同步的方式將一連串的位元組寫入目前的資料流,由這個資料流中目前的位置前移寫入的位元組數目,並且監視取消要求。Asynchronously writes a sequence of bytes to the current stream, advances the current position within this stream by the number of bytes written, and monitors cancellation requests.

(繼承來源 Stream)
WriteByte(Byte)

寫入一個位元組至資料流的目前位置,並將資料流位置推進一個位元組。Writes a byte to the current position in the stream and advances the position within the stream by one byte.

(繼承來源 Stream)

明確介面實作

IDisposable.Dispose()

釋放 Stream 所使用的所有資源。Releases all resources used by the Stream.

(繼承來源 Stream)

擴充方法

ConfigureAwait(IAsyncDisposable, Boolean)

設定如何執行從非同步可處置項目傳回的工作 await。Configures how awaits on the tasks returned from an async disposable are performed.

適用於

另請參閱