X509Chain Класс

Определение

Представляет обработчик для создания цепочки для сертификатов X509Certificate2.Represents a chain-building engine for X509Certificate2 certificates.

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
Наследование
X509Chain
Реализации

Примеры

Следующий пример кода открывает личное хранилище сертификатов текущего пользователя, позволяет выбрать сертификат, а затем записывает сведения о сертификате и цепочке сертификатов в консоль.The following code example opens the current user's personal certificate store, allows you to select a certificate, then writes certificate and certificate chain information to the console. Выходные данные зависят от выбранного сертификата.The output depends on the certificate you select.

#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

Комментарии

X509ChainОбъект имеет глобальное состояние ошибки с именем ChainStatus , которое должно использоваться для проверки сертификата.The X509Chain object has a global error status called ChainStatus that should be used for certificate validation. Правила, управляющие проверкой сертификата, являются сложными, и можно легко упростить логику проверки, игнорируя состояние ошибки одного или нескольких участвующих элементов.The rules governing certificate validation are complex, and it is easy to oversimplify the validation logic by ignoring the error status of one or more of the elements involved. Глобальное состояние ошибки учитывает состояние каждого элемента в цепочке.The global error status takes into consideration the status of each element in the chain.

Важно!

Начиная с платформа .NET Framework 4,6, этот тип реализует IDisposable интерфейс.Starting with the .NET Framework 4.6, this type implements the IDisposable interface. По окончании использования выдаленную ему память следует прямо или косвенно освободить.When you have finished using the type, you should dispose of it either directly or indirectly. Чтобы сделать это прямо, вызовите его метод Dispose в блоке try/catch.To dispose of the type directly, call its Dispose method in a try/catch block. Чтобы сделать это косвенно, используйте языковые конструкции, такие как using (в C#) или Using (в Visual Basic).To dispose of it indirectly, use a language construct such as using (in C#) or Using (in Visual Basic). Дополнительные сведения см. в разделе "Использование объекта, реализующего IDisposable" в статье об интерфейсе IDisposable.For more information, see the "Using an Object that Implements IDisposable" section in the IDisposable interface topic.

Для приложений, предназначенных для платформа .NET Framework 4.5.2 и более ранних версий, X509Chain класс не реализует IDisposable интерфейс и поэтому не имеет Dispose метода.For apps that target the .NET Framework 4.5.2 and earlier versions, the X509Chain class does not implement the IDisposable interface and therefore does not have a Dispose method.

Конструкторы

X509Chain()

Инициализирует новый экземпляр класса X509Chain.Initializes a new instance of the X509Chain class.

X509Chain(Boolean)

Инициализирует новый экземпляр класса X509Chain, который задает значение, определяющее, должен ли использоваться контекст компьютера.Initializes a new instance of the X509Chain class specifying a value that indicates whether the machine context should be used.

X509Chain(IntPtr)

Инициализирует в цепочке X.509 новый экземпляр класса X509Chain с помощью дескриптора IntPtr.Initializes a new instance of the X509Chain class using an IntPtr handle to an X.509 chain.

Свойства

ChainContext

Возвращает дескриптор цепочки X.509.Gets a handle to an X.509 chain.

ChainElements

Возвращает коллекцию объектов X509ChainElement.Gets a collection of X509ChainElement objects.

ChainPolicy

Возвращает или задает объект X509ChainPolicy, используемый для создания цепочки сертификатов X.509.Gets or sets the X509ChainPolicy to use when building an X.509 certificate chain.

ChainStatus

Возвращает состояние каждого элемента в объекте X509Chain.Gets the status of each element in an X509Chain object.

SafeHandle

Получает безопасный дескриптор для этого экземпляра X509Chain.Gets a safe handle for this X509Chain instance.

Методы

Build(X509Certificate2)

Создает цепочку X.509 с использованием политики, указанной в объекте X509ChainPolicy.Builds an X.509 chain using the policy specified in X509ChainPolicy.

Create()

Создает объект X509Chain после запроса сопоставления, заданного в файле CryptoConfig, и сопоставляет цепочку с имеющимся сопоставлением.Creates an X509Chain object after querying for the mapping defined in the CryptoConfig file, and maps the chain to that mapping.

Dispose()

Освобождает все ресурсы, используемые этим классом X509Chain.Releases all of the resources used by this X509Chain.

Dispose(Boolean)

Освобождает неуправляемые ресурсы, используемые объектом X509Chain, а при необходимости освобождает также управляемые ресурсы.Releases the unmanaged resources used by this X509Chain, and optionally releases the managed resources.

Equals(Object)

Определяет, равен ли указанный объект текущему объекту.Determines whether the specified object is equal to the current object.

(Унаследовано от Object)
Finalize()

Высвобождает неуправляемые ресурсы, используемые этим экземпляром.Releases the unmanaged resources held by this instance.

GetHashCode()

Служит хэш-функцией по умолчанию.Serves as the default hash function.

(Унаследовано от Object)
GetType()

Возвращает объект Type для текущего экземпляра.Gets the Type of the current instance.

(Унаследовано от Object)
MemberwiseClone()

Создает неполную копию текущего объекта Object.Creates a shallow copy of the current Object.

(Унаследовано от Object)
Reset()

Очищает текущий объект X509Chain.Clears the current X509Chain object.

ToString()

Возвращает строку, представляющую текущий объект.Returns a string that represents the current object.

(Унаследовано от Object)

Применяется к