X509Chain Clase

Definición

Representa un motor de compilación de cadenas para los certificados X509Certificate2.

public ref class X509Chain : IDisposable
public ref class X509Chain
public class X509Chain : IDisposable
public class X509Chain
type X509Chain = class
    interface IDisposable
type X509Chain = class
Public Class X509Chain
Implements IDisposable
Public Class X509Chain
Herencia
X509Chain
Implementaciones

Ejemplos

En el ejemplo de código siguiente se abre el almacén de certificados personal del usuario actual, se le permite seleccionar un certificado y, a continuación, escribir información de la cadena de certificados y certificados en la consola. La salida depende del certificado que seleccione.

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

using namespace System;
using namespace System::Security::Cryptography;
using namespace System::Security::Cryptography::X509Certificates;
using namespace System::IO;

int main()
{
   //Create new X509 store from local certificate store.
   X509Store ^ store = gcnew X509Store( "MY",StoreLocation::CurrentUser );
   store->Open( static_cast<OpenFlags>(OpenFlags::OpenExistingOnly | OpenFlags::ReadWrite) );

   //Output store information.
   Console::WriteLine( "Store Information" );
   Console::WriteLine( "Number of certificates in the store: {0}", store->Certificates->Count );
   Console::WriteLine( "Store location: {0}", store->Location );
   Console::WriteLine( "Store name: {0} {1}", store->Name, Environment::NewLine );

   //Put certificates from the store into a collection so user can select one.
   X509Certificate2Collection ^ fcollection = dynamic_cast<X509Certificate2Collection^>(store->Certificates);
   X509Certificate2Collection ^ collection = X509Certificate2UI::SelectFromCollection(fcollection, "Select an X509 Certificate","Choose a certificate to examine.",X509SelectionFlag::SingleSelection);
   X509Certificate2 ^ certificate = collection[ 0 ];
   X509Certificate2UI::DisplayCertificate(certificate);

   //Output chain information of the selected certificate.
   X509Chain ^ ch = gcnew X509Chain;
   ch->ChainPolicy->RevocationMode = X509RevocationMode::Online;
   ch->Build( certificate );
   Console::WriteLine( "Chain Information" );
   Console::WriteLine( "Chain revocation flag: {0}", ch->ChainPolicy->RevocationFlag );
   Console::WriteLine( "Chain revocation mode: {0}", ch->ChainPolicy->RevocationMode );
   Console::WriteLine( "Chain verification flag: {0}", ch->ChainPolicy->VerificationFlags );
   Console::WriteLine( "Chain verification time: {0}", ch->ChainPolicy->VerificationTime );
   Console::WriteLine( "Chain status length: {0}", ch->ChainStatus->Length );
   Console::WriteLine( "Chain application policy count: {0}", ch->ChainPolicy->ApplicationPolicy->Count );
   Console::WriteLine( "Chain certificate policy count: {0} {1}", ch->ChainPolicy->CertificatePolicy->Count, Environment::NewLine );

   //Output chain element information.
   Console::WriteLine( "Chain Element Information" );
   Console::WriteLine( "Number of chain elements: {0}", ch->ChainElements->Count );
   Console::WriteLine( "Chain elements synchronized? {0} {1}", ch->ChainElements->IsSynchronized, Environment::NewLine );
   System::Collections::IEnumerator^ myEnum = ch->ChainElements->GetEnumerator();
   while ( myEnum->MoveNext() )
   {
      X509ChainElement ^ element = safe_cast<X509ChainElement ^>(myEnum->Current);
      Console::WriteLine( "Element issuer name: {0}", element->Certificate->Issuer );
      Console::WriteLine( "Element certificate valid until: {0}", element->Certificate->NotAfter );
      Console::WriteLine( "Element certificate is valid: {0}", element->Certificate->Verify() );
      Console::WriteLine( "Element error status length: {0}", element->ChainElementStatus->Length );
      Console::WriteLine( "Element information: {0}", element->Information );
      Console::WriteLine( "Number of element extensions: {0}{1}", element->Certificate->Extensions->Count, Environment::NewLine );
      if ( ch->ChainStatus->Length > 1 )
      {
         for ( int index = 0; index < element->ChainElementStatus->Length; index++ )
         {
            Console::WriteLine( element->ChainElementStatus[ index ].Status );
            Console::WriteLine( element->ChainElementStatus[ index ].StatusInformation );
         }
      }
   }

   store->Close();
}
using System;
using System.Security.Cryptography;
using System.Security.Cryptography.X509Certificates;
using System.IO;

class TestX509Chain
{
    static void Main(string[] args)
    {
        //Create new X509 store from local certificate store.
        X509Store store = new X509Store("MY", StoreLocation.CurrentUser);
        store.Open(OpenFlags.OpenExistingOnly | OpenFlags.ReadWrite);

        //Output store information.
        Console.WriteLine ("Store Information");
        Console.WriteLine ("Number of certificates in the store: {0}", store.Certificates.Count);
        Console.WriteLine ("Store location: {0}", store.Location);
        Console.WriteLine ("Store name: {0} {1}", store.Name, Environment.NewLine);
    
        //Put certificates from the store into a collection so user can select one.
        X509Certificate2Collection fcollection = (X509Certificate2Collection)store.Certificates;
        X509Certificate2Collection collection = X509Certificate2UI.SelectFromCollection(fcollection, "Select an X509 Certificate", "Choose a certificate to examine.", X509SelectionFlag.SingleSelection);
        X509Certificate2 certificate = collection[0];
        X509Certificate2UI.DisplayCertificate(certificate);

        //Output chain information of the selected certificate.
        X509Chain ch = new X509Chain();
        ch.ChainPolicy.RevocationMode = X509RevocationMode.Online;
        ch.Build (certificate);
        Console.WriteLine ("Chain Information");
        Console.WriteLine ("Chain revocation flag: {0}", ch.ChainPolicy.RevocationFlag);
        Console.WriteLine ("Chain revocation mode: {0}", ch.ChainPolicy.RevocationMode);
        Console.WriteLine ("Chain verification flag: {0}", ch.ChainPolicy.VerificationFlags);
        Console.WriteLine ("Chain verification time: {0}", ch.ChainPolicy.VerificationTime);
        Console.WriteLine ("Chain status length: {0}", ch.ChainStatus.Length);
        Console.WriteLine ("Chain application policy count: {0}", ch.ChainPolicy.ApplicationPolicy.Count);
        Console.WriteLine ("Chain certificate policy count: {0} {1}", ch.ChainPolicy.CertificatePolicy.Count, Environment.NewLine);

        //Output chain element information.
        Console.WriteLine ("Chain Element Information");
        Console.WriteLine ("Number of chain elements: {0}", ch.ChainElements.Count);
        Console.WriteLine ("Chain elements synchronized? {0} {1}", ch.ChainElements.IsSynchronized, Environment.NewLine);
    
        foreach (X509ChainElement element in ch.ChainElements)
        {
            Console.WriteLine ("Element issuer name: {0}", element.Certificate.Issuer);
            Console.WriteLine ("Element certificate valid until: {0}", element.Certificate.NotAfter);
            Console.WriteLine ("Element certificate is valid: {0}", element.Certificate.Verify ());
            Console.WriteLine ("Element error status length: {0}", element.ChainElementStatus.Length);
            Console.WriteLine ("Element information: {0}", element.Information);
            Console.WriteLine ("Number of element extensions: {0}{1}", element.Certificate.Extensions.Count, Environment.NewLine);

            if (ch.ChainStatus.Length > 1)
            {
                for (int index = 0; index < element.ChainElementStatus.Length; index++)
                {
                    Console.WriteLine (element.ChainElementStatus[index].Status);
                    Console.WriteLine (element.ChainElementStatus[index].StatusInformation);
                }
            }
        }
        store.Close();
    }
}
Imports System.Security.Cryptography
Imports System.Security.Cryptography.X509Certificates
Imports System.IO

Class TestX509Chain

    Shared Sub Main(ByVal args() As String)
        'Create new X509 store from local certificate store.
        Dim store As New X509Store("MY", StoreLocation.CurrentUser)
        store.Open(OpenFlags.OpenExistingOnly Or OpenFlags.ReadWrite)

        'Output store information.
        Console.WriteLine("Store Information")
        Console.WriteLine("Number of certificates in the store: {0}", store.Certificates.Count)
        Console.WriteLine("Store location: {0}", store.Location)
        Console.WriteLine("Store name: {0} {1}", store.Name, Environment.NewLine)

        'Put certificates from the store into a collection so user can select one.
        Dim fcollection As X509Certificate2Collection = CType(store.Certificates, X509Certificate2Collection)
        Dim collection As X509Certificate2Collection = X509Certificate2UI.SelectFromCollection(fcollection, "Select an X509 Certificate", "Choose a certificate to examine.", X509SelectionFlag.SingleSelection)
        Dim certificate As X509Certificate2 = collection(0)
        X509Certificate2UI.DisplayCertificate(certificate)

        'Output chain information of the selected certificate.
        Dim ch As New X509Chain()
        ch.ChainPolicy.RevocationMode = X509RevocationMode.Online
        ch.Build(certificate)
        Console.WriteLine("Chain Information")
        Console.WriteLine("Chain revocation flag: {0}", ch.ChainPolicy.RevocationFlag)
        Console.WriteLine("Chain revocation mode: {0}", ch.ChainPolicy.RevocationMode)
        Console.WriteLine("Chain verification flag: {0}", ch.ChainPolicy.VerificationFlags)
        Console.WriteLine("Chain verification time: {0}", ch.ChainPolicy.VerificationTime)
        Console.WriteLine("Chain status length: {0}", ch.ChainStatus.Length)
        Console.WriteLine("Chain application policy count: {0}", ch.ChainPolicy.ApplicationPolicy.Count)
        Console.WriteLine("Chain certificate policy count: {0} {1}", ch.ChainPolicy.CertificatePolicy.Count, Environment.NewLine)

        'Output chain element information.
        Console.WriteLine("Chain Element Information")
        Console.WriteLine("Number of chain elements: {0}", ch.ChainElements.Count)
        Console.WriteLine("Chain elements synchronized? {0} {1}", ch.ChainElements.IsSynchronized, Environment.NewLine)

        Dim element As X509ChainElement
        For Each element In ch.ChainElements
            Console.WriteLine("Element issuer name: {0}", element.Certificate.Issuer)
            Console.WriteLine("Element certificate valid until: {0}", element.Certificate.NotAfter)
            Console.WriteLine("Element certificate is valid: {0}", element.Certificate.Verify())
            Console.WriteLine("Element error status length: {0}", element.ChainElementStatus.Length)
            Console.WriteLine("Element information: {0}", element.Information)
            Console.WriteLine("Number of element extensions: {0}{1}", element.Certificate.Extensions.Count, Environment.NewLine)

            If ch.ChainStatus.Length > 1 Then
                Dim index As Integer
                For index = 0 To element.ChainElementStatus.Length
                    Console.WriteLine(element.ChainElementStatus(index).Status)
                    Console.WriteLine(element.ChainElementStatus(index).StatusInformation)
                Next index
            End If
        Next element
        store.Close()
    End Sub
End Class

Comentarios

El X509Chain objeto tiene un estado de error global denominado ChainStatus que se debe usar para la validación de certificados. Las reglas que rigen la validación de certificados son complejas y es fácil simplificar la lógica de validación ignorando el estado de error de uno o varios de los elementos implicados. El estado de error global tiene en cuenta el estado de cada elemento de la cadena.

Importante

A partir de .NET Framework 4.6, este tipo implementa la IDisposable interfaz . Cuando haya terminado de utilizar el tipo, debe desecharlo directa o indirectamente. Para eliminar el tipo directamente, llame a su método Dispose en un bloque try/catch. Para deshacerse de él indirectamente, use una construcción de lenguaje como using (en C#) o Using (en Visual Basic). Para más información, vea la sección "Uso de objetos que implementan IDisposable" en el tema de la interfaz IDisposable.

En el caso de las aplicaciones destinadas a .NET Framework 4.5.2 y versiones anteriores, la X509Chain clase no implementa la IDisposable interfaz y, por lo tanto, no tiene un Dispose método.

Constructores

X509Chain()

Inicializa una nueva instancia de la clase X509Chain.

X509Chain(Boolean)

Inicializa una nueva instancia de la clase X509Chain especificando un valor que indica si se debe usar el contexto de la máquina.

X509Chain(IntPtr)

Inicializa una nueva instancia de la clase X509Chain mediante un identificador IntPtr de una cadena X.509.

Propiedades

ChainContext

Obtiene un identificador de una cadena X.509.

ChainElements

Obtiene una colección de objetos X509ChainElement.

ChainPolicy

Obtiene o establece el objeto X509ChainPolicy que se va a usar al compilar una cadena de certificados X.509.

ChainStatus

Obtiene el estado de todos los elementos de un objeto X509Chain.

SafeHandle

Obtiene un identificador seguro para esta instancia de X509Chain.

Métodos

Build(X509Certificate2)

Compila una cadena X.509 usando la directiva especificada en X509ChainPolicy.

Create()

Crea un objeto X509Chain después de consultar la asignación definida en el archivo CryptoConfig, y asigna la cadena a esa asignación.

Dispose()

Libera todos los recursos utilizados por este objeto X509Chain.

Dispose(Boolean)

Libera los recursos no administrados que usa X509Chain y, de forma opcional, libera los recursos administrados.

Equals(Object)

Determina si el objeto especificado es igual que el objeto actual.

(Heredado de Object)
GetHashCode()

Sirve como la función hash predeterminada.

(Heredado de Object)
GetType()

Obtiene el Type de la instancia actual.

(Heredado de Object)
MemberwiseClone()

Crea una copia superficial del Object actual.

(Heredado de Object)
Reset()

Borra el objeto X509Chain actual.

ToString()

Devuelve una cadena que representa el objeto actual.

(Heredado de Object)

Se aplica a