SslStream クラス

定義

Secure Socket Layer (SSL) セキュリティ プロトコルを使用し、サーバーと、オプションでクライアントを認証するクライアント サーバー通信に使用されるストリームを提供します。

public ref class SslStream : System::Net::Security::AuthenticatedStream
public class SslStream : System.Net.Security.AuthenticatedStream
type SslStream = class
    inherit AuthenticatedStream
type SslStream = class
    inherit AuthenticatedStream
    interface IDisposable
Public Class SslStream
Inherits AuthenticatedStream
継承
継承
実装

次のコード例は、クラスを使用SslStreamしてTcpListenerクライアントと通信するコードを作成する方法を示しています。

#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

次のコード例では、クラスを使用SslStreamしてTcpClientサーバーと通信する a を作成する方法を示します。

#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使用されます。 このメソッドは GetStreamNetworkStream クラスでの使用に適しています SslStream

サーバーを SslStream作成した後、必要に応じてクライアントを認証する必要があります。 サーバーは、ID の証明を確立し、クライアントにも要求できる X509 証明書を提供する必要があります。 を使用して情報を送信する前に、認証を実行する SslStream必要があります。 クライアントは、認証が完了するまでブロックする同期 AuthenticateAsClient メソッドまたは非同期 BeginAuthenticateAsClient メソッドを使用して認証を開始します。非同期メソッドは、認証の完了を待つのをブロックしません。 サーバーは、同期 AuthenticateAsServer または非同期 BeginAuthenticateAsServer の方法を使用して認証を開始します。 クライアントとサーバーの両方が認証を開始する必要があります。

認証は、セキュリティ サポート プロバイダー (SSPI) チャネル プロバイダーによって処理されます。 クライアントには、作成時にデリゲートを指定 RemoteCertificateValidationCallback して、サーバーの証明書の検証を制御する機会が SslStream与えられます。 サーバーは、デリゲートを指定して検証を RemoteCertificateValidationCallback 制御することもできます。 デリゲートによって参照されるメソッドには、リモート パーティの証明書と、証明書の検証中に SSPI で発生したエラーが含まれます。 サーバーがデリゲートを指定した場合、サーバーがクライアント認証を要求したかどうかに関係なく、デリゲートのメソッドが呼び出されることに注意してください。 サーバーがクライアント認証を要求しなかった場合、サーバーの委任メソッドは null 証明書と証明書エラーの空の配列を受け取ります。

サーバーでクライアント認証が必要な場合、クライアントは認証用に 1 つ以上の証明書を指定する必要があります。 クライアントに複数の証明書がある場合、クライアントは代理人を LocalCertificateSelectionCallback 提供して、サーバーの正しい証明書を選択できます。 クライアントの証明書は、現在のユーザーの "My" 証明書ストアに配置する必要があります。 証明書を使用したクライアント認証は、(SSL バージョン 2) プロトコルでは Ssl2 サポートされていません。

認証に失敗した場合は、その認証SslStreamAuthenticationException受け取り、使用できなくなります。 ガベージ コレクターが収集できるように、このオブジェクトを閉じて、そのオブジェクトへの参照をすべて削除する必要があります。

SSL ハンドシェイクとも呼ばれる認証プロセスが成功すると、サーバーの ID (および必要に応じてクライアント) が確立され SslStream 、クライアントとサーバーがメッセージを交換するために使用できます。 情報を送受信する前に、クライアントとサーバーが SslStream 提供するセキュリティ サービスとレベルを確認して、選択したプロトコル、アルゴリズム、および強度が整合性と機密性の要件を満たしているかどうかを判断する必要があります。 現在の設定で十分でない場合は、ストリームを閉じる必要があります。 およびプロパティを使用して提供されるSslStreamセキュリティ サービスをIsEncryptedIsSigned確認できます。 次の表は、認証、暗号化、およびデータ署名に使用される暗号化設定を報告する要素を示しています。

要素 メンバー
サーバーの認証に使用されるセキュリティ プロトコルと、必要に応じてクライアント。 SslProtocolプロパティと関連SslProtocolsする列挙体。
キー交換アルゴリズム。 KeyExchangeAlgorithmプロパティと関連ExchangeAlgorithmTypeする列挙体。
メッセージ整合性アルゴリズム。 HashAlgorithmプロパティと関連HashAlgorithmTypeする列挙体。
メッセージの機密性アルゴリズム。 CipherAlgorithmプロパティと関連CipherAlgorithmTypeする列挙体。
選択したアルゴリズムの長所。 KeyExchangeStrengthHashStrengthおよびCipherStrengthプロパティ。

認証が成功したら、同期 Write または非同期 BeginWrite の方法を使用してデータを送信できます。 同期メソッドまたは非同期ReadBeginReadメソッドを使用してデータを受信できます。

基になるストリームを SslStream 開いたままにする必要があることを指定した場合は、使用が完了したときにそのストリームを閉じる責任があります。

注意

オブジェクトを作成 SslStream するアプリケーションが標準ユーザーの資格情報を使用して実行される場合、アプリケーションはローカル コンピューター ストアにインストールされている証明書にアクセスできません。そのためには、ユーザーに明示的にアクセス許可が付与されていない限りです。

SslStream は、内部ストリームからスローされたときにタイムアウトが他 IOException のストリームと共に、呼び出し元によって致命的として扱われることを前提としています。 タイムアウト後にインスタンスを SslStream 再利用すると、ガベージが返されます。 このような場合、アプリケーションは例外をSslStreamスローする必要がありますClose

.NET Framework 4.6 には、安全でない暗号およびハッシュ アルゴリズムの接続をブロックする、新しいセキュリティ機能が含まれています。 HttpClient、HttpWebRequest、FTPClient、SmtpClient、SslStream などの API を介して TLS/SSL を使用して、.NET Framework 4.6 を対象とするアプリケーションは、既定でセキュリティが強化された動作を取得します。

開発者は、既存の SSL3 サービスまたは TLS と RC4 サービスとの相互運用性を維持するために、この動作をオプトアウトすることができます。 この記事 では、新しい動作が無効になるようにコードを変更する方法について説明します。

.NET Framework 4.7 では、TLS バージョンを指定せず、代わりに SCHANNEL でシステムの既定値として定義されている TLS バージョンを使用する SslStream を認証するメソッドの新しいオーバーロードが追加されます。 これらのメソッドをアプリで使用すると、TLS バージョンのベスト プラクティスが時間の経過と同時に変化し、アプリを再構築して再デプロイすることなく、後で既定値を変更できるようになります。

.NET Frameworkに関するトランスポート層セキュリティ (TLS) のベスト プラクティスも参照してください。

コンストラクター

SslStream(Stream)

指定した Stream を使用して SslStream クラスの新しいインスタンスを初期化します。

SslStream(Stream, Boolean)

指定した Stream とストリームを閉じる動作を使用して、SslStream クラスの新しいインスタンスを初期化します。

SslStream(Stream, Boolean, RemoteCertificateValidationCallback)

指定した Stream、ストリームを閉じる動作、および証明書検証デリゲートを使用して、SslStream クラスの新しいインスタンスを初期化します。

SslStream(Stream, Boolean, RemoteCertificateValidationCallback, LocalCertificateSelectionCallback)

指定した Stream、ストリームを閉じる動作、証明書検証デリゲート、および証明書選択デリゲートを使用して、SslStream クラスの新しいインスタンスを初期化します。

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

指定した Stream を使用して SslStream クラスの新しいインスタンスを初期化します。

プロパティ

CanRead

基になるストリームが読み取り可能かどうかを示す Boolean 値を取得します。

CanSeek

基になるストリームがシークできるかどうかを示す Boolean 値を取得します。

CanTimeout

基になるストリームがタイムアウトをサポートしているかどうかを示す Boolean 値を取得します。

CanWrite

基になるストリームが書き込み可能かどうかを示す Boolean 値を取得します。

CheckCertRevocationStatus

証明書検証プロセスで、証明書失効リストを照合するかどうかを示す Boolean 値を取得します。

CipherAlgorithm

この SslStream が使用する一括暗号化アルゴリズムを識別する値を取得します。

CipherStrength

この SslStream が使用する暗号アルゴリズムの強度を識別する値を取得します。

HashAlgorithm

メッセージ認証コード (MAC: Message Authentication Code) の生成に使用するアルゴリズムを取得します。

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 バイトを読み取り、ストリーム内の位置を 1 バイト進めます。または、ストリームの末尾の場合は -1 を返します。

ReadByte()

ストリームから 1 バイトを読み取り、ストリーム内の位置を 1 バイト進めます。ストリームの末尾の場合は -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 をスローします。

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)

非同期の破棄可能から返されるタスク上での待機がどのように実行されるかを構成します。

適用対象

こちらもご覧ください