X509Store Classe

Définition

Représente un magasin X.509, magasin physique où les certificats sont conservés et gérés.Represents an X.509 store, which is a physical store where certificates are persisted and managed. Cette classe ne peut pas être héritée.This class cannot be inherited.

public ref class X509Store sealed : IDisposable
public ref class X509Store sealed
public sealed class X509Store : IDisposable
public sealed class X509Store
type X509Store = class
    interface IDisposable
type X509Store = class
Public NotInheritable Class X509Store
Implements IDisposable
Public NotInheritable Class X509Store
Héritage
X509Store
Implémente

Exemples

Cette section contient deux exemples.This section contains two examples. Le premier exemple montre comment vous pouvez ouvrir des magasins X. 509 standard et répertorier le nombre de certificats dans chacun d’eux.The first example demonstrates how you can open standard X.509 stores and list the number of certificates in each.

Le deuxième exemple montre comment vous pouvez ajouter et supprimer des certificats uniques et des plages de certificats.The second example demonstrates how you can add and remove single certificates and ranges of certificates.

Exemple 1Example 1

Cet exemple tente d’ouvrir chaque magasin standard dans chaque emplacement standard sur l’ordinateur actuel.This example tries to open each standard store in each standard location on the current computer. Il affiche un résumé qui indique si chaque magasin existe et, le cas échéant, le nombre de certificats qu’il contient.It prints a summary that shows whether each store exists and, if so, the number of certificates it contains.

L’exemple crée un objet X509Store pour chaque combinaison de nom standard et d’emplacement standard.The example creates an X509Store object for each combination of standard name and standard location. Elle appelle la méthode Open avec l’indicateur OpenFlags.OpenExistingOnly, qui ouvre le magasin physique uniquement s’il existe déjà.It calls the Open method with the OpenFlags.OpenExistingOnly flag, which opens the physical store only if it already exists. Si le magasin physique existe, l’exemple utilise les propriétés Name, Locationet Certificates pour afficher le nombre de certificats dans le magasin.If the physical store exists, the example uses the Name, Location, and Certificates properties to display the number of certificates in the store.

using System;
using System.Security.Cryptography;
using System.Security.Cryptography.X509Certificates;

public class Example
{
    static void Main()
    {
        Console.WriteLine("\r\nExists Certs Name and Location");
        Console.WriteLine("------ ----- -------------------------");

        foreach (StoreLocation storeLocation in (StoreLocation[]) 
            Enum.GetValues(typeof(StoreLocation)))
        {
            foreach (StoreName storeName in (StoreName[]) 
                Enum.GetValues(typeof(StoreName)))
            {
                X509Store store = new X509Store(storeName, storeLocation);

                try
                {
                    store.Open(OpenFlags.OpenExistingOnly);

                    Console.WriteLine("Yes    {0,4}  {1}, {2}", 
                        store.Certificates.Count, store.Name, store.Location);
                }   
                catch (CryptographicException)
                {
                    Console.WriteLine("No           {0}, {1}", 
                        store.Name, store.Location);
                }
            }
            Console.WriteLine();
        }
    }
}

/* This example produces output similar to the following:

Exists Certs Name and Location
------ ----- -------------------------
Yes       1  AddressBook, CurrentUser
Yes      25  AuthRoot, CurrentUser
Yes     136  CA, CurrentUser
Yes      55  Disallowed, CurrentUser
Yes      20  My, CurrentUser
Yes      36  Root, CurrentUser
Yes       0  TrustedPeople, CurrentUser
Yes       1  TrustedPublisher, CurrentUser

No           AddressBook, LocalMachine
Yes      25  AuthRoot, LocalMachine
Yes     131  CA, LocalMachine
Yes      55  Disallowed, LocalMachine
Yes       3  My, LocalMachine
Yes      36  Root, LocalMachine
Yes       0  TrustedPeople, LocalMachine
Yes       1  TrustedPublisher, LocalMachine

 */
Option Strict On

Imports System.Security.Cryptography
Imports System.Security.Cryptography.X509Certificates

Module Example

    Sub Main()

        Console.WriteLine(vbCrLf & "Exists Certs Name and Location")
        Console.WriteLine("------ ----- -------------------------")

        For Each storeLocation As StoreLocation In _
                CType([Enum].GetValues(GetType(StoreLocation)), StoreLocation())

            For Each storeName As StoreName In _
                    CType([Enum].GetValues(GetType(StoreName)), StoreName())

                Dim store As New X509Store(StoreName, StoreLocation)

                Try
                    store.Open(OpenFlags.OpenExistingOnly)
                    Console.WriteLine("Yes    {0,4}  {1}, {2}", _
                        store.Certificates.Count, store.Name, store.Location)
                Catch e As CryptographicException
                    Console.WriteLine("No           {0}, {1}", _
                        store.Name, store.Location)
                End Try
            Next

            Console.WriteLine()
        Next
    End Sub
End Module

' This example produces output similar to the following:

'Exists Certs Name and Location
'------ ----- -------------------------
'Yes       1  AddressBook, CurrentUser
'Yes      25  AuthRoot, CurrentUser
'Yes     136  CA, CurrentUser
'Yes      55  Disallowed, CurrentUser
'Yes      20  My, CurrentUser
'Yes      36  Root, CurrentUser
'Yes       0  TrustedPeople, CurrentUser
'Yes       1  TrustedPublisher, CurrentUser

'No           AddressBook, LocalMachine
'Yes      25  AuthRoot, LocalMachine
'Yes     131  CA, LocalMachine
'Yes      55  Disallowed, LocalMachine
'Yes       3  My, LocalMachine
'Yes      36  Root, LocalMachine
'Yes       0  TrustedPeople, LocalMachine
'Yes       1  TrustedPublisher, LocalMachine

Exemple 2Example 2

Cet exemple ouvre un magasin de certificats X. 509, ajoute et supprime des certificats, puis ferme le magasin.This example opens an X.509 certificate store, adds and deletes certificates, and then closes the store. Il part du principe que vous avez trois certificats à ajouter à un magasin local et à supprimer de celui-ci.It assumes that you have three certificates to add to and remove from a local store.

#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 called teststore from the local certificate store.
   X509Store ^ store = gcnew X509Store( "teststore",StoreLocation::CurrentUser );
   store->Open( OpenFlags::ReadWrite );
   X509Certificate2 ^ certificate = gcnew X509Certificate2;
   
   //Create certificates from certificate files.
   //You must put in a valid path to three certificates in the following constructors.
   X509Certificate2 ^ certificate1 = gcnew X509Certificate2( "c:\\mycerts\\*****.cer" );
   X509Certificate2 ^ certificate2 = gcnew X509Certificate2( "c:\\mycerts\\*****.cer" );
   X509Certificate2 ^ certificate5 = gcnew X509Certificate2( "c:\\mycerts\\*****.cer" );
   
   //Create a collection and add two of the certificates.
   X509Certificate2Collection ^ collection = gcnew X509Certificate2Collection;
   collection->Add( certificate2 );
   collection->Add( certificate5 );
   
   //Add certificates to the store.
   store->Add( certificate1 );
   store->AddRange( collection );
   X509Certificate2Collection ^ storecollection = dynamic_cast<X509Certificate2Collection^>(store->Certificates);
   Console::WriteLine( "Store name: {0}", store->Name );
   Console::WriteLine( "Store location: {0}", store->Location );
   System::Collections::IEnumerator^ myEnum = storecollection->GetEnumerator();
   while ( myEnum->MoveNext() )
   {
      X509Certificate2 ^ x509 = safe_cast<X509Certificate2 ^>(myEnum->Current);
      Console::WriteLine( "certificate name: {0}", x509->Subject );
   }

   
   //Remove a certificate.
   store->Remove( certificate1 );
   X509Certificate2Collection ^ storecollection2 = dynamic_cast<X509Certificate2Collection^>(store->Certificates);
   Console::WriteLine( "{1}Store name: {0}", store->Name, Environment::NewLine );
   System::Collections::IEnumerator^ myEnum1 = storecollection2->GetEnumerator();
   while ( myEnum1->MoveNext() )
   {
      X509Certificate2 ^ x509 = safe_cast<X509Certificate2 ^>(myEnum1->Current);
      Console::WriteLine( "certificate name: {0}", x509->Subject );
   }

   
   //Remove a range of certificates.
   store->RemoveRange( collection );
   X509Certificate2Collection ^ storecollection3 = dynamic_cast<X509Certificate2Collection^>(store->Certificates);
   Console::WriteLine( "{1}Store name: {0}", store->Name, Environment::NewLine );
   if ( storecollection3->Count == 0 )
   {
      Console::WriteLine( "Store contains no certificates." );
   }
   else
   {
      System::Collections::IEnumerator^ myEnum2 = storecollection3->GetEnumerator();
      while ( myEnum2->MoveNext() )
      {
         X509Certificate2 ^ x509 = safe_cast<X509Certificate2 ^>(myEnum2->Current);
         Console::WriteLine( "certificate name: {0}", x509->Subject );
      }
   }

   
   //Close the store.
   store->Close();
}

using System;
using System.Security.Cryptography;
using System.Security.Cryptography.X509Certificates;
using System.IO;

public class X509store2
{
    public static void Main (string[] args)
    {
        //Create new X509 store called teststore from the local certificate store.
        X509Store store = new X509Store ("teststore", StoreLocation.CurrentUser);
        store.Open (OpenFlags.ReadWrite);
        X509Certificate2 certificate = new X509Certificate2 ();

        //Create certificates from certificate files.
        //You must put in a valid path to three certificates in the following constructors.
        X509Certificate2 certificate1 = new X509Certificate2 ("c:\\mycerts\\*****.cer");
        X509Certificate2 certificate2 = new X509Certificate2 ("c:\\mycerts\\*****.cer");
        X509Certificate2 certificate5 = new X509Certificate2 ("c:\\mycerts\\*****.cer");

        //Create a collection and add two of the certificates.
        X509Certificate2Collection collection = new X509Certificate2Collection ();
        collection.Add (certificate2);
        collection.Add (certificate5);

        //Add certificates to the store.
        store.Add (certificate1);
        store.AddRange (collection);

        X509Certificate2Collection storecollection = (X509Certificate2Collection)store.Certificates;
        Console.WriteLine ("Store name: {0}", store.Name);
        Console.WriteLine ("Store location: {0}", store.Location);
        foreach (X509Certificate2 x509 in storecollection)
        {
            Console.WriteLine("certificate name: {0}",x509.Subject);
        }

        //Remove a certificate.
        store.Remove (certificate1);
        X509Certificate2Collection storecollection2 = (X509Certificate2Collection)store.Certificates;
        Console.WriteLine ("{1}Store name: {0}", store.Name, Environment.NewLine);
        foreach (X509Certificate2 x509 in storecollection2)
        {
            Console.WriteLine ("certificate name: {0}", x509.Subject);
        }

        //Remove a range of certificates.
        store.RemoveRange (collection);
        X509Certificate2Collection storecollection3 = (X509Certificate2Collection)store.Certificates;
        Console.WriteLine ("{1}Store name: {0}", store.Name, Environment.NewLine);
        if (storecollection3.Count == 0)
        {
            Console.WriteLine ("Store contains no certificates.");
        }
        else
        {
            foreach (X509Certificate2 x509 in storecollection3)
            {
                Console.WriteLine ("certificate name: {0}", x509.Subject);
            }
        }

        //Close the store.
        store.Close ();
    }	
}
Imports System.Security.Cryptography
Imports System.Security.Cryptography.X509Certificates
Imports System.IO



Class X509store2

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

        'Create certificates from certificate files.
        'You must put in a valid path to three certificates in the following constructors.
        Dim certificate1 As New X509Certificate2("c:\mycerts\*****.cer")
        Dim certificate2 As New X509Certificate2("c:\mycerts\*****.cer")
        Dim certificate5 As New X509Certificate2("c:\mycerts\*****.cer")

        'Create a collection and add two of the certificates.
        Dim collection As New X509Certificate2Collection()
        collection.Add(certificate2)
        collection.Add(certificate5)

        'Add certificates to the store.
        store.Add(certificate1)
        store.AddRange(collection)

        Dim storecollection As X509Certificate2Collection = CType(store.Certificates, X509Certificate2Collection)
        Console.WriteLine("Store name: {0}", store.Name)
        Console.WriteLine("Store location: {0}", store.Location)
        Dim x509 As X509Certificate2
        For Each x509 In storecollection
            Console.WriteLine("certificate name: {0}", x509.Subject)
        Next x509

        'Remove a certificate.
        store.Remove(certificate1)
        Dim storecollection2 As X509Certificate2Collection = CType(store.Certificates, X509Certificate2Collection)
        Console.WriteLine("{1}Store name: {0}", store.Name, Environment.NewLine)
        Dim x509a As X509Certificate2
        For Each x509a In storecollection2
            Console.WriteLine("certificate name: {0}", x509a.Subject)
        Next x509a

        'Remove a range of certificates.
        store.RemoveRange(collection)
        Dim storecollection3 As X509Certificate2Collection = CType(store.Certificates, X509Certificate2Collection)
        Console.WriteLine("{1}Store name: {0}", store.Name, Environment.NewLine)
        If storecollection3.Count = 0 Then
            Console.WriteLine("Store contains no certificates.")
        Else
            Dim x509b As X509Certificate2
            For Each x509b In storecollection3
                Console.WriteLine("certificate name: {0}", x509b.Subject)
            Next x509b
        End If

        'Close the store.
        store.Close()

    End Sub
End Class

Remarques

Utilisez cette classe pour travailler avec un magasin X. 509.Use this class to work with an X.509 store.

Important

À partir de la .NET Framework 4.6.NET Framework 4.6, ce type implémente l’interface IDisposable.Starting with the .NET Framework 4.6.NET Framework 4.6, this type implements the IDisposable interface. Une fois que vous avez fini d’utiliser le type, vous devez le supprimer directement ou indirectement.When you have finished using the type, you should dispose of it either directly or indirectly. Pour supprimer directement le type Dispose, appelez sa méthode dans un bloc try/catch.To dispose of the type directly, call its Dispose method in a try/catch block. Pour la supprimer indirectement, utilisez une construction de langage telle que using (dans C#) ou Using (dans Visual Basic).To dispose of it indirectly, use a language construct such as using (in C#) or Using (in Visual Basic). Pour plus d’informations, consultez la section « Utilisation d’un objet qui implémente IDisposable » dans la rubrique de l’interface IDisposable.For more information, see the "Using an Object that Implements IDisposable" section in the IDisposable interface topic.

Pour les applications qui ciblent le .NET Framework 4.5.2.NET Framework 4.5.2 et les versions antérieures, la classe X509Store n’implémente pas l’interface IDisposable et, par conséquent, n’a pas de méthode Dispose.For apps that target the .NET Framework 4.5.2.NET Framework 4.5.2 and earlier versions, the X509Store class does not implement the IDisposable interface and therefore does not have a Dispose method.

Constructeurs

X509Store()

Initialise une nouvelle instance de la classe X509Store à l’aide du magasin de certificats personnels de l’utilisateur actif.Initializes a new instance of the X509Store class using the personal certificates store of the current user.

X509Store(IntPtr)

Initialise une nouvelle instance de la classe X509Store en utilisant un handle Intptr vers un magasin HCERTSTORE.Initializes a new instance of the X509Store class using an Intptr handle to an HCERTSTORE store.

X509Store(StoreLocation)

Initialise une nouvelle instance de la classe X509Store à l’aide du magasin de certificats personnels à partir de la valeur d’emplacement du magasin spécifiée.Initializes a new instance of the X509Store class using the personal certificate store from the specified store location value.

X509Store(StoreName)

Initialise une nouvelle instance de la classe X509Store à l’aide du nom de magasin spécifié des magasins de certificats de l’utilisateur actif.Initializes a new instance of the X509Store class using the specified store name from the current user's certificate stores.

X509Store(StoreName, StoreLocation)

Initialise une nouvelle instance de la classe X509Store à l’aide des valeurs StoreName et StoreLocation spécifiées.Initializes a new instance of the X509Store class using the specified StoreName and StoreLocation values.

X509Store(StoreName, StoreLocation, OpenFlags)

Initialise une nouvelle instance de la classe X509Store à l’aide du nom de magasin et des valeurs d’emplacement de magasin spécifiés, puis l’ouvre en utilisant les indicateurs spécifiés.Initializes a new instance of the X509Store class using the specified store name and store location values, then opens it using the specified flags.

X509Store(String)

Initialise une nouvelle instance de la classe X509Store avec le nom de magasin spécifié.Initializes a new instance of the X509Store class using the specified store name.

X509Store(String, StoreLocation)

Initialise une nouvelle instance de la classe X509Store à l’aide d’un nom de magasin et d’un emplacement de magasin spécifiés.Initializes a new instance of the X509Store class using a specified store name and store location.

X509Store(String, StoreLocation, OpenFlags)

Initialise une nouvelle instance de la classe X509Store à l’aide du nom de magasin et des valeurs d’emplacement de magasin spécifiés, puis l’ouvre en utilisant les indicateurs spécifiés.Initializes a new instance of the X509Store class using the specified store name and store location values, then opens it using the specified flags.

Propriétés

Certificates

Retourne une collection de certificats se trouvant dans un magasin de certificats X.509.Returns a collection of certificates located in an X.509 certificate store.

IsOpen

Obtient une valeur qui indique si l’instance est connectée à un magasin de certificats ouvert.Gets a value that indicates whether the instance is connected to an open certificate store.

Location

Obtient l'emplacement du magasin de certificats X.509.Gets the location of the X.509 certificate store.

Name

Obtient le nom du magasin de certificats X.509.Gets the name of the X.509 certificate store.

StoreHandle

Obtient un handle IntPtr pour un magasin HCERTSTORE.Gets an IntPtr handle to an HCERTSTORE store.

Méthodes

Add(X509Certificate2)

Ajoute un certificat à un magasin de certificats X.509.Adds a certificate to an X.509 certificate store.

AddRange(X509Certificate2Collection)

Ajoute une collection de certificats à un magasin de certificats X.509.Adds a collection of certificates to an X.509 certificate store.

Close()

Ferme un magasin de certificats X.509.Closes an X.509 certificate store.

Dispose()

Libère les ressources utilisées par ce X509Store.Releases the resources used by this X509Store.

Equals(Object)

Détermine si l'objet spécifié est égal à l'objet actuel.Determines whether the specified object is equal to the current object.

(Hérité de Object)
GetHashCode()

Sert de fonction de hachage par défaut.Serves as the default hash function.

(Hérité de Object)
GetType()

Obtient le Type de l'instance actuelle.Gets the Type of the current instance.

(Hérité de Object)
MemberwiseClone()

Crée une copie superficielle du Object actuel.Creates a shallow copy of the current Object.

(Hérité de Object)
Open(OpenFlags)

Ouvre un magasin de certificats X.509 ou crée un magasin, selon les valeurs des indicateurs OpenFlags.Opens an X.509 certificate store or creates a new store, depending on OpenFlags flag settings.

Remove(X509Certificate2)

Supprime un certificat d'un magasin de certificats X.509.Removes a certificate from an X.509 certificate store.

RemoveRange(X509Certificate2Collection)

Supprime une plage de certificats d'un magasin de certificats X.509.Removes a range of certificates from an X.509 certificate store.

ToString()

Retourne une chaîne qui représente l'objet actif.Returns a string that represents the current object.

(Hérité de Object)

S’applique à