SslStream 클래스

정의

SSL(Secure Socket Layer) 보안 프로토콜을 사용하여 서버 및 필요에 따라 클라이언트를 인증하는 클라이언트-서버 통신에 사용되는 스트림을 제공합니다.

public ref class SslStream : System::Net::Security::AuthenticatedStream
public class SslStream : System.Net.Security.AuthenticatedStream
type SslStream = class
    inherit AuthenticatedStream
type SslStream = class
    inherit AuthenticatedStream
    interface IDisposable
Public Class SslStream
Inherits AuthenticatedStream
상속
상속
구현

예제

다음 코드 예제에서는 클래스를 TcpListener 사용 하 여 SslStream 클라이언트와 통신 하는 만드는 방법을 보여 줍니다.

#using <System.dll>

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

public:

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

      }
   }


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

   }


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

      return messageData->ToString();
   }


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


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


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


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

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


private:

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

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

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

};

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

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

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

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

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

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

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

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

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

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

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

            Try

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

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

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

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

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

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

        Private Shared Function ReadMessage(sslStream As SslStream) As String

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

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

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

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

            Return messageData.ToString()
        End Function

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

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

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

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

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

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

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

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

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

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

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

다음 코드 예제에서는 클래스를 TcpClient 사용 하 여 SslStream 서버와 통신 하는 만드는 방법을 보여 줍니다.

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

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

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

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

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

            return description;
        }

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

Namespace Examples.System.Net

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

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

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

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

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

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

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

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

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

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

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

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

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

            Return messageData.ToString()

        End Function

        Private Shared Sub DisplayUsage()

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

        End Sub

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

            Dim serverCertificateName As String
            Dim machineName As String

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

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

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

            SslTcpClient.RunClient(machineName, serverCertificateName)

            Return 0

        End Function

    End Class

End Namespace

설명

SSL 프로토콜은 SslStream. 클라이언트와 서버 간에 중요한 정보를 전달할 때 SSL 연결(예: 제공) SslStream을 사용해야 합니다. 이 기능을 SslStream 사용하면 네트워크에서 전송하는 동안 모든 사용자가 정보를 읽고 변조하는 것을 방지할 수 있습니다.

인스턴스는 SslStream 만들 때 제공하는 스트림을 사용하여 데이터를 전송합니다 SslStream. 이 기본 스트림을 제공할 때 기본 스트림을 닫을 때도 기본 스트림을 SslStream 닫을지 여부를 지정하는 옵션이 있습니다. 일반적으로 클래스는 SslStream 클래스와 TcpListener 함께 TcpClient 사용됩니다. 메서드는 GetStream 클래스와 NetworkStream 함께 사용하기에 적합합니다 SslStream .

서버를 만든 SslStream후 필요에 따라 클라이언트를 인증해야 합니다. 서버는 해당 ID의 증명을 설정하고 클라이언트도 그렇게 되도록 요청할 수 있는 X509 인증서를 제공해야 합니다. 를 사용하여 정보를 전송하기 전에 인증을 SslStream수행해야 합니다. 클라이언트는 인증이 완료될 때까지 차단하는 동기 AuthenticateAsClient 메서드 또는 인증이 완료될 때까지 기다리는 것을 차단하지 않는 비동 BeginAuthenticateAsClient 기 메서드를 사용하여 인증을 시작합니다. 서버는 동기 AuthenticateAsServer 또는 비동기 메서드를 사용하여 인증을 BeginAuthenticateAsServer 시작합니다. 클라이언트와 서버 모두 인증을 시작해야 합니다.

인증은 SSPI(보안 지원 공급자) 채널 공급자에 의해 처리됩니다. 클라이언트는 만들 때 대리자를 지정하여 서버 인증서의 유효성 검사를 제어할 RemoteCertificateValidationCallback 수 있습니다 SslStream. 서버는 대리자를 제공하여 유효성 검사를 제어할 RemoteCertificateValidationCallback 수도 있습니다. 대리자가 참조하는 메서드에는 원격 당사자의 인증서와 인증서의 유효성을 검사하는 동안 발생한 오류 SSPI가 포함됩니다. 서버에서 대리자를 지정하는 경우 서버에서 클라이언트 인증을 요청했는지 여부에 관계없이 대리자의 메서드가 호출됩니다. 서버가 클라이언트 인증을 요청하지 않은 경우 서버의 대리자 메서드는 null 인증서와 인증서 오류의 빈 배열을 받습니다.

서버에 클라이언트 인증이 필요한 경우 클라이언트는 인증을 위해 하나 이상의 인증서를 지정해야 합니다. 클라이언트에 둘 이상의 인증서가 있는 경우 클라이언트는 서버에 대한 올바른 인증서를 LocalCertificateSelectionCallback 선택하는 대리자를 제공할 수 있습니다. 클라이언트의 인증서는 현재 사용자의 "내" 인증서 저장소에 있어야 합니다. 인증서를 통한 클라이언트 인증은 (SSL 버전 2) 프로토콜에 Ssl2 대해 지원되지 않습니다.

인증에 실패하면 해당 인증이 AuthenticationException수신되고 SslStream 더 이상 사용할 수 없습니다. 가비지 수집기에서 수집할 수 있도록 이 개체를 닫고 모든 참조를 제거해야 합니다.

SSL 핸드셰이크라고도 하는 인증 프로세스가 성공하면 서버의 ID(및 필요에 따라 클라이언트)가 설정되고 클라이언트와 SslStream 서버에서 메시지를 교환하는 데 사용할 수 있습니다. 정보를 보내거나 받기 전에 클라이언트와 서버는 선택한 프로토콜, 알고리즘 및 강도가 무결성 및 기밀성에 대한 요구 사항을 충족하는지 확인하기 위해 제공 SslStream 된 보안 서비스 및 수준을 확인해야 합니다. 현재 설정이 충분하지 않으면 스트림을 닫아야 합니다. 사용 IsEncryptedIsSigned 속성에서 제공하는 SslStream 보안 서비스를 확인할 수 있습니다. 다음 표에서는 인증, 암호화 및 데이터 서명에 사용되는 암호화 설정을 보고하는 요소를 보여줍니다.

요소 멤버
서버 및 필요에 따라 클라이언트를 인증하는 데 사용되는 보안 프로토콜입니다. SslProtocol 속성 및 연결된 SslProtocols 열거형입니다.
키 교환 알고리즘입니다. KeyExchangeAlgorithm 속성 및 연결된 ExchangeAlgorithmType 열거형입니다.
메시지 무결성 알고리즘입니다. HashAlgorithm 속성 및 연결된 HashAlgorithmType 열거형입니다.
메시지 기밀성 알고리즘입니다. CipherAlgorithm 속성 및 연결된 CipherAlgorithmType 열거형입니다.
선택한 알고리즘의 장점입니다. KeyExchangeStrength, HashStrengthCipherStrength 속성입니다.

인증에 성공하면 동기 Write 또는 비동 BeginWrite 기 메서드를 사용하여 데이터를 보낼 수 있습니다. 동기 또는 비동 Read BeginRead 기 메서드를 사용하여 데이터를 받을 수 있습니다.

기본 스트림을 SslStream 열어 두도록 지정한 경우 사용이 완료되면 해당 스트림을 닫아야 합니다.

참고

만들고 있는 애플리케이션을 SslStream 일반 사용자의 자격 증명을 사용 하 여 실행 개체, 애플리케이션 권한을 명시적으로 부여 되어 사용자에 게 이렇게 하려면 로컬 컴퓨터 저장소에 설치 된 인증서에 액세스할 수 없습니다.

SslStream 에서는 내부 스트림에서 throw될 때 다른 IOException 시간 제한과 함께 시간 초과가 호출자에 의해 치명적인 것으로 처리된다고 가정합니다. 시간 제한 후에 인스턴스를 다시 사용하면 SslStream 가비지가 반환됩니다. 애플리케이션 해야 CloseSslStream 이러한 경우 예외를 throw 합니다.

.NET Framework 4.6에는 연결에 대한 안전하지 않은 암호 및 해시 알고리즘을 차단하는 새로운 보안 기능이 포함되어 있습니다. HttpClient, HttpWebRequest, FTPClient, SmtpClient, SslStream 등과 같은 API를 통해 TLS/SSL을 사용하고 .NET Framework 4.6을 대상으로 하는 애플리케이션은 기본적으로 더 안전한 동작을 가져옵니다.

개발자는 기존 SSL3 서비스 또는 TLS(RC4 서비스)와의 상호 운용성을 유지하기 위해 이 동작을 옵트아웃(opt out)할 수 있습니다. 이 문서에서 는 새 동작을 사용하지 않도록 코드를 수정하는 방법을 설명합니다.

.NET Framework 4.7은 TLS 버전을 지정하지 않고 대신 SCHANNEL에서 시스템 기본값으로 정의된 TLS 버전을 사용하는 SslStreams를 인증하는 메서드에 대한 새 오버로드를 추가합니다. 앱에서 이러한 메서드를 사용하여 나중에 앱을 다시 빌드하고 다시 배포할 필요 없이 시간이 지남에 따라 TLS 버전 모범 사례 변경으로 기본값을 수정할 수 있습니다.

또한 .NET Framework TLS(전송 계층 보안) 모범 사례를 참조하세요.

생성자

SslStream(Stream)

지정된 SslStream를 사용하여 Stream 클래스의 새 인스턴스를 초기화합니다.

SslStream(Stream, Boolean)

지정된 SslStream과 스트림 닫기 동작을 사용해서 Stream 클래스의 새 인스턴스를 초기화합니다.

SslStream(Stream, Boolean, RemoteCertificateValidationCallback)

지정된 SslStream, 스트림 닫기 동작 및 인증서 유효성 검사 대리자를 사용하여 Stream 클래스의 새 인스턴스를 초기화합니다.

SslStream(Stream, Boolean, RemoteCertificateValidationCallback, LocalCertificateSelectionCallback)

지정된 SslStream, 스트림 닫기 동작, 인증서 유효성 검사 대리자 및 인증서 선택 대리자를 사용하여 Stream 클래스의 새 인스턴스를 초기화합니다.

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

지정된 SslStream를 사용하여 Stream 클래스의 새 인스턴스를 초기화합니다.

속성

CanRead

기본 스트림을 읽을 수 있는지를 나타내는 Boolean 값을 가져옵니다.

CanSeek

기본 스트림을 검색할 수 있는지를 나타내는 Boolean 값을 가져옵니다.

CanTimeout

기본 스트림에 제한 시간을 설정할 수 있는지를 나타내는 Boolean 값을 가져옵니다.

CanWrite

기본 스트림이 쓰기 가능한지를 나타내는 Boolean 값을 가져옵니다.

CheckCertRevocationStatus

인증서 유효성 검사 프로세스를 진행하는 동안 인증서 해지 목록을 확인하는지 여부를 나타내는 Boolean 값을 가져옵니다.

CipherAlgorithm

SslStream에서 사용하는 일괄 암호화 알고리즘을 식별하는 값을 가져옵니다.

CipherStrength

SslStream에서 사용하는 암호화 알고리즘의 강도를 식별하는 값을 가져옵니다.

HashAlgorithm

MAC(메시지 인증 코드)를 생성하는 데 사용되는 알고리즘을 가져옵니다.

HashStrength

이 인스턴스에서 사용하는 해시 알고리즘의 강도를 식별하는 값을 가져옵니다.

InnerStream

AuthenticatedStream에서 데이터를 보내고 받는 데 사용하는 스트림을 가져옵니다.

(다음에서 상속됨 AuthenticatedStream)
IsAuthenticated

인증이 성공했는지를 나타내는 Boolean 값을 가져옵니다.

IsEncrypted

SslStream에서 데이터 암호화를 사용하는지 여부를 나타내는 Boolean 값을 가져옵니다.

IsMutuallyAuthenticated

서버와 클라이언트 모두 인증되었는지 여부를 나타내는 Boolean 값을 가져옵니다.

IsServer

SslStream에서 사용하는 연결의 로컬측이 서버로 인증되었는지 여부를 나타내는 Boolean 값을 가져옵니다.

IsSigned

이 스트림을 사용하여 보내는 데이터에 서명할지를 나타내는 Boolean 값을 가져옵니다.

KeyExchangeAlgorithm

SslStream에서 사용하는 키 교환 알고리즘을 가져옵니다.

KeyExchangeStrength

이 인스턴스에서 사용하는 키 교환 알고리즘의 강도를 식별하는 값을 가져옵니다.

LeaveInnerStreamOpen

AuthenticatedStream에서 데이터를 보내고 받는 데 사용하는 스트림이 계속 열려 있는지 여부를 가져옵니다.

(다음에서 상속됨 AuthenticatedStream)
Length

기본 스트림의 길이를 가져옵니다.

LocalCertificate

로컬 엔드포인트를 인증하는 데 사용되는 인증서를 가져옵니다.

NegotiatedApplicationProtocol

TLS 핸드셰이크의 협상된 애플리케이션 프로토콜입니다.

NegotiatedCipherSuite

이 연결용으로 협상된 암호 그룹을 가져옵니다.

Position

기본 스트림 내의 현재 위치를 가져오거나 설정합니다.

ReadTimeout

읽기 작업에서 데이터 대기를 차단하는 시간(밀리초)을 가져오거나 설정합니다.

RemoteCertificate

원격 엔드포인트를 인증하는 데 사용되는 인증서를 가져옵니다.

SslProtocol

이 연결을 인증하는 데 사용된 보안 프로토콜을 나타내는 값을 가져옵니다.

TargetHostName

클라이언트에서 연결하려는 서버의 이름을 가져옵니다. 이 이름은 서버 인증서 유효성 검사에 사용됩니다. DNS 이름 또는 IP 주소일 수 있습니다.

TransportContext

확장 보호를 사용하는 인증에 사용되는 TransportContext를 가져옵니다.

WriteTimeout

쓰기 작업에서 데이터 대기를 차단하는 시간을 가져오거나 설정합니다.

메서드

AuthenticateAsClient(SslClientAuthenticationOptions)

클라이언트-서버 연결에서 서버 및 필요에 따라 클라이언트를 인증하기 위해 클라이언트에서 호출됩니다.

AuthenticateAsClient(String)

클라이언트-서버 연결에서 서버 및 필요에 따라 클라이언트를 인증하기 위해 클라이언트에서 호출됩니다.

AuthenticateAsClient(String, X509CertificateCollection, Boolean)

클라이언트-서버 연결에서 서버 및 필요에 따라 클라이언트를 인증하기 위해 클라이언트에서 호출됩니다. 인증 프로세스에서는 지정된 인증서 컬렉션과 시스템 기본 SSL 프로토콜을 사용합니다.

AuthenticateAsClient(String, X509CertificateCollection, SslProtocols, Boolean)

클라이언트-서버 연결에서 서버 및 필요에 따라 클라이언트를 인증하기 위해 클라이언트에서 호출됩니다. 인증 프로세스에는 지정된 인증서 컬렉션과 SSL 프로토콜이 사용됩니다.

AuthenticateAsClientAsync(SslClientAuthenticationOptions, CancellationToken)

클라이언트-서버 연결에서 비동기 작업으로 서버 및 필요에 따라 클라이언트를 인증하기 위해 클라이언트에서 호출됩니다. 인증 프로세스는 sslClientAuthenticationOptions 속성 모음에 지정된 정보를 사용합니다.

AuthenticateAsClientAsync(String)

클라이언트-서버 연결에서 비동기 작업으로 서버 및 필요에 따라 클라이언트를 인증하기 위해 클라이언트에서 호출됩니다.

AuthenticateAsClientAsync(String, X509CertificateCollection, Boolean)

클라이언트-서버 연결에서 비동기 작업으로 서버 및 필요에 따라 클라이언트를 인증하기 위해 클라이언트에서 호출됩니다. 인증 프로세스에서는 지정된 인증서 컬렉션과 시스템 기본 SSL 프로토콜을 사용합니다.

AuthenticateAsClientAsync(String, X509CertificateCollection, SslProtocols, Boolean)

클라이언트-서버 연결에서 비동기 작업으로 서버 및 필요에 따라 클라이언트를 인증하기 위해 클라이언트에서 호출됩니다. 인증 프로세스에는 지정된 인증서 컬렉션과 SSL 프로토콜이 사용됩니다.

AuthenticateAsServer(SslServerAuthenticationOptions)

클라이언트-서버 연결에서 지정된 인증서를 사용하여 서버를 인증하고 선택적으로 클라이언트를 인증하기 위해 서버에서 호출합니다.

AuthenticateAsServer(X509Certificate)

클라이언트-서버 연결에서 지정된 인증서를 사용하여 서버를 인증하고 선택적으로 클라이언트를 인증하기 위해 서버에서 호출합니다.

AuthenticateAsServer(X509Certificate, Boolean, Boolean)

지정된 인증서, 요구 사항 및 시스템 기본 보안 프로토콜을 사용하여 클라이언트-서버 연결에서 서버 및 필요에 따라 클라이언트를 인증하기 위해 서버에서 호출됩니다.

AuthenticateAsServer(X509Certificate, Boolean, SslProtocols, Boolean)

지정된 인증서, 요구 사항 및 보안 프로토콜을 사용하여 클라이언트-서버 연결에서 서버 및 필요에 따라 클라이언트를 인증하기 위해 서버에서 호출됩니다.

AuthenticateAsServerAsync(ServerOptionsSelectionCallback, Object, CancellationToken)

클라이언트-서버 연결에서 서버를 인증하고 선택적으로 클라이언트를 인증하는 비동기 작업으로 서버에서 호출합니다. 인증 프로세스는 optionsCallback에서 반환된 정보를 사용합니다.

AuthenticateAsServerAsync(SslServerAuthenticationOptions, CancellationToken)

클라이언트-서버 연결에서 서버를 인증하고 선택적으로 클라이언트를 인증하는 비동기 작업으로 서버에서 호출합니다. 인증 프로세스는 sslClientAuthenticationOptions 속성 모음에 지정된 정보를 사용합니다.

AuthenticateAsServerAsync(X509Certificate)

클라이언트-서버 연결에서 지정된 인증서를 사용하여 서버를 인증하고 선택적으로 클라이언트를 인증하기 위해 비동기 작업으로 서버에서 호출합니다.

AuthenticateAsServerAsync(X509Certificate, Boolean, Boolean)

지정된 인증서, 요구 사항 및 보안 프로토콜을 사용하여 클라이언트-서버 연결에서 서버 및 필요에 따라 클라이언트를 비동기 작업으로 인증하기 위해 서버에서 호출됩니다.

AuthenticateAsServerAsync(X509Certificate, Boolean, SslProtocols, Boolean)

지정된 인증서, 요구 사항 및 보안 프로토콜을 사용하여 클라이언트-서버 연결에서 서버 및 필요에 따라 클라이언트를 비동기 작업으로 인증하기 위해 서버에서 호출됩니다.

BeginAuthenticateAsClient(String, AsyncCallback, Object)

서버를 인증하고 선택적으로 클라이언트를 인증하는 비동기 작업을 시작하기 위해 클라이언트에서 호출합니다.

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

지정된 인증서 및 시스템 기본 보안 프로토콜을 사용하여 서버 및 필요에 따라 클라이언트를 인증하는 비동기 작업을 시작하기 위해 클라이언트에서 호출됩니다.

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

지정된 인증서 및 보안 프로토콜을 사용하여 서버를 인증하고 선택적으로 클라이언트를 인증하는 비동기 작업을 시작하기 위해 클라이언트에서 호출합니다.

BeginAuthenticateAsServer(X509Certificate, AsyncCallback, Object)

클라이언트-서버 연결에서 클라이언트를 인증하고 선택적으로 서버를 인증하는 비동기 작업을 시작하기 위해 서버에서 호출합니다.

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

지정된 인증서, 요구 사항 및 시스템 기본 보안 프로토콜을 사용하여 서버 및 필요에 따라 클라이언트를 인증하는 비동기 작업을 시작하기 위해 서버에서 호출됩니다.

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

지정된 인증서, 요구 사항 및 보안 프로토콜을 사용하여 서버 및 필요에 따라 클라이언트를 인증하는 비동기 작업을 시작하기 위해 서버에서 호출됩니다.

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

스트림에서 데이터를 읽어 지정된 배열에 저장하는 비동기 읽기 작업을 시작합니다.

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

비동기 읽기 작업을 시작합니다. 대신 ReadAsync(Byte[], Int32, Int32)를 사용하세요.

(다음에서 상속됨 Stream)
BeginWrite(Byte[], Int32, Int32, AsyncCallback, Object)

지정된 버퍼에서 스트림에 Byte를 쓰는 비동기 쓰기 작업을 시작합니다.

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

비동기 쓰기 작업을 시작합니다. 대신 WriteAsync(Byte[], Int32, Int32)를 사용하세요.

(다음에서 상속됨 Stream)
Close()

현재 스트림을 닫고 현재 스트림과 관련된 소켓과 파일 핸들 등의 리소스를 모두 해제합니다. 이 메서드를 호출하는 대신 스트림이 올바르게 삭제되었는지 확인합니다.

(다음에서 상속됨 Stream)
CopyTo(Stream)

현재 스트림에서 바이트를 읽어서 다른 스트림에 해당 바이트를 씁니다. 두 스트림 위치는 복사된 바이트 수만큼 고급입니다.

(다음에서 상속됨 Stream)
CopyTo(Stream, Int32)

현재 스트림에서 바이트를 읽어서 지정된 버퍼 크기로 다른 스트림에 씁니다. 두 스트림 위치는 복사된 바이트 수만큼 고급입니다.

(다음에서 상속됨 Stream)
CopyToAsync(Stream)

현재 스트림에서 모든 바이트를 비동기적으로 읽어 다른 스트림에 씁니다. 두 스트림 위치는 복사된 바이트 수만큼 고급입니다.

(다음에서 상속됨 Stream)
CopyToAsync(Stream, CancellationToken)

현재 스트림에서 바이트를 비동기적으로 읽어 지정된 취소 토큰을 사용하여 다른 스트림에 씁니다. 두 스트림 위치는 복사된 바이트 수만큼 고급입니다.

(다음에서 상속됨 Stream)
CopyToAsync(Stream, Int32)

현재 스트림에서 바이트를 비동기적으로 읽어 지정된 버퍼 크기로 다른 스트림에 씁니다. 두 스트림 위치는 복사된 바이트 수만큼 고급입니다.

(다음에서 상속됨 Stream)
CopyToAsync(Stream, Int32, CancellationToken)

현재 스트림에서 바이트를 비동기적으로 읽어 지정된 버퍼 크기 및 취소 토큰을 사용하여 다른 스트림에 씁니다. 두 스트림 위치는 복사된 바이트 수만큼 고급입니다.

(다음에서 상속됨 Stream)
CreateObjRef(Type)

원격 개체와 통신하는 데 사용되는 프록시 생성에 필요한 모든 관련 정보가 들어 있는 개체를 만듭니다.

(다음에서 상속됨 MarshalByRefObject)
CreateWaitHandle()
사용되지 않습니다.
사용되지 않습니다.
사용되지 않습니다.

WaitHandle 개체를 할당합니다.

(다음에서 상속됨 Stream)
Dispose()

Stream에서 사용하는 모든 리소스를 해제합니다.

(다음에서 상속됨 Stream)
Dispose(Boolean)

SslStream에서 사용하는 관리되지 않는 리소스를 해제하고, 관리되는 리소스를 선택적으로 해제할 수 있습니다.

Dispose(Boolean)

AuthenticatedStream에서 사용하는 관리되지 않는 리소스를 해제하고, 관리되는 리소스를 선택적으로 해제할 수 있습니다.

(다음에서 상속됨 AuthenticatedStream)
DisposeAsync()

SslStream에서 사용하는 비관리형 리소스와 관리형 리소스를 비동기적으로 해제합니다.

DisposeAsync()

AuthenticatedStream에서 사용하는 비관리형 리소스와 관리형 리소스를 비동기적으로 해제합니다.

(다음에서 상속됨 AuthenticatedStream)
EndAuthenticateAsClient(IAsyncResult)

이전에 BeginAuthenticateAsClient를 호출하여 시작한 보류 상태의 비동기 서버 인증 작업을 끝냅니다.

EndAuthenticateAsServer(IAsyncResult)

이전에 BeginAuthenticateAsClient를 호출하여 시작한 보류 상태의 비동기 클라이언트 인증 작업을 끝냅니다.

EndRead(IAsyncResult)

이전에 BeginRead(Byte[], Int32, Int32, AsyncCallback, Object)를 호출하여 시작한 비동기 읽기 작업을 끝냅니다.

EndRead(IAsyncResult)

보류 중인 비동기 읽기가 완료되기를 기다립니다. 대신 ReadAsync(Byte[], Int32, Int32)를 사용하세요.

(다음에서 상속됨 Stream)
EndWrite(IAsyncResult)

이전에 BeginWrite(Byte[], Int32, Int32, AsyncCallback, Object)를 호출하여 시작한 비동기 쓰기 작업을 끝냅니다.

EndWrite(IAsyncResult)

비동기 쓰기 작업을 끝냅니다. 대신 WriteAsync(Byte[], Int32, Int32)를 사용하세요.

(다음에서 상속됨 Stream)
Equals(Object)

지정된 개체가 현재 개체와 같은지 확인합니다.

(다음에서 상속됨 Object)
Finalize()

SslStream에서 사용하는 모든 리소스를 해제합니다.

Flush()

버퍼링된 모든 데이터를 기본 디바이스에 씁니다.

FlushAsync()

이 스트림에 대한 모든 버퍼를 비동기적으로 지우고 버퍼링된 모든 데이터가 내부 디바이스에 비동기적으로 쓰여지도록 합니다.

(다음에서 상속됨 Stream)
FlushAsync(CancellationToken)

버퍼링된 모든 데이터를 기본 디바이스에 비동기적으로 씁니다.

FlushAsync(CancellationToken)

이 스트림에 대해 모든 버퍼를 비동기적으로 지우고 버퍼링된 데이터가 내부 디바이스에 쓰여지도록 하고 취소 요청을 모니터링합니다.

(다음에서 상속됨 Stream)
GetHashCode()

기본 해시 함수로 작동합니다.

(다음에서 상속됨 Object)
GetLifetimeService()
사용되지 않습니다.

이 인스턴스의 수명 정책을 제어하는 현재의 수명 서비스 개체를 검색합니다.

(다음에서 상속됨 MarshalByRefObject)
GetType()

현재 인스턴스의 Type을 가져옵니다.

(다음에서 상속됨 Object)
InitializeLifetimeService()
사용되지 않습니다.

이 인스턴스의 수명 정책을 제어하는 수명 서비스 개체를 가져옵니다.

(다음에서 상속됨 MarshalByRefObject)
MemberwiseClone()

현재 Object의 단순 복사본을 만듭니다.

(다음에서 상속됨 Object)
MemberwiseClone(Boolean)

현재 MarshalByRefObject 개체의 단순 복사본을 만듭니다.

(다음에서 상속됨 MarshalByRefObject)
NegotiateClientCertificateAsync(CancellationToken)

인증된 연결에서 클라이언트 인증서를 협상합니다.

ObjectInvariant()
사용되지 않습니다.

Contract에 대한 지원을 제공합니다.

(다음에서 상속됨 Stream)
Read(Byte[], Int32, Int32)

이 스트림에서 데이터를 읽어 지정된 배열에 저장합니다.

Read(Span<Byte>)

파생 클래스에서 재정의되면 현재 스트림에서 바이트의 시퀀스를 읽고, 읽은 바이트 수만큼 스트림 내에서 앞으로 이동합니다.

(다음에서 상속됨 Stream)
ReadAsync(Byte[], Int32, Int32)

현재 스트림에서 바이트 시퀀스를 읽고 읽은 바이트 수만큼 스트림에서 위치를 비동기적으로 앞으로 이동합니다.

(다음에서 상속됨 Stream)
ReadAsync(Byte[], Int32, Int32, CancellationToken)

이 스트림에서 데이터를 비동기식으로 읽어 지정된 바이트 배열의 범위에 저장합니다.

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

현재 스트림에서 바이트의 시퀀스를 비동기적으로 읽고 읽은 바이트 수만큼 스트림 내에서 앞으로 이동하며 취소 요청을 모니터링합니다.

(다음에서 상속됨 Stream)
ReadAsync(Memory<Byte>, CancellationToken)

이 스트림에서 데이터를 비동기식으로 읽어 지정된 메모리 범위에 저장합니다.

ReadAsync(Memory<Byte>, CancellationToken)

현재 스트림에서 바이트의 시퀀스를 비동기적으로 읽고 읽은 바이트 수만큼 스트림 내에서 앞으로 이동하며 취소 요청을 모니터링합니다.

(다음에서 상속됨 Stream)
ReadAtLeast(Span<Byte>, Int32, Boolean)

현재 스트림에서 최소 바이트 수를 읽고 읽은 바이트 수만큼 스트림 내의 위치를 이동합니다.

(다음에서 상속됨 Stream)
ReadAtLeastAsync(Memory<Byte>, Int32, Boolean, CancellationToken)

현재 스트림에서 최소 바이트 수를 비동기적으로 읽고, 읽은 바이트 수만큼 스트림 내의 위치를 이동하고, 취소 요청을 모니터링합니다.

(다음에서 상속됨 Stream)
ReadByte()

SslStream에서 바이트를 읽고 스트림 내 위치를 한 바이트씩 앞으로 이동하거나 스트림 끝일 경우 -1을 반환합니다.

ReadByte()

스트림에서 바이트를 읽고 스트림 내 위치를 한 바이트씩 앞으로 이동하거나 스트림 끝일 경우 -1을 반환합니다.

(다음에서 상속됨 Stream)
ReadExactly(Byte[], Int32, Int32)

count 현재 스트림에서 바이트 수를 읽고 스트림 내의 위치를 이동합니다.

(다음에서 상속됨 Stream)
ReadExactly(Span<Byte>)

현재 스트림에서 바이트를 읽고 스트림이 채워질 때까지 스트림 내의 buffer 위치를 이동합니다.

(다음에서 상속됨 Stream)
ReadExactlyAsync(Byte[], Int32, Int32, CancellationToken)

현재 스트림에서 바이트 수를 비동기적으로 읽고 count , 스트림 내의 위치를 발전시키고, 취소 요청을 모니터링합니다.

(다음에서 상속됨 Stream)
ReadExactlyAsync(Memory<Byte>, CancellationToken)

현재 스트림에서 바이트를 비동기적으로 읽고, 스트림이 채워질 때까지 buffer 스트림 내의 위치를 이동하고, 취소 요청을 모니터링합니다.

(다음에서 상속됨 Stream)
Seek(Int64, SeekOrigin)

NotSupportedException를 throw합니다.

SetLength(Int64)

기본 스트림의 길이를 설정합니다.

ShutdownAsync()

이 SslStream을 종료합니다.

ToString()

현재 개체를 나타내는 문자열을 반환합니다.

(다음에서 상속됨 Object)
Write(Byte[])

지정된 데이터를 이 스트림에 씁니다.

Write(Byte[], Int32, Int32)

지정된 버퍼와 오프셋을 사용하여 지정된 수의 Byte를 기본 스트림에 씁니다.

Write(ReadOnlySpan<Byte>)

파생 클래스를 재정의될 때 현재 스트림에 바이트의 시퀀스를 쓰고 쓰여진 바이트 수만큼 이 스트림 내에서 앞으로 이동합니다.

(다음에서 상속됨 Stream)
WriteAsync(Byte[], Int32, Int32)

현재 스트림에 바이트 시퀀스를 비동기적으로 쓰고 쓴 바이트 수만큼 이 스트림에서 현재 위치를 앞으로 이동합니다.

(다음에서 상속됨 Stream)
WriteAsync(Byte[], Int32, Int32, CancellationToken)

바이트 배열의 지정된 범위에서 데이터를 기본 스트림에 비동기식으로 씁니다.

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

바이트의 시퀀스를 현재 스트림에 비동기적으로 쓰고 쓰여진 바이트 수만큼 이 스트림 내의 현재 위치를 앞으로 이동한 후 취소 요청을 모니터링합니다.

(다음에서 상속됨 Stream)
WriteAsync(ReadOnlyMemory<Byte>, CancellationToken)

읽기 전용 바이트 메모리 범위에서 기본 스트림에 데이터를 비동기식으로 씁니다.

WriteAsync(ReadOnlyMemory<Byte>, CancellationToken)

바이트의 시퀀스를 현재 스트림에 비동기적으로 쓰고 쓰여진 바이트 수만큼 이 스트림 내의 현재 위치를 앞으로 이동한 후 취소 요청을 모니터링합니다.

(다음에서 상속됨 Stream)
WriteByte(Byte)

스트림의 현재 위치에 바이트를 쓰고 스트림 내 위치를 1바이트씩 앞으로 이동합니다.

(다음에서 상속됨 Stream)

확장 메서드

ConfigureAwait(IAsyncDisposable, Boolean)

비동기 일회용에서 반환되는 작업을 대기하는 방법을 구성합니다.

적용 대상

추가 정보