X509ChainPolicy Класс

Определение

Представляет политику цепочки, применяемую при создании цепочки сертификатов X509. Этот класс не наследуется.

public ref class X509ChainPolicy sealed
public sealed class X509ChainPolicy
type X509ChainPolicy = class
Public NotInheritable Class X509ChainPolicy
Наследование
X509ChainPolicy

Примеры

В следующем примере открывается личное хранилище сертификатов текущего пользователя, позволяет пользователю выбрать сертификат, а затем записывать сведения о сертификате и цепочке сертификатов в консоль. Выходные данные зависят от выбранного сертификата.

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

Комментарии

Каждый X509Certificate2 объект может иметь X509ChainPolicy свойство, указывающее политику, используемую в процессе проверки. Обратите внимание, что только X509Certificate2 объекты могут создавать X509ChainPolicy объект.

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

Имя Описание
X509ChainPolicy()

Инициализирует новый экземпляр класса X509ChainPolicy.

Свойства

Имя Описание
ApplicationPolicy

Возвращает коллекцию идентификаторов объектов (OID), указывающую, какие политики приложений или расширенные параметры использования ключей (EKUs) сертификат должен поддерживать.

CertificatePolicy

Возвращает коллекцию идентификаторов объектов (OID), указывающую, какие политики сертификатов должны поддерживать сертификат.

CustomTrustStore

Представляет коллекцию сертификатов, заменяющих доверие сертификатов по умолчанию.

DisableCertificateDownloads

Возвращает или задает значение, указывающее, может ли подсистема цепочки использовать расширение AIA для поиска неизвестных сертификатов издателя.

ExtraStore

Возвращает объект, представляющий дополнительную коллекцию сертификатов, которые можно искать в подсистеме цепочки при проверке цепочки сертификатов.

RevocationFlag

Возвращает или задает значения для флагов отзыва X509.

RevocationMode

Возвращает или задает значения для режима отзыва сертификата X509.

TrustMode

Режим определения корневого доверия для создания цепочки сертификатов.

UrlRetrievalTimeout

Возвращает или задает максимальное время, затраченное на проверку отзыва через Интернет или скачивая список отзыва сертификатов (CRL). Значение означает отсутствие ограничений Zero .

VerificationFlags

Возвращает флаги проверки для сертификата.

VerificationTime

Возвращает или задает время проверки цепочки.

VerificationTimeIgnored

Возвращает или задает значение, указывающее, следует ли использовать VerificationTime проверку цепочки или текущее системное время при создании цепочки сертификатов X.509.

Методы

Имя Описание
Clone()

Создает новый экземпляр политики цепочки с теми же параметрами, что и этот экземпляр.

Equals(Object)

Определяет, равен ли указанный объект текущему объекту.

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

Служит хэш-функцией по умолчанию.

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

Возвращает Type текущего экземпляра.

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

Создает неглубокую копию текущей Object.

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

Сбрасывает элементы в X509ChainPolicy значения по умолчанию.

ToString()

Возвращает строку, представляющую текущий объект.

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

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