Share via


SslStream Kelas

Definisi

Menyediakan aliran yang digunakan untuk komunikasi server klien yang menggunakan protokol keamanan Secure Socket Layer (SSL) untuk mengautentikasi server dan secara opsional klien.

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

Contoh

Contoh kode berikut menunjukkan pembuatan TcpListener yang menggunakan SslStream kelas untuk berkomunikasi dengan klien.

#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,5000 );
      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 );
      Console::WriteLine( L"Is mutually authenticated: {0}", stream->IsMutuallyAuthenticated );
   }


   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, 5000);
            listener.Start();
            while (true)
            {
                Console.WriteLine("Waiting for a client to connect...");
                // Application blocks while waiting for an incoming connection.
                // Type CNTL-C to terminate the server.
                TcpClient client = listener.AcceptTcpClient();
                ProcessClient(client);
            }
        }
        static void ProcessClient (TcpClient client)
        {
            // A client has connected. Create the
            // SslStream using the client's network stream.
            SslStream sslStream = new SslStream(
                client.GetStream(), false);
            // Authenticate the server but don't require the client to authenticate.
            try
            {
                sslStream.AuthenticateAsServer(serverCertificate, clientCertificateRequired: false, checkCertificateRevocation: true);

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

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

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

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

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

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

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

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

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

            Try

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

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

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

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

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

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

        Private Shared Function ReadMessage(sslStream As SslStream) As String

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

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

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

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

            Return messageData.ToString()
        End Function

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

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

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

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

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

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

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

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

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

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

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

Contoh kode berikut menunjukkan pembuatan TcpClient yang menggunakan SslStream kelas untuk berkomunikasi dengan 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, 5000);
            Console::WriteLine("Client connected.");
              
            // Create an SSL stream that will close 
            // the client's stream.
            SslStream^ sslStream = gcnew SslStream(
                client->GetStream(), false,
                gcnew RemoteCertificateValidationCallback(ValidateServerCertificate),
                nullptr);
              
            // The server name must match the name
            // on the server certificate.
            try
            {
                sslStream->AuthenticateAsClient(serverName);
            }
            catch (AuthenticationException^ ex) 
            {
                Console::WriteLine("Exception: {0}", ex->Message);
                if (ex->InnerException != nullptr)
                {
                    Console::WriteLine("Inner exception: {0}", 
                        ex->InnerException->Message);
                }

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

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

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

Namespace Examples.System.Net

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

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

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

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

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

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

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

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

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

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

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

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

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

            Return messageData.ToString()

        End Function

        Private Shared Sub DisplayUsage()

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

        End Sub

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

            Dim serverCertificateName As String
            Dim machineName As String

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

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

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

            SslTcpClient.RunClient(machineName, serverCertificateName)

            Return 0

        End Function

    End Class

End Namespace

Keterangan

Protokol SSL membantu memberikan pemeriksaan kerahasiaan dan integritas untuk pesan yang dikirimkan menggunakan SslStream. Koneksi SSL, seperti yang disediakan oleh SslStream, harus digunakan saat berkomunikasi informasi sensitif antara klien dan server. SslStream Menggunakan bantuan untuk mencegah siapa pun membaca dan mengubah informasi saat transit di jaringan.

Instans SslStream mengirimkan data menggunakan aliran yang Anda berikan saat membuat SslStream. Saat Anda menyediakan aliran yang mendasar SslStream ini, Anda memiliki opsi untuk menentukan apakah menutup juga menutup aliran yang mendasar. Biasanya, SslStream kelas digunakan dengan TcpClient kelas dan TcpListener . Metode ini GetStream menyediakan yang NetworkStream cocok untuk digunakan dengan SslStream kelas .

Setelah membuat SslStream, server dan secara opsional, klien harus diautentikasi. Server harus menyediakan sertifikat X509 yang menetapkan bukti identitasnya dan dapat meminta klien juga melakukannya. Autentikasi harus dilakukan sebelum mengirimkan informasi menggunakan SslStream. Klien memulai autentikasi menggunakan metode sinkron AuthenticateAsClient , yang memblokir hingga autentikasi selesai, atau metode asinkron BeginAuthenticateAsClient , yang tidak memblokir menunggu autentikasi selesai. Server memulai autentikasi menggunakan metode sinkron AuthenticateAsServer atau asinkron BeginAuthenticateAsServer . Klien dan server harus memulai autentikasi.

Autentikasi ditangani oleh penyedia saluran Penyedia Dukungan Keamanan (SSPI). Klien diberi kesempatan untuk mengontrol validasi sertifikat server dengan menentukan RemoteCertificateValidationCallback delegasi saat membuat SslStream. Server juga dapat mengontrol validasi dengan menyediakan RemoteCertificateValidationCallback delegasi. Metode yang direferensikan oleh delegasi mencakup sertifikat pihak jarak jauh dan kesalahan apa pun yang ditemui SSPI saat memvalidasi sertifikat. Perhatikan bahwa jika server menentukan delegasi, metode delegasi dipanggil terlepas dari apakah server meminta autentikasi klien. Jika server tidak meminta autentikasi klien, metode delegasi server menerima sertifikat null dan array kesalahan sertifikat kosong.

Jika server memerlukan autentikasi klien, klien harus menentukan satu atau beberapa sertifikat untuk autentikasi. Jika klien memiliki lebih dari satu sertifikat, klien dapat memberikan LocalCertificateSelectionCallback delegasi untuk memilih sertifikat yang benar untuk server. Sertifikat klien harus terletak di penyimpanan sertifikat "Saya" pengguna saat ini. Autentikasi klien melalui sertifikat tidak didukung untuk Ssl2 protokol (SSL versi 2).

Jika autentikasi gagal, Anda menerima AuthenticationException, dan SslStream tidak lagi dapat digunakan. Anda harus menutup objek ini dan menghapus semua referensi ke objek tersebut sehingga dapat dikumpulkan oleh pengumpul sampah.

Ketika proses autentikasi, juga dikenal sebagai jabat tangan SSL, berhasil, identitas server (dan secara opsional, klien) dibuat dan SslStream dapat digunakan oleh klien dan server untuk bertukar pesan. Sebelum mengirim atau menerima informasi, klien dan server harus memeriksa layanan dan tingkat keamanan yang disediakan oleh SslStream untuk menentukan apakah protokol, algoritma, dan kekuatan yang dipilih memenuhi persyaratan mereka untuk integritas dan kerahasiaan. Jika pengaturan saat ini tidak cukup, aliran harus ditutup. Anda dapat memeriksa layanan keamanan yang disediakan dengan SslStream menggunakan IsEncrypted properti dan IsSigned . Tabel berikut ini memperlihatkan elemen yang melaporkan pengaturan kriptografi yang digunakan untuk autentikasi, enkripsi, dan penandatanganan data.

Elemen Anggota
Protokol keamanan yang digunakan untuk mengautentikasi server dan, secara opsional, klien. Properti SslProtocol dan enumerasi terkait SslProtocols .
Algoritma pertukaran kunci. Properti KeyExchangeAlgorithm dan enumerasi terkait ExchangeAlgorithmType .
Algoritma integritas pesan. Properti HashAlgorithm dan enumerasi terkait HashAlgorithmType .
Algoritma kerahasiaan pesan. Properti CipherAlgorithm dan enumerasi terkait CipherAlgorithmType .
Kekuatan algoritma yang dipilih. Properti KeyExchangeStrength, HashStrength, dan CipherStrength .

Setelah autentikasi berhasil, Anda dapat mengirim data menggunakan metode sinkron Write atau asinkron BeginWrite . Anda dapat menerima data menggunakan metode sinkron Read atau asinkron BeginRead .

Jika Anda menentukan bahwa SslStream aliran yang mendasar harus dibiarkan terbuka, Anda bertanggung jawab untuk menutup aliran tersebut ketika Anda selesai menggunakannya.

Catatan

Jika aplikasi yang membuat SslStream objek berjalan dengan kredensial pengguna Normal, aplikasi tidak akan dapat mengakses sertifikat yang diinstal di penyimpanan komputer lokal kecuali izin telah diberikan secara eksplisit kepada pengguna untuk melakukannya.

SslStream mengasumsikan bahwa batas waktu bersama dengan yang lain IOException ketika seseorang dilemparkan dari aliran dalam akan diperlakukan sebagai fatal oleh pemanggilnya. Menggunakan SslStream kembali instans setelah batas waktu akan mengembalikan sampah. Aplikasi harus Close memberikan SslStream pengecualian dan dalam kasus ini.

.NET Framework 4.6 menyertakan fitur keamanan baru yang memblokir cipher dan algoritma hashing yang tidak aman untuk koneksi. Aplikasi yang menggunakan TLS/SSL melalui API seperti HttpClient, HttpWebRequest, FTPClient, SmtpClient, SslStream, dll. dan penargetan .NET Framework 4.6 mendapatkan perilaku yang lebih aman secara default.

Pengembang mungkin ingin menolak perilaku ini untuk menjaga interoperabilitas dengan layanan SSL3 yang ada ATAU layanan TLS w/ RC4. Artikel ini menjelaskan cara mengubah kode Anda sehingga perilaku baru dinonaktifkan.

.NET Framework 4.7 menambahkan kelebihan beban baru untuk metode yang mengautentikasi SslStreams yang tidak menentukan versi TLS, tetapi sebaliknya gunakan versi TLS yang didefinisikan sebagai default sistem di SCHANNEL. Gunakan metode ini di aplikasi Anda sebagai cara untuk dapat memodifikasi default nanti saat praktik terbaik versi TLS berubah dari waktu ke waktu, tanpa perlu membangun kembali dan menyebarkan ulang aplikasi Anda.

Lihat juga praktik terbaik Transport Layer Security (TLS) dengan .NET Framework.

Konstruktor

SslStream(Stream)

Menginisialisasi instans SslStream baru kelas menggunakan Stream.

SslStream(Stream, Boolean)

Menginisialisasi instans SslStream baru kelas menggunakan perilaku penutupan yang ditentukan Stream dan streaming.

SslStream(Stream, Boolean, RemoteCertificateValidationCallback)

Menginisialisasi instans SslStream baru kelas menggunakan perilaku penutupan aliran yang ditentukan Streamdan delegasi validasi sertifikat.

SslStream(Stream, Boolean, RemoteCertificateValidationCallback, LocalCertificateSelectionCallback)

Menginisialisasi instans SslStream baru kelas menggunakan perilaku penutupan aliran, delegasi validasi sertifikat, dan delegasi pemilihan sertifikat yang ditentukan Stream.

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

Menginisialisasi instans SslStream baru kelas menggunakan Stream.

Properti

CanRead

Boolean Mendapatkan nilai yang menunjukkan apakah aliran yang mendasar dapat dibaca.

CanSeek

Boolean Mendapatkan nilai yang menunjukkan apakah aliran yang mendasar dapat dicari.

CanTimeout

Boolean Mendapatkan nilai yang menunjukkan apakah aliran yang mendasar mendukung waktu habis.

CanWrite

Boolean Mendapatkan nilai yang menunjukkan apakah aliran yang mendasar dapat ditulis.

CheckCertRevocationStatus

Boolean Mendapatkan nilai yang menunjukkan apakah daftar pencabutan sertifikat diperiksa selama proses validasi sertifikat.

CipherAlgorithm

Mendapatkan nilai yang mengidentifikasi algoritma enkripsi massal yang digunakan oleh ini SslStream.

CipherStrength

Mendapatkan nilai yang mengidentifikasi kekuatan algoritma sandi yang digunakan oleh ini SslStream.

HashAlgorithm

Mendapatkan algoritma yang digunakan untuk menghasilkan kode autentikasi pesan (MAC).

HashStrength

Mendapatkan nilai yang mengidentifikasi kekuatan algoritma hash yang digunakan oleh instans ini.

InnerStream

Mendapatkan aliran yang digunakan oleh ini AuthenticatedStream untuk mengirim dan menerima data.

(Diperoleh dari AuthenticatedStream)
IsAuthenticated

Boolean Mendapatkan nilai yang menunjukkan apakah autentikasi berhasil.

IsEncrypted

Boolean Mendapatkan nilai yang menunjukkan apakah ini SslStream menggunakan enkripsi data.

IsMutuallyAuthenticated

Boolean Mendapatkan nilai yang menunjukkan apakah server dan klien telah diautentikasi.

IsServer

Boolean Mendapatkan nilai yang menunjukkan apakah sisi lokal koneksi yang digunakan oleh ini SslStream diautentikasi sebagai server.

IsSigned

Boolean Mendapatkan nilai yang menunjukkan apakah data yang dikirim menggunakan aliran ini ditandatangani.

KeyExchangeAlgorithm

Mendapatkan algoritma pertukaran kunci yang digunakan oleh ini SslStream.

KeyExchangeStrength

Mendapatkan nilai yang mengidentifikasi kekuatan algoritma pertukaran kunci yang digunakan oleh instans ini.

LeaveInnerStreamOpen

Mendapatkan apakah aliran yang digunakan oleh ini AuthenticatedStream untuk mengirim dan menerima data telah dibiarkan terbuka.

(Diperoleh dari AuthenticatedStream)
Length

Mendapatkan panjang aliran yang mendasar.

LocalCertificate

Mendapatkan sertifikat yang digunakan untuk mengautentikasi titik akhir lokal.

NegotiatedApplicationProtocol

Protokol aplikasi yang dinegosiasikan dalam jabat tangan TLS.

NegotiatedCipherSuite

Mendapatkan cipher suite yang dinegosiasikan untuk koneksi ini.

Position

Mendapatkan atau mengatur posisi saat ini di aliran yang mendasar.

ReadTimeout

Mendapatkan atau mengatur jumlah waktu, yang dinyatakan dalam milidetik, operasi baca memblokir menunggu data.

RemoteCertificate

Mendapatkan sertifikat yang digunakan untuk mengautentikasi titik akhir jarak jauh.

SslProtocol

Mendapatkan nilai yang menunjukkan protokol keamanan yang digunakan untuk mengautentikasi koneksi ini.

TargetHostName

Mendapatkan nama server yang coba disambungkan klien. Nama tersebut digunakan untuk validasi sertifikat server. Ini bisa berupa nama DNS atau alamat IP.

TransportContext

Mendapatkan yang TransportContext digunakan untuk autentikasi menggunakan perlindungan yang diperluas.

WriteTimeout

Mendapatkan atau mengatur jumlah waktu operasi tulis memblokir menunggu data.

Metode

AuthenticateAsClient(SslClientAuthenticationOptions)

Dipanggil oleh klien untuk mengautentikasi server dan secara opsional klien dalam koneksi klien-server.

AuthenticateAsClient(String)

Dipanggil oleh klien untuk mengautentikasi server dan secara opsional klien dalam koneksi klien-server.

AuthenticateAsClient(String, X509CertificateCollection, Boolean)

Dipanggil oleh klien untuk mengautentikasi server dan secara opsional klien dalam koneksi klien-server. Proses autentikasi menggunakan pengumpulan sertifikat yang ditentukan, dan protokol SSL default sistem.

AuthenticateAsClient(String, X509CertificateCollection, SslProtocols, Boolean)

Dipanggil oleh klien untuk mengautentikasi server dan secara opsional klien dalam koneksi klien-server. Proses autentikasi menggunakan kumpulan sertifikat dan protokol SSL yang ditentukan.

AuthenticateAsClientAsync(SslClientAuthenticationOptions, CancellationToken)

Dipanggil oleh klien untuk mengautentikasi server dan secara opsional klien dalam koneksi klien-server sebagai operasi asinkron. Proses autentikasi menggunakan informasi yang ditentukan dalam sslClientAuthenticationOptions tas properti.

AuthenticateAsClientAsync(String)

Dipanggil oleh klien untuk mengautentikasi server dan secara opsional klien dalam koneksi klien-server sebagai operasi asinkron.

AuthenticateAsClientAsync(String, X509CertificateCollection, Boolean)

Dipanggil oleh klien untuk mengautentikasi server dan secara opsional klien dalam koneksi klien-server sebagai operasi asinkron. Proses autentikasi menggunakan kumpulan sertifikat yang ditentukan dan protokol SSL default sistem.

AuthenticateAsClientAsync(String, X509CertificateCollection, SslProtocols, Boolean)

Dipanggil oleh klien untuk mengautentikasi server dan secara opsional klien dalam koneksi klien-server sebagai operasi asinkron. Proses autentikasi menggunakan kumpulan sertifikat dan protokol SSL yang ditentukan.

AuthenticateAsServer(SslServerAuthenticationOptions)

Dipanggil oleh server untuk mengautentikasi server dan secara opsional klien dalam koneksi klien-server menggunakan sertifikat yang ditentukan.

AuthenticateAsServer(X509Certificate)

Dipanggil oleh server untuk mengautentikasi server dan secara opsional klien dalam koneksi klien-server menggunakan sertifikat yang ditentukan.

AuthenticateAsServer(X509Certificate, Boolean, Boolean)

Dipanggil oleh server untuk mengautentikasi server dan secara opsional klien dalam koneksi server klien menggunakan sertifikat dan persyaratan yang ditentukan, dan menggunakan protokol keamanan default sistem.

AuthenticateAsServer(X509Certificate, Boolean, SslProtocols, Boolean)

Dipanggil oleh server untuk mengautentikasi server dan secara opsional klien dalam koneksi klien-server menggunakan sertifikat, persyaratan, dan protokol keamanan yang ditentukan.

AuthenticateAsServerAsync(ServerOptionsSelectionCallback, Object, CancellationToken)

Dipanggil oleh server untuk mengautentikasi server dan secara opsional klien dalam koneksi klien-server sebagai operasi asinkron. Proses autentikasi menggunakan informasi yang dikembalikan oleh optionsCallback.

AuthenticateAsServerAsync(SslServerAuthenticationOptions, CancellationToken)

Dipanggil oleh server untuk mengautentikasi server dan secara opsional klien dalam koneksi klien-server sebagai operasi asinkron. Proses autentikasi menggunakan informasi yang ditentukan dalam sslClientAuthenticationOptions tas properti.

AuthenticateAsServerAsync(X509Certificate)

Dipanggil oleh server untuk mengautentikasi server dan secara opsional klien dalam koneksi server klien menggunakan sertifikat yang ditentukan sebagai operasi asinkron.

AuthenticateAsServerAsync(X509Certificate, Boolean, Boolean)

Dipanggil oleh server untuk mengautentikasi server dan secara opsional klien dalam koneksi server klien menggunakan sertifikat, persyaratan, dan protokol keamanan yang ditentukan sebagai operasi asinkron.

AuthenticateAsServerAsync(X509Certificate, Boolean, SslProtocols, Boolean)

Dipanggil oleh server untuk mengautentikasi server dan secara opsional klien dalam koneksi server klien menggunakan sertifikat, persyaratan, dan protokol keamanan yang ditentukan sebagai operasi asinkron.

BeginAuthenticateAsClient(String, AsyncCallback, Object)

Dipanggil oleh klien untuk memulai operasi asinkron untuk mengautentikasi server dan secara opsional klien.

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

Dipanggil oleh klien untuk memulai operasi asinkron untuk mengautentikasi server dan secara opsional klien menggunakan sertifikat yang ditentukan dan protokol keamanan default sistem.

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

Dipanggil oleh klien untuk memulai operasi asinkron untuk mengautentikasi server dan secara opsional klien menggunakan sertifikat dan protokol keamanan yang ditentukan.

BeginAuthenticateAsServer(X509Certificate, AsyncCallback, Object)

Dipanggil oleh server untuk memulai operasi asinkron untuk mengautentikasi klien dan secara opsional server dalam koneksi server klien.

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

Dipanggil oleh server untuk memulai operasi asinkron untuk mengautentikasi server dan secara opsional klien menggunakan sertifikat dan persyaratan yang ditentukan, dan protokol keamanan default sistem.

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

Dipanggil oleh server untuk memulai operasi asinkron untuk mengautentikasi server dan secara opsional klien menggunakan sertifikat, persyaratan, dan protokol keamanan yang ditentukan.

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

Memulai operasi baca asinkron yang membaca data dari aliran dan menyimpannya dalam array yang ditentukan.

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

Memulai operasi baca asinkron. (Pertimbangkan untuk menggunakan ReadAsync(Byte[], Int32, Int32) sebagai gantinya.)

(Diperoleh dari Stream)
BeginWrite(Byte[], Int32, Int32, AsyncCallback, Object)

Memulai operasi penulisan asinkron yang menulis Bytes dari buffer yang ditentukan ke aliran.

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

Memulai operasi tulis asinkron. (Pertimbangkan untuk menggunakan WriteAsync(Byte[], Int32, Int32) sebagai gantinya.)

(Diperoleh dari Stream)
Close()

Menutup aliran saat ini dan merilis sumber daya apa pun (seperti soket dan handel file) yang terkait dengan aliran saat ini. Alih-alih memanggil metode ini, pastikan aliran dibuang dengan benar.

(Diperoleh dari Stream)
CopyTo(Stream)

Membaca byte dari aliran saat ini dan menulisnya ke aliran lain. Kedua posisi aliran dimajukan dengan jumlah byte yang disalin.

(Diperoleh dari Stream)
CopyTo(Stream, Int32)

Membaca byte dari aliran saat ini dan menulisnya ke aliran lain, menggunakan ukuran buffer tertentu. Kedua posisi aliran dimajukan dengan jumlah byte yang disalin.

(Diperoleh dari Stream)
CopyToAsync(Stream)

Secara asinkron membaca byte dari aliran saat ini dan menulisnya ke aliran lain. Kedua posisi aliran dimajukan dengan jumlah byte yang disalin.

(Diperoleh dari Stream)
CopyToAsync(Stream, CancellationToken)

Secara asinkron membaca byte dari aliran saat ini dan menulisnya ke aliran lain, menggunakan token pembatalan yang ditentukan. Kedua posisi aliran dimajukan dengan jumlah byte yang disalin.

(Diperoleh dari Stream)
CopyToAsync(Stream, Int32)

Secara asinkron membaca byte dari aliran saat ini dan menulisnya ke aliran lain, menggunakan ukuran buffer tertentu. Kedua posisi aliran dimajukan dengan jumlah byte yang disalin.

(Diperoleh dari Stream)
CopyToAsync(Stream, Int32, CancellationToken)

Secara asinkron membaca byte dari aliran saat ini dan menulisnya ke aliran lain, menggunakan ukuran buffer dan token pembatalan yang ditentukan. Kedua posisi aliran dimajukan dengan jumlah byte yang disalin.

(Diperoleh dari Stream)
CreateObjRef(Type)

Membuat objek yang berisi semua informasi relevan yang diperlukan untuk menghasilkan proksi yang digunakan untuk berkomunikasi dengan objek jarak jauh.

(Diperoleh dari MarshalByRefObject)
CreateWaitHandle()
Kedaluwarsa.
Kedaluwarsa.
Kedaluwarsa.

Mengalokasikan WaitHandle objek.

(Diperoleh dari Stream)
Dispose()

Merilis semua sumber daya yang Streamdigunakan oleh .

(Diperoleh dari Stream)
Dispose(Boolean)

Merilis sumber daya tidak terkelola yang SslStream digunakan oleh dan secara opsional merilis sumber daya terkelola.

Dispose(Boolean)

Merilis sumber daya tidak terkelola yang AuthenticatedStream digunakan oleh dan secara opsional merilis sumber daya terkelola.

(Diperoleh dari AuthenticatedStream)
DisposeAsync()

Secara asinkron merilis sumber daya yang tidak dikelola dan dikelola yang digunakan oleh SslStream.

DisposeAsync()

Secara asinkron merilis sumber daya yang tidak dikelola dan dikelola yang digunakan oleh AuthenticatedStream.

(Diperoleh dari AuthenticatedStream)
EndAuthenticateAsClient(IAsyncResult)

Mengakhiri operasi autentikasi server asinkron yang tertunda dimulai dengan panggilan sebelumnya ke BeginAuthenticateAsClient.

EndAuthenticateAsServer(IAsyncResult)

Mengakhiri operasi autentikasi klien asinkron yang tertunda dimulai dengan panggilan sebelumnya ke BeginAuthenticateAsClient.

EndRead(IAsyncResult)

Mengakhiri operasi baca asinkron yang dimulai dengan panggilan sebelumnya ke BeginRead(Byte[], Int32, Int32, AsyncCallback, Object).

EndRead(IAsyncResult)

Menunggu pembacaan asinkron yang tertunda selesai. (Pertimbangkan untuk menggunakan ReadAsync(Byte[], Int32, Int32) sebagai gantinya.)

(Diperoleh dari Stream)
EndWrite(IAsyncResult)

Mengakhiri operasi penulisan asinkron yang dimulai dengan panggilan sebelumnya ke BeginWrite(Byte[], Int32, Int32, AsyncCallback, Object).

EndWrite(IAsyncResult)

Mengakhiri operasi penulisan asinkron. (Pertimbangkan untuk menggunakan WriteAsync(Byte[], Int32, Int32) sebagai gantinya.)

(Diperoleh dari Stream)
Equals(Object)

Menentukan apakah objek yang ditentukan sama dengan objek saat ini.

(Diperoleh dari Object)
Finalize()

Merilis semua sumber daya yang SslStreamdigunakan oleh .

Flush()

Menyebabkan data buffer ditulis ke perangkat yang mendasar.

FlushAsync()

Secara asinkron menghapus semua buffer untuk aliran ini dan menyebabkan data buffer ditulis ke perangkat yang mendasar.

(Diperoleh dari Stream)
FlushAsync(CancellationToken)

Secara asinkron menulis data yang di-buffer ke perangkat yang mendasar.

FlushAsync(CancellationToken)

Secara asinkron menghapus semua buffer untuk aliran ini, menyebabkan data yang di-buffer ditulis ke perangkat yang mendasar, dan memantau permintaan pembatalan.

(Diperoleh dari Stream)
GetHashCode()

Berfungsi sebagai fungsi hash default.

(Diperoleh dari Object)
GetLifetimeService()
Kedaluwarsa.

Mengambil objek layanan seumur hidup saat ini yang mengontrol kebijakan seumur hidup untuk instans ini.

(Diperoleh dari MarshalByRefObject)
GetType()

Mendapatkan instans Type saat ini.

(Diperoleh dari Object)
InitializeLifetimeService()
Kedaluwarsa.

Mendapatkan objek layanan seumur hidup untuk mengontrol kebijakan seumur hidup untuk instans ini.

(Diperoleh dari MarshalByRefObject)
MemberwiseClone()

Membuat salinan dangkal dari yang saat ini Object.

(Diperoleh dari Object)
MemberwiseClone(Boolean)

Membuat salinan dangkal objek saat ini MarshalByRefObject .

(Diperoleh dari MarshalByRefObject)
NegotiateClientCertificateAsync(CancellationToken)

Menegosiasikan sertifikat klien pada koneksi yang diautentikasi.

ObjectInvariant()
Kedaluwarsa.

Menyediakan dukungan untuk Contract.

(Diperoleh dari Stream)
Read(Byte[], Int32, Int32)

Membaca data dari aliran ini dan menyimpannya dalam array yang ditentukan.

Read(Span<Byte>)

Ketika ditimpa di kelas turunan, membaca urutan byte dari aliran saat ini dan memajukan posisi dalam aliran dengan jumlah byte yang dibaca.

(Diperoleh dari Stream)
ReadAsync(Byte[], Int32, Int32)

Secara asinkron membaca urutan byte dari aliran saat ini dan memajukan posisi dalam aliran dengan jumlah byte yang dibaca.

(Diperoleh dari Stream)
ReadAsync(Byte[], Int32, Int32, CancellationToken)

Secara asinkron membaca data dari aliran ini dan menyimpannya dalam rentang array byte yang ditentukan.

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

Secara asinkron membaca urutan byte dari aliran saat ini, memajukan posisi dalam aliran dengan jumlah byte yang dibaca, dan memantau permintaan pembatalan.

(Diperoleh dari Stream)
ReadAsync(Memory<Byte>, CancellationToken)

Secara asinkron membaca data dari aliran ini dan menyimpannya dalam rentang memori yang ditentukan.

ReadAsync(Memory<Byte>, CancellationToken)

Secara asinkron membaca urutan byte dari aliran saat ini, memajukan posisi dalam aliran dengan jumlah byte yang dibaca, dan memantau permintaan pembatalan.

(Diperoleh dari Stream)
ReadAtLeast(Span<Byte>, Int32, Boolean)

Membaca setidaknya jumlah minimum byte dari aliran saat ini dan memajukan posisi dalam aliran dengan jumlah byte yang dibaca.

(Diperoleh dari Stream)
ReadAtLeastAsync(Memory<Byte>, Int32, Boolean, CancellationToken)

Secara asinkron membaca setidaknya jumlah minimum byte dari aliran saat ini, memajukan posisi dalam aliran dengan jumlah byte yang dibaca, dan memantau permintaan pembatalan.

(Diperoleh dari Stream)
ReadByte()

Membaca byte dari SslStream dan memajukan posisi dalam aliran satu byte, atau mengembalikan -1 jika di akhir aliran.

ReadByte()

Membaca byte dari aliran dan memajukan posisi dalam aliran satu byte, atau mengembalikan -1 jika di akhir aliran.

(Diperoleh dari Stream)
ReadExactly(Byte[], Int32, Int32)

count Membaca jumlah byte dari aliran saat ini dan memajukan posisi dalam aliran.

(Diperoleh dari Stream)
ReadExactly(Span<Byte>)

Membaca byte dari aliran saat ini dan memajukan posisi dalam aliran hingga buffer terisi.

(Diperoleh dari Stream)
ReadExactlyAsync(Byte[], Int32, Int32, CancellationToken)

Secara asinkron membaca count jumlah byte dari aliran saat ini, memajukan posisi dalam aliran, dan memantau permintaan pembatalan.

(Diperoleh dari Stream)
ReadExactlyAsync(Memory<Byte>, CancellationToken)

Secara asinkron membaca byte dari aliran saat ini, memajukan posisi dalam aliran hingga buffer terisi, dan memantau permintaan pembatalan.

(Diperoleh dari Stream)
Seek(Int64, SeekOrigin)

Melempar .NotSupportedException

SetLength(Int64)

Mengatur panjang aliran yang mendasar.

ShutdownAsync()

Mematikan SslStream ini.

ToString()

Mengembalikan string yang mewakili objek saat ini.

(Diperoleh dari Object)
Write(Byte[])

Menulis data yang ditentukan ke aliran ini.

Write(Byte[], Int32, Int32)

Tulis jumlah Bytes yang ditentukan ke aliran yang mendasar menggunakan buffer dan offset yang ditentukan.

Write(ReadOnlySpan<Byte>)

Ketika ditimpa di kelas turunan, menulis urutan byte ke aliran saat ini dan memajukan posisi saat ini dalam aliran ini dengan jumlah byte yang ditulis.

(Diperoleh dari Stream)
WriteAsync(Byte[], Int32, Int32)

Secara asinkron menulis urutan byte ke aliran saat ini dan memajukan posisi saat ini dalam aliran ini dengan jumlah byte yang ditulis.

(Diperoleh dari Stream)
WriteAsync(Byte[], Int32, Int32, CancellationToken)

Secara asinkron menulis data ke aliran yang mendasar dari rentang array byte yang ditentukan.

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

Secara asinkron menulis urutan byte ke aliran saat ini, memajukan posisi saat ini dalam aliran ini dengan jumlah byte yang ditulis, dan memantau permintaan pembatalan.

(Diperoleh dari Stream)
WriteAsync(ReadOnlyMemory<Byte>, CancellationToken)

Secara asinkron menulis data ke aliran yang mendasar dari rentang memori byte baca-saja.

WriteAsync(ReadOnlyMemory<Byte>, CancellationToken)

Secara asinkron menulis urutan byte ke aliran saat ini, memajukan posisi saat ini dalam aliran ini dengan jumlah byte yang ditulis, dan memantau permintaan pembatalan.

(Diperoleh dari Stream)
WriteByte(Byte)

Menulis byte ke posisi saat ini di aliran dan memajukan posisi dalam aliran satu byte.

(Diperoleh dari Stream)

Metode Ekstensi

CopyToAsync(Stream, PipeWriter, CancellationToken)

Secara asinkron membaca byte dari Stream dan menulisnya ke yang ditentukan PipeWriter, menggunakan token pembatalan.

ConfigureAwait(IAsyncDisposable, Boolean)

Mengonfigurasi bagaimana menunggu tugas yang dikembalikan dari asinkron sekali pakai dilakukan.

Berlaku untuk

Lihat juga