SslStream クラスとは? わかりやすく解説

SslStream クラス

メモ : このクラスは、.NET Framework version 2.0新しく追加されたものです。

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

名前空間: System.Net.Security
アセンブリ: System (system.dll 内)
構文構文

Public Class SslStream
    Inherits AuthenticatedStream
public class SslStream : AuthenticatedStream
public ref class SslStream : public
 AuthenticatedStream
public class SslStream extends AuthenticatedStream
public class SslStream extends
 AuthenticatedStream
解説解説

SSL プロトコル使用すると、SslStream使用して送信されメッセージ機密性整合性チェックできますクライアントサーバー間で機密情報やり取りする場合には、SslStream によって提供されるような SSL 接続使用する必要がありますSslStream使用すると、ネットワーク上で送信中に第三者情報読み取った改変したりするのを防ぐことができます

SslStream インスタンスは、SslStream作成時にユーザー指定するストリーム使用してデータ送信します。この基になるストリーム指定するときにはSslStream閉じたときに基になるストリーム閉じかどうか指定するオプションあります通常SslStream クラスは、TcpClient クラスと TcpListener クラス使用されます。GetStream メソッドには、SslStream クラスでの使用適した NetworkStream が用意されています。

SslStream作成したら、サーバーオプションクライアント認証する必要がありますサーバーは、その ID証明する X509 証明書提供する必要があり、クライアントにもこれを提供することを要求できますSslStream使用して情報送信する前に認証を行う必要がありますクライアントは、認証完了するまでブロックする同期 AuthenticateAsClient メソッド、または認証完了するまでブロックせずに待機する非同期 BeginAuthenticateAsClient メソッド使用して認証開始しますサーバーは、同期 AuthenticateAsServer メソッドまたは非同期 BeginAuthenticateAsServer メソッド使用して認証開始しますクライアントサーバー両方認証を行う必要があります

認証は、SSPI (Security Support Provider) チャネル プロバイダによって処理されます。SslStream作成時に RemoteCertificateValidationCallback デリゲート指定することによって、クライアントサーバーの証明書の検証制御できるようになります。CertificateValidationCallback デリゲート指定すると、サーバー検証制御できますデリゲートによって参照されるメソッドには、リモートの証明書と、証明書検証時に SSPI検出したエラー含まれます。サーバーデリゲート指定した場合サーバークライアント認証要求したかどうかに関係なく、そのデリゲートメソッド呼び出されます。サーバークライアント認証要求しなかった場合サーバーデリゲートメソッドは、null 証明書証明書エラーの空の配列受け取ります

サーバークライアント認証を必要とする場合クライアント認証使用する 1 つ上の証明書指定する必要がありますクライアント複数の証明書がある場合には、クライアントは LocalCertificateSelectionCallback デリゲート提供してサーバー対す適切な証明書選択できますクライアントの証明書は、現在のユーザーの "My" 証明書ストア格納する必要があります証明書によるクライアント認証は、Ssl2 (SSL Version 2) プロトコルではサポートされていません。

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

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

要素

メンバ

サーバーオプションクライアント認証使用するセキュリティ プロトコル

SslProtocol プロパティおよび関連付けられた SslProtocols 列挙

キー交換アルゴリズム

KeyExchangeAlgorithm プロパティおよび関連付けられた ExchangeAlgorithmType 列挙

メッセージ整合性アルゴリズム

HashAlgorithm プロパティおよび関連付けられた HashAlgorithmType 列挙

メッセージ機密性アルゴリズム

CipherAlgorithm プロパティおよび関連付けられた CipherAlgorithmType 列挙

選択されアルゴリズム強度

KeyExchangeStrength、HashStrength、および CipherStrength の各プロパティ

認証成功したら、同期 Write メソッドまたは非同期 BeginWrite メソッド使用してデータ送信できますデータ受信するには、同期 Read メソッドまたは非同期 BeginRead メソッド使用します

基になるストリーム開いたままにしておくように SslStream に指定している場合は、ストリーム使い終わったときに、ユーザーストリーム閉じる必要があります

使用例使用例

SslStream クラス使用してクライアント通信する TcpListener作成するコード例次に示します

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, 
                    false, SslProtocols.Tls, 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;
        } 
    }
}

SslStream クラス使用してサーバー通信する TcpClient作成するコード例次に示します

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;
        }
    }
}
    
継承階層継承階層
System.Object
   System.MarshalByRefObject
     System.IO.Stream
       System.Net.Security.AuthenticatedStream
        System.Net.Security.SslStream
スレッド セーフスレッド セーフ
この型の public static (Visual Basic では Shared) メンバはすべて、スレッド セーフです。インスタンス メンバ場合は、スレッド セーフであるとは限りません。
プラットフォームプラットフォーム
バージョン情報バージョン情報
参照参照
関連項目
SslStream メンバ
System.Net.Security 名前空間
NegotiateStream クラス
AuthenticatedStream クラス



英和和英テキスト翻訳>> Weblio翻訳
英語⇒日本語日本語⇒英語
  

辞書ショートカット

すべての辞書の索引

「SslStream クラス」の関連用語

SslStream クラスのお隣キーワード
検索ランキング

   

英語⇒日本語
日本語⇒英語
   



SslStream クラスのページの著作権
Weblio 辞書 情報提供元は 参加元一覧 にて確認できます。

   
日本マイクロソフト株式会社日本マイクロソフト株式会社
© 2024 Microsoft.All rights reserved.

©2024 GRAS Group, Inc.RSS