Este artigo foi traduzido por máquina. Para visualizar o arquivo em inglês, marque a caixa de seleção Inglês. Você também pode exibir o texto Em inglês em uma janela pop-up, movendo o ponteiro do mouse sobre o texto.
Tradução
Inglês
Esta documentação foi arquivada e não está sendo atualizada.

Enumeração SslProtocols

Define as possíveis versões de SslProtocols.

Esta enumeração tem um atributo FlagsAttribute que permite uma combinação bit a bit de seus valores de membro.

Namespace:  System.Security.Authentication
Assembly:  System (em System.dll)

[FlagsAttribute]
public enum SslProtocols

Nome do membroDescrição
None Nenhum protocolo SSL é especificado.
Ssl2Especifica o protocolo SSL 2.0.SSL 2.0 foi substituído pelo protocolo TLS e é fornecida somente para compatibilidade com versões anteriores.
Ssl3Especifica o protocolo SSL 3,0.SSL 3,0 foi substituído pelo protocolo TLS e é fornecida somente para compatibilidade com versões anteriores.
TlsEspecifica o protocolo de segurança TLS 1.0.O protocolo TLS é definido em IETF RFC 2246.
Default Especifica que tanto Sockets camada (protocolo SSL) 3.0 ou TLS (Transport camada segurança) 1.0 são aceitáveis para comunicações seguras

O exemplo de código a seguir demonstra a criação de um TcpClient que usa o SslStream classe para se comunicar com um servidor.

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
{
    publicclass SslTcpClient 
    {   
        privatestatic Hashtable certificateErrors = new Hashtable();

        // The following method is invoked by the RemoteCertificateValidationDelegate.publicstaticbool ValidateServerCertificate(
              object sender,
              X509Certificate certificate,
              X509Chain chain,
              SslPolicyErrors sslPolicyErrors)
        {
           if (sslPolicyErrors == SslPolicyErrors.None)
                returntrue;

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

            // Do not allow this client to communicate with unauthenticated servers.returnfalse;
        }
        publicstaticvoid 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 = newchar[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();
        }
        privatestaticvoid DisplayUsage()
        { 
            Console.WriteLine("To start the client specify:");
            Console.WriteLine("clientSync machineName [serverName]");
            Environment.Exit(1);
        }
        publicstaticint 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 Professional x64 Edition, Windows XP Starter Edition, Windows Server 2003, Windows Server 2000 SP4, Windows Millennium Edition, Windows 98

o.NET Framework e.NET Compact Framework não oferecem suporte a todas as versões de cada plataforma. Para obter uma lista de versões suportadas, consulte Requisitos de sistema do .NET framework.

.NET Framework

Compatível com: 3.5, 3.0, 2.0
Mostrar: