Partilhar via


X509Certificate2.PrivateKey Propriedade

Definição

Cuidado

X509Certificate2.PrivateKey is obsolete. Use the appropriate method to get the private key, such as GetRSAPrivateKey, or use the CopyWithPrivateKey method to create a new instance with a private key.

Obtém ou define o objeto AsymmetricAlgorithm que representa a chave privada associada a um certificado.

public:
 property System::Security::Cryptography::AsymmetricAlgorithm ^ PrivateKey { System::Security::Cryptography::AsymmetricAlgorithm ^ get(); void set(System::Security::Cryptography::AsymmetricAlgorithm ^ value); };
public System.Security.Cryptography.AsymmetricAlgorithm? PrivateKey { get; set; }
[System.Obsolete("X509Certificate2.PrivateKey is obsolete. Use the appropriate method to get the private key, such as GetRSAPrivateKey, or use the CopyWithPrivateKey method to create a new instance with a private key.", DiagnosticId="SYSLIB0028", UrlFormat="https://aka.ms/dotnet-warnings/{0}")]
public System.Security.Cryptography.AsymmetricAlgorithm? PrivateKey { get; set; }
public System.Security.Cryptography.AsymmetricAlgorithm PrivateKey { get; set; }
member this.PrivateKey : System.Security.Cryptography.AsymmetricAlgorithm with get, set
[<System.Obsolete("X509Certificate2.PrivateKey is obsolete. Use the appropriate method to get the private key, such as GetRSAPrivateKey, or use the CopyWithPrivateKey method to create a new instance with a private key.", DiagnosticId="SYSLIB0028", UrlFormat="https://aka.ms/dotnet-warnings/{0}")>]
member this.PrivateKey : System.Security.Cryptography.AsymmetricAlgorithm with get, set
Public Property PrivateKey As AsymmetricAlgorithm

Valor da propriedade

Um objeto AsymmetricAlgorithm, que é o provedor de serviços de criptografia DSA ou RSA.

Atributos

Exceções

O valor da chave não é uma chave RSA ou DSA ou a chave é ilegível.

O valor definido para essa propriedade é null.

Não é compatível com o algoritmo de chave dessa chave privada.

As chaves X.509 não correspondem.

A chave do provedor de serviços de criptografia é null.

Somente .NET Core e .NET 5+: foi feita uma tentativa de definir essa propriedade.

Exemplos

O exemplo de código a seguir abre o repositório de certificados do usuário atual, seleciona apenas certificados ativos e permite que o usuário selecione um ou mais certificados. Em seguida, o exemplo grava informações de certificado no console.

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

using namespace System;
using namespace System::Security::Cryptography;
using namespace System::Security::Permissions;
using namespace System::IO;
using namespace System::Security::Cryptography::X509Certificates;
int main()
{
   try
   {
      X509Store ^ store = gcnew X509Store( "MY",StoreLocation::CurrentUser );
      store->Open( static_cast<OpenFlags>(OpenFlags::ReadOnly | OpenFlags::OpenExistingOnly) );
      X509Certificate2Collection ^ collection = dynamic_cast<X509Certificate2Collection^>(store->Certificates);
      X509Certificate2Collection ^ fcollection = dynamic_cast<X509Certificate2Collection^>(collection->Find( X509FindType::FindByTimeValid, DateTime::Now, false ));
      X509Certificate2Collection ^ scollection = X509Certificate2UI::SelectFromCollection(fcollection, "Test Certificate Select","Select a certificate from the following list to get information on that certificate",X509SelectionFlag::MultiSelection);
      Console::WriteLine( "Number of certificates: {0}{1}", scollection->Count, Environment::NewLine );
      System::Collections::IEnumerator^ myEnum = scollection->GetEnumerator();
      while ( myEnum->MoveNext() )
      {
         X509Certificate2 ^ x509 = safe_cast<X509Certificate2 ^>(myEnum->Current);
         array<Byte>^rawdata = x509->RawData;
         Console::WriteLine( "Content Type: {0}{1}", X509Certificate2::GetCertContentType( rawdata ), Environment::NewLine );
         Console::WriteLine( "Friendly Name: {0}{1}", x509->FriendlyName, Environment::NewLine );
         Console::WriteLine( "Certificate Verified?: {0}{1}", x509->Verify(), Environment::NewLine );
         Console::WriteLine( "Simple Name: {0}{1}", x509->GetNameInfo( X509NameType::SimpleName, true ), Environment::NewLine );
         Console::WriteLine( "Signature Algorithm: {0}{1}", x509->SignatureAlgorithm->FriendlyName, Environment::NewLine );
         Console::WriteLine( "Private Key: {0}{1}", x509->PrivateKey->ToXmlString( false ), Environment::NewLine );
         Console::WriteLine( "Public Key: {0}{1}", x509->PublicKey->Key->ToXmlString( false ), Environment::NewLine );
         Console::WriteLine( "Certificate Archived?: {0}{1}", x509->Archived, Environment::NewLine );
         Console::WriteLine( "Length of Raw Data: {0}{1}", x509->RawData->Length, Environment::NewLine );
         x509->Reset();
      }
      store->Close();
   }
   catch ( CryptographicException^ ) 
   {
      Console::WriteLine( "Information could not be written out for this certificate." );
   }

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

class CertSelect
{
    static void Main()
    {
        X509Store store = new X509Store("MY",StoreLocation.CurrentUser);
        store.Open(OpenFlags.ReadOnly | OpenFlags.OpenExistingOnly);

        X509Certificate2Collection collection = (X509Certificate2Collection)store.Certificates;
        X509Certificate2Collection fcollection = (X509Certificate2Collection)collection.Find(X509FindType.FindByTimeValid,DateTime.Now,false);
        X509Certificate2Collection scollection = X509Certificate2UI.SelectFromCollection(fcollection, "Test Certificate Select","Select a certificate from the following list to get information on that certificate",X509SelectionFlag.MultiSelection);
        Console.WriteLine("Number of certificates: {0}{1}",scollection.Count,Environment.NewLine);

        foreach (X509Certificate2 x509 in scollection)
        {
            try
            {
                byte[] rawdata = x509.RawData;
                Console.WriteLine("Content Type: {0}{1}",X509Certificate2.GetCertContentType(rawdata),Environment.NewLine);
                Console.WriteLine("Friendly Name: {0}{1}",x509.FriendlyName,Environment.NewLine);
                Console.WriteLine("Certificate Verified?: {0}{1}",x509.Verify(),Environment.NewLine);
                Console.WriteLine("Simple Name: {0}{1}",x509.GetNameInfo(X509NameType.SimpleName,true),Environment.NewLine);
                Console.WriteLine("Signature Algorithm: {0}{1}",x509.SignatureAlgorithm.FriendlyName,Environment.NewLine);
                Console.WriteLine("Public Key: {0}{1}",x509.PublicKey.Key.ToXmlString(false),Environment.NewLine);
                Console.WriteLine("Certificate Archived?: {0}{1}",x509.Archived,Environment.NewLine);
                Console.WriteLine("Length of Raw Data: {0}{1}",x509.RawData.Length,Environment.NewLine);
                X509Certificate2UI.DisplayCertificate(x509);
                x509.Reset();
            }
            catch (CryptographicException)
            {
                Console.WriteLine("Information could not be written out for this certificate.");
            }
        }
        store.Close();
    }
}
Imports System.Security.Cryptography
Imports System.Security.Permissions
Imports System.IO
Imports System.Security.Cryptography.X509Certificates

Class CertSelect

    Shared Sub Main()

        Dim store As New X509Store("MY", StoreLocation.CurrentUser)
        store.Open(OpenFlags.ReadOnly Or OpenFlags.OpenExistingOnly)

        Dim collection As X509Certificate2Collection = CType(store.Certificates, X509Certificate2Collection)
        Dim fcollection As X509Certificate2Collection = CType(collection.Find(X509FindType.FindByTimeValid, DateTime.Now, False), X509Certificate2Collection)
        Dim scollection As X509Certificate2Collection = X509Certificate2UI.SelectFromCollection(fcollection, "Test Certificate Select", "Select a certificate from the following list to get information on that certificate", X509SelectionFlag.MultiSelection)
        Console.WriteLine("Number of certificates: {0}{1}", scollection.Count, Environment.NewLine)
         
        For Each x509 As X509Certificate2 In scollection
            Try
                Dim rawdata As Byte() = x509.RawData
                Console.WriteLine("Content Type: {0}{1}", X509Certificate2.GetCertContentType(rawdata), Environment.NewLine)
                Console.WriteLine("Friendly Name: {0}{1}", x509.FriendlyName, Environment.NewLine)
                Console.WriteLine("Certificate Verified?: {0}{1}", x509.Verify(), Environment.NewLine)
                Console.WriteLine("Simple Name: {0}{1}", x509.GetNameInfo(X509NameType.SimpleName, True), Environment.NewLine)
                Console.WriteLine("Signature Algorithm: {0}{1}", x509.SignatureAlgorithm.FriendlyName, Environment.NewLine)
                Console.WriteLine("Public Key: {0}{1}", x509.PublicKey.Key.ToXmlString(False), Environment.NewLine)
                Console.WriteLine("Certificate Archived?: {0}{1}", x509.Archived, Environment.NewLine)
                Console.WriteLine("Length of Raw Data: {0}{1}", x509.RawData.Length, Environment.NewLine)
                X509Certificate2UI.DisplayCertificate(x509)
                x509.Reset()         
             Catch cExcept As CryptographicException
                 Console.WriteLine("Information could not be written out for this certificate.")
             End Try
        Next x509

        store.Close()
    End Sub
End Class

Comentários

Atualmente, essa propriedade dá suporte apenas a chaves RSA ou DSA, portanto, ela retorna um RSA ou um DSA objeto no .NET Core ou um RSACryptoServiceProvider objeto ou DSACryptoServiceProvider em .NET Framework. Se nenhuma chave privada estiver associada ao certificado, ela retornará null.

Aviso

Se você definir essa propriedade null como ou para outra chave sem excluí-la primeiro, um arquivo de chave privada será deixado no disco.

Para excluir corretamente a chave privada associada a essa propriedade, defina PersistKeyInCsp como falsee, em seguida, chame o Clear método .

Aplica-se a