Exporter (0) Imprimer
Développer tout

SslProtocols, énumération

Mise à jour : novembre 2007

Définit les versions possibles de SslProtocols.

Cette énumération possède un attribut FlagsAttribute qui permet la combinaison d'opérations de bits de ses valeurs de membres.

Espace de noms :  System.Security.Authentication
Assembly :  System (dans System.dll)

[FlagsAttribute]
public enum SslProtocols
/** @attribute FlagsAttribute */
public enum SslProtocols
public enum SslProtocols

Nom de membreDescription
NoneAucun protocole SSL n'est spécifié.
Ssl2Spécifie le protocole SSL 2.0. SSL 2.0 a été remplacé par le protocole TLS ; il n'est prévu que pour des raisons de compatibilité descendante.
Ssl3Spécifie le protocole SSL 3.0. SSL 3.0 a été remplacé par le protocole TLS ; il n'est prévu que pour des raisons de compatibilité descendante.
TlsSpécifie le protocole de sécurité TLS 1.0. Le protocole TLS est défini dans IETF RFC 2246.
DefaultSpécifie que le protocole SSL (Secure Sockets Layer) 3.0 ou TLS (Transport Layer Security) 1.0 est acceptable pour les communications sécurisées

L'exemple de code suivant illustre la création d'un TcpClient utilisant la classe SslStream pour communiquer avec un serveur.

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;
        }
    }
}



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

public class SslTcpClient
{
    private static Hashtable certificateErrors = new Hashtable();

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

    private static String CertificateErrorDescription(int problem)
    {
        // Initialize the error message dictionary if it is not yet available.
        if (certificateErrors.get_Count() == 0) {
            InitializeCertificateErrors();
        }
        String description = (String)certificateErrors.get_Item((Int32)problem);
        if (description == null) {
            description = String.Format("Unknown certificate error - 0x{0:x8}",
                System.Convert.ToString(problem));
        }
        return description;
    } //CertificateErrorDescription

    // The following method is invoked by the CertificateValidationDelegate.
    public static boolean 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;
    } //ValidateServerCertificate

    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, 8080);
        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.get_Message());
            if (e.get_InnerException() != null) {
                Console.WriteLine("Inner exception: {0}", 
                    e.get_InnerException().get_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>".
        ubyte messsage[] = Encoding.get_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.");
    } //RunClient

    static String ReadMessage(SslStream sslStream)
    {
        // Read the  message sent by the server.
        // The end of the message is signaled using the
        // "<EOF>" marker.
        ubyte buffer[] = new ubyte[2048];
        StringBuilder messageData = new StringBuilder();
        int bytes = -1;
        do {
            bytes = sslStream.Read(buffer, 0, buffer.get_Length());
            // Use Decoder class to convert from bytes to UTF8
            // in case a character spans two buffers.
            Decoder decoder = Encoding.get_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();
    } //ReadMessage

    private static void DisplayUsage()
    {
        Console.WriteLine("To start the client specify:");
        Console.WriteLine("clientSync machineName [serverName]");
        Environment.Exit(1);
    } //DisplayUsage

    public static void main(String[] args)
    {
        String serverCertificateName = null;
        String machineName = null;
        if (args == null || args.get_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.get_Length() < 2) {
            serverCertificateName = machineName;
        }
        else {
            serverCertificateName = args[1];
        }
        SslTcpClient.RunClient(machineName, serverCertificateName);
    } //main
} //SslTcpClient


Windows Vista, Windows XP SP2, Windows XP Media Center Edition, Windows XP Professionnel Édition x64, Windows XP Starter Edition, Windows Server 2003, Windows Server 2000 SP4, Windows Millennium Edition, Windows 98

Le .NET Framework et le .NET Compact Framework ne prennent pas en charge toutes les versions de chaque plateforme. Pour obtenir la liste des versions prises en charge, consultez Configuration requise du .NET Framework.

.NET Framework

Pris en charge dans : 3.5, 3.0, 2.0

Ajouts de la communauté

AJOUTER
Afficher:
© 2014 Microsoft