X509Certificate2.Import Método

Definición

Rellena un objeto X509Certificate2 con la información proporcionada del certificado.Populates an X509Certificate2 object with the certificate information provided.

Sobrecargas

Import(Byte[])

Rellena un objeto X509Certificate2 con datos de una matriz de bytes.Populates an X509Certificate2 object with data from a byte array.

Import(String)

Rellena un objeto X509Certificate2 con información de un archivo de certificado.Populates an X509Certificate2 object with information from a certificate file.

Import(Byte[], SecureString, X509KeyStorageFlags)

Rellena un objeto X509Certificate2 utilizando los datos de una matriz de bytes, una contraseña y una marca de almacenamiento de claves.Populates an X509Certificate2 object using data from a byte array, a password, and a key storage flag.

Import(Byte[], String, X509KeyStorageFlags)

Rellena un objeto X509Certificate2 utilizando los datos de una matriz de bytes, una contraseña y los marcadores para determinar cómo importar la clave privada.Populates an X509Certificate2 object using data from a byte array, a password, and flags for determining how to import the private key.

Import(String, SecureString, X509KeyStorageFlags)

Rellena un objeto X509Certificate2 con información de un archivo de certificado, una contraseña y una marca de almacenamiento de claves.Populates an X509Certificate2 object with information from a certificate file, a password, and a key storage flag.

Import(String, String, X509KeyStorageFlags)

Rellena un objeto X509Certificate2 con información de un archivo de certificado, una contraseña y un valor de X509KeyStorageFlags.Populates an X509Certificate2 object with information from a certificate file, a password, and a X509KeyStorageFlags value.

Import(Byte[])

Rellena un objeto X509Certificate2 con datos de una matriz de bytes.Populates an X509Certificate2 object with data from a byte array.

public:
 override void Import(cli::array <System::Byte> ^ rawData);
public override void Import (byte[] rawData);
override this.Import : byte[] -> unit
Public Overrides Sub Import (rawData As Byte())

Parámetros

rawData
Byte[]

Matriz de bytes que contiene los datos de un certificado X.509.A byte array containing data from an X.509 certificate.

Comentarios

Este método se puede utilizar para tomar una matriz de bytes sin formato de un certificado X. 509 y rellenar el X509Certificate2 objeto con sus valores asociados.This method can be used to take a raw byte array of an X.509 certificate and populate the X509Certificate2 object with its associated values.

Dado que este método solo acepta una matriz de bytes, solo se puede usar para los tipos de certificado que no requieran una contraseña, incluido un certificado X. 509 codificado en base64 o con codificación DER o un certificado PFX/PKCS12.Since this method accepts only a byte array, it can be used only for certificate types that do not require a password, including a Base64-encoded or DER-encoded X.509 certificate or a PFX/PKCS12 certificate. Tenga en cuenta que un certificado PFX/PKCS12 puede contener más de un certificado.Note that a PFX/PKCS12 certificate can contain more than one certificate. En ese caso, se usa el primer certificado asociado a una clave privada o, si no se encuentra ninguna clave privada, se usa el primer certificado.In that case, the first certificate associated with a private key is used or, if no private key is found, the first certificate is used.

Se aplica a

Import(String)

Rellena un objeto X509Certificate2 con información de un archivo de certificado.Populates an X509Certificate2 object with information from a certificate file.

public:
 override void Import(System::String ^ fileName);
public override void Import (string fileName);
override this.Import : string -> unit
Public Overrides Sub Import (fileName As String)

Parámetros

fileName
String

Nombre de un certificado.The name of a certificate.

Comentarios

Este método usa un archivo de certificado, como un archivo con una extensión. cer, que representa un certificado X. 509 y rellena el X509Certificate2 objeto con el certificado que contiene el archivo.This method uses a certificate file, such as a file with a .cer extension, that represents an X.509 certificate and populates the X509Certificate2 object with the certificate the file contains.

Este método se puede usar con varios tipos de certificados, incluidos certificados X. 509 codificados en base64 o codificados en DER, certificados PFX/PKCS12 y certificados de firma, como Authenticode.This method can be used with several certificate types, including Base64-encoded or DER-encoded X.509 certificates, PFX/PKCS12 certificates, and signer certificates such as Authenticode. Tenga en cuenta que un certificado PFX/PKCS12 puede contener más de un certificado.Note that a PFX/PKCS12 certificate can contain more than one certificate. En ese caso, se usa el primer certificado asociado a una clave privada o, si no se encuentra ninguna clave privada, se usa el primer certificado.In that case, the first certificate associated with a private key is used or, if no private key is found, the first certificate is used.

Se aplica a

Import(Byte[], SecureString, X509KeyStorageFlags)

Importante

Esta API no es conforme a CLS.

Rellena un objeto X509Certificate2 utilizando los datos de una matriz de bytes, una contraseña y una marca de almacenamiento de claves.Populates an X509Certificate2 object using data from a byte array, a password, and a key storage flag.

public:
 override void Import(cli::array <System::Byte> ^ rawData, System::Security::SecureString ^ password, System::Security::Cryptography::X509Certificates::X509KeyStorageFlags keyStorageFlags);
[System.CLSCompliant(false)]
public override void Import (byte[] rawData, System.Security.SecureString? password, System.Security.Cryptography.X509Certificates.X509KeyStorageFlags keyStorageFlags);
[System.CLSCompliant(false)]
public override void Import (byte[] rawData, System.Security.SecureString password, System.Security.Cryptography.X509Certificates.X509KeyStorageFlags keyStorageFlags);
public override void Import (byte[] rawData, System.Security.SecureString password, System.Security.Cryptography.X509Certificates.X509KeyStorageFlags keyStorageFlags);
[<System.CLSCompliant(false)>]
override this.Import : byte[] * System.Security.SecureString * System.Security.Cryptography.X509Certificates.X509KeyStorageFlags -> unit
override this.Import : byte[] * System.Security.SecureString * System.Security.Cryptography.X509Certificates.X509KeyStorageFlags -> unit
Public Overrides Sub Import (rawData As Byte(), password As SecureString, keyStorageFlags As X509KeyStorageFlags)

Parámetros

rawData
Byte[]

Matriz de bytes que contiene los datos de un certificado X.509.A byte array that contains data from an X.509 certificate.

password
SecureString

Contraseña requerida para obtener acceso a los datos del certificado X.509.The password required to access the X.509 certificate data.

keyStorageFlags
X509KeyStorageFlags

Combinación bit a bit de los valores de enumeración que controlan dónde y cómo importar el certificado.A bitwise combination of the enumeration values that control where and how to import the certificate.

Atributos

Comentarios

Puede usar este método para los tipos de certificados, como los certificados X. 509 codificados en base64 o con codificación DER, o los certificados PFX/PKCS12.You can use this method for certificate types such as Base64-encoded or DER-encoded X.509 certificates, or PFX/PKCS12 certificates. Tenga en cuenta que un certificado PFX/PKCS12 puede contener más de un certificado.Note that a PFX/PKCS12 certificate can contain more than one certificate. En ese caso, se usa el primer certificado asociado a una clave privada o, si no se encuentra ninguna clave privada, se usa el primer certificado.In that case, the first certificate associated with a private key is used or, if no private key is found, the first certificate is used.

Importante

No codifique nunca una contraseña dentro del código fuente.Never hard code a password within your source code. Las contraseñas codificadas de forma rígida se pueden recuperar de un ensamblado mediante el Ildasm.exe (desensamblador de IL), un editor hexadecimal o simplemente abriendo el ensamblado en un editor de texto como Notepad.exe.Hard-coded passwords can be retrieved from an assembly using the Ildasm.exe (IL Disassembler), a hex editor, or by simply opening up the assembly in a text editor such as Notepad.exe.

Se aplica a

Import(Byte[], String, X509KeyStorageFlags)

Rellena un objeto X509Certificate2 utilizando los datos de una matriz de bytes, una contraseña y los marcadores para determinar cómo importar la clave privada.Populates an X509Certificate2 object using data from a byte array, a password, and flags for determining how to import the private key.

public:
 override void Import(cli::array <System::Byte> ^ rawData, System::String ^ password, System::Security::Cryptography::X509Certificates::X509KeyStorageFlags keyStorageFlags);
public override void Import (byte[] rawData, string? password, System.Security.Cryptography.X509Certificates.X509KeyStorageFlags keyStorageFlags);
public override void Import (byte[] rawData, string password, System.Security.Cryptography.X509Certificates.X509KeyStorageFlags keyStorageFlags);
override this.Import : byte[] * string * System.Security.Cryptography.X509Certificates.X509KeyStorageFlags -> unit
Public Overrides Sub Import (rawData As Byte(), password As String, keyStorageFlags As X509KeyStorageFlags)

Parámetros

rawData
Byte[]

Matriz de bytes que contiene los datos de un certificado X.509.A byte array containing data from an X.509 certificate.

password
String

Contraseña requerida para obtener acceso a los datos del certificado X.509.The password required to access the X.509 certificate data.

keyStorageFlags
X509KeyStorageFlags

Combinación bit a bit de los valores de enumeración que controlan dónde y cómo importar el certificado.A bitwise combination of the enumeration values that control where and how to import the certificate.

Ejemplos

En el ejemplo de código siguiente se crea un ejecutable de línea de comandos que toma un archivo de certificado como argumento e imprime varias propiedades de certificado en la consola.The following code example creates a command-line executable that takes a certificate file as an argument and prints various certificate properties to the console.

#using <System.dll>

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

//Reads a file.
array<Byte>^ ReadFile( String^ fileName )
{
   FileStream^ f = gcnew FileStream( fileName,FileMode::Open,FileAccess::Read );
   int size = (int)f->Length;
   array<Byte>^data = gcnew array<Byte>(size);
   size = f->Read( data, 0, size );
   f->Close();
   return data;
}

[SecurityPermissionAttribute(SecurityAction::LinkDemand, Unrestricted = true)]
int main()
{
   array<String^>^args = Environment::GetCommandLineArgs();

   //Test for correct number of arguments.
   if ( args->Length < 2 )
   {
      Console::WriteLine( "Usage: CertInfo <filename>" );
      return  -1;
   }

   try
   {
      System::Security::Cryptography::X509Certificates::X509Certificate2 ^ x509 =
            gcnew System::Security::Cryptography::X509Certificates::X509Certificate2;

      //Create X509Certificate2 object from .cer file.
      array<Byte>^rawData = ReadFile( args[ 1 ] );

      x509->Import(rawData);

      //Print to console information contained in the certificate.
      Console::WriteLine( "{0}Subject: {1}{0}", Environment::NewLine, x509->Subject );
      Console::WriteLine( "{0}Issuer: {1}{0}", Environment::NewLine, x509->Issuer );
      Console::WriteLine( "{0}Version: {1}{0}", Environment::NewLine, x509->Version );
      Console::WriteLine( "{0}Valid Date: {1}{0}", Environment::NewLine, x509->NotBefore );
      Console::WriteLine( "{0}Expiry Date: {1}{0}", Environment::NewLine, x509->NotAfter );
      Console::WriteLine( "{0}Thumbprint: {1}{0}", Environment::NewLine, x509->Thumbprint );
      Console::WriteLine( "{0}Serial Number: {1}{0}", Environment::NewLine, x509->SerialNumber );
      Console::WriteLine( "{0}Friendly Name: {1}{0}", Environment::NewLine, x509->PublicKey->Oid->FriendlyName );
      Console::WriteLine( "{0}Public Key Format: {1}{0}", Environment::NewLine, x509->PublicKey->EncodedKeyValue->Format(true) );
      Console::WriteLine( "{0}Raw Data Length: {1}{0}", Environment::NewLine, x509->RawData->Length );
      Console::WriteLine( "{0}Certificate to string: {1}{0}", Environment::NewLine, x509->ToString( true ) );
      Console::WriteLine( "{0}Certificate to XML String: {1}{0}", Environment::NewLine, x509->PublicKey->Key->ToXmlString( false ) );

      //Add the certificate to a X509Store.
      X509Store ^ store = gcnew X509Store;
      store->Open( OpenFlags::MaxAllowed );
      store->Add( x509 );
      store->Close();
   }
   catch ( DirectoryNotFoundException^ )
   {
      Console::WriteLine( "Error: The directory specified could not be found." );
   }
   catch ( IOException^ )
   {
      Console::WriteLine( "Error: A file in the directory could not be accessed." );
   }
   catch ( NullReferenceException^ )
   {
      Console::WriteLine( "File must be a .cer file. Program does not have access to that type of file." );
   }

}

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

class CertInfo
{
    //Reads a file.
    internal static byte[] ReadFile (string fileName)
    {
        FileStream f = new FileStream(fileName, FileMode.Open, FileAccess.Read);
        int size = (int)f.Length;
        byte[] data = new byte[size];
        size = f.Read(data, 0, size);
        f.Close();
        return data;
    }
    //Main method begins here.
    static void Main(string[] args)
    {
        //Test for correct number of arguments.
        if (args.Length < 1)
        {
            Console.WriteLine("Usage: CertInfo <filename>");
            return;
        }
        try
        {
            X509Certificate2 x509 = new X509Certificate2();
            //Create X509Certificate2 object from .cer file.
            byte[] rawData = ReadFile(args[0]);
            x509.Import(rawData);

            //Print to console information contained in the certificate.
            Console.WriteLine("{0}Subject: {1}{0}", Environment.NewLine, x509.Subject);
            Console.WriteLine("{0}Issuer: {1}{0}", Environment.NewLine, x509.Issuer);
            Console.WriteLine("{0}Version: {1}{0}", Environment.NewLine, x509.Version);
            Console.WriteLine("{0}Valid Date: {1}{0}", Environment.NewLine, x509.NotBefore);
            Console.WriteLine("{0}Expiry Date: {1}{0}", Environment.NewLine, x509.NotAfter);
            Console.WriteLine("{0}Thumbprint: {1}{0}", Environment.NewLine, x509.Thumbprint);
            Console.WriteLine("{0}Serial Number: {1}{0}", Environment.NewLine, x509.SerialNumber);
            Console.WriteLine("{0}Friendly Name: {1}{0}", Environment.NewLine, x509.PublicKey.Oid.FriendlyName);
            Console.WriteLine("{0}Public Key Format: {1}{0}", Environment.NewLine, x509.PublicKey.EncodedKeyValue.Format(true));
            Console.WriteLine("{0}Raw Data Length: {1}{0}", Environment.NewLine, x509.RawData.Length);
            Console.WriteLine("{0}Certificate to string: {1}{0}", Environment.NewLine, x509.ToString(true));
            Console.WriteLine("{0}Certificate to XML String: {1}{0}", Environment.NewLine, x509.PublicKey.Key.ToXmlString(false));

            //Add the certificate to a X509Store.
            X509Store store = new X509Store();
            store.Open(OpenFlags.MaxAllowed);
            store.Add(x509);
            store.Close();
        }
        catch (DirectoryNotFoundException)
        {
               Console.WriteLine("Error: The directory specified could not be found.");
        }
        catch (IOException)
        {
            Console.WriteLine("Error: A file in the directory could not be accessed.");
        }
        catch (NullReferenceException)
        {
            Console.WriteLine("File must be a .cer file. Program does not have access to that type of file.");
        }
    }
}
Imports System.Security.Cryptography
Imports System.Security.Permissions
Imports System.IO
Imports System.Security.Cryptography.X509Certificates

Class CertInfo

    'Reads a file.
    Friend Shared Function ReadFile(ByVal fileName As String) As Byte()
        Dim f As New FileStream(fileName, FileMode.Open, FileAccess.Read)
        Dim size As Integer = Fix(f.Length)
        Dim data(size - 1) As Byte
        size = f.Read(data, 0, size)
        f.Close()
        Return data

    End Function 

    <SecurityPermission(SecurityAction.LinkDemand, Unrestricted:=True)> _
    Shared Sub Main(ByVal args() As String)
        'Test for correct number of arguments.
        If args.Length < 1 Then
            Console.WriteLine("Usage: CertInfo <filename>")
            Return
        End If
        Try
            Dim x509 As New X509Certificate2()
            'Create X509Certificate2 object from .cer file.
            Dim rawData As Byte() = ReadFile(args(0))
            
            x509.Import(rawData)

            'Print to console information contained in the certificate.
            Console.WriteLine("{0}Subject: {1}{0}", Environment.NewLine, x509.Subject)
            Console.WriteLine("{0}Issuer: {1}{0}", Environment.NewLine, x509.Issuer)
            Console.WriteLine("{0}Version: {1}{0}", Environment.NewLine, x509.Version)
            Console.WriteLine("{0}Valid Date: {1}{0}", Environment.NewLine, x509.NotBefore)
            Console.WriteLine("{0}Expiry Date: {1}{0}", Environment.NewLine, x509.NotAfter)
            Console.WriteLine("{0}Thumbprint: {1}{0}", Environment.NewLine, x509.Thumbprint)
            Console.WriteLine("{0}Serial Number: {1}{0}", Environment.NewLine, x509.SerialNumber)
            Console.WriteLine("{0}Friendly Name: {1}{0}", Environment.NewLine, x509.PublicKey.Oid.FriendlyName)
            Console.WriteLine("{0}Public Key Format: {1}{0}", Environment.NewLine, x509.PublicKey.EncodedKeyValue.Format(True))
            Console.WriteLine("{0}Raw Data Length: {1}{0}", Environment.NewLine, x509.RawData.Length)
            Console.WriteLine("{0}Certificate to string: {1}{0}", Environment.NewLine, x509.ToString(True))

            Console.WriteLine("{0}Certificate to XML String: {1}{0}", Environment.NewLine, x509.PublicKey.Key.ToXmlString(False))

            'Add the certificate to a X509Store.
            Dim store As New X509Store()
            store.Open(OpenFlags.MaxAllowed)
            store.Add(x509)
            store.Close()

        Catch dnfExcept As DirectoryNotFoundException
            Console.WriteLine("Error: The directory specified could not be found.")
        Catch ioExpcept As IOException
            Console.WriteLine("Error: A file in the directory could not be accessed.")
        Catch nrExcept As NullReferenceException
            Console.WriteLine("File must be a .cer file. Program does not have access to that type of file.")
        End Try

    End Sub
End Class

Comentarios

Este método se puede utilizar para rellenar un X509Certificate2 objeto utilizando una contraseña para el certificado representado por la matriz de bytes.This method can be used to populate an X509Certificate2 object using a password for the certificate represented by the byte array. El X509KeyStorageFlags valor se puede utilizar para controlar dónde y cómo importar la clave privada.The X509KeyStorageFlags value can be used to control where and how to import the private key.

Este método acepta una matriz de bytes y se puede usar para los tipos de certificados, como los certificados X. 509 con codificación base64 o con codificación DER o los certificados PFX/PKCS12.This method accepts a byte array and can be used for certificate types such as Base64-encoded or DER-encoded X.509 certificates or PFX/PKCS12 certificates. Tenga en cuenta que un certificado PFX/PKCS12 puede contener más de un certificado.Note that a PFX/PKCS12 certificate can contain more than one certificate. En ese caso, se usa el primer certificado asociado a una clave privada o, si no se encuentra ninguna clave privada, se usa el primer certificado.In that case, the first certificate associated with a private key is used or, if no private key is found, the first certificate is used.

Importante

No codifique nunca una contraseña dentro del código fuente.Never hard code a password within your source code. Las contraseñas codificadas de forma rígida se pueden recuperar de un ensamblado mediante el Ildasm.exe (desensamblador de IL), un editor hexadecimal o simplemente abriendo el ensamblado en un editor de texto como Notepad.exe.Hard-coded passwords can be retrieved from an assembly using the Ildasm.exe (IL Disassembler), a hex editor, or by simply opening up the assembly in a text editor such as Notepad.exe.

Se aplica a

Import(String, SecureString, X509KeyStorageFlags)

Importante

Esta API no es conforme a CLS.

Rellena un objeto X509Certificate2 con información de un archivo de certificado, una contraseña y una marca de almacenamiento de claves.Populates an X509Certificate2 object with information from a certificate file, a password, and a key storage flag.

public:
 override void Import(System::String ^ fileName, System::Security::SecureString ^ password, System::Security::Cryptography::X509Certificates::X509KeyStorageFlags keyStorageFlags);
[System.CLSCompliant(false)]
public override void Import (string fileName, System.Security.SecureString? password, System.Security.Cryptography.X509Certificates.X509KeyStorageFlags keyStorageFlags);
[System.CLSCompliant(false)]
public override void Import (string fileName, System.Security.SecureString password, System.Security.Cryptography.X509Certificates.X509KeyStorageFlags keyStorageFlags);
public override void Import (string fileName, System.Security.SecureString password, System.Security.Cryptography.X509Certificates.X509KeyStorageFlags keyStorageFlags);
[<System.CLSCompliant(false)>]
override this.Import : string * System.Security.SecureString * System.Security.Cryptography.X509Certificates.X509KeyStorageFlags -> unit
override this.Import : string * System.Security.SecureString * System.Security.Cryptography.X509Certificates.X509KeyStorageFlags -> unit
Public Overrides Sub Import (fileName As String, password As SecureString, keyStorageFlags As X509KeyStorageFlags)

Parámetros

fileName
String

Nombre de un archivo de certificado.The name of a certificate file.

password
SecureString

Contraseña requerida para obtener acceso a los datos del certificado X.509.The password required to access the X.509 certificate data.

keyStorageFlags
X509KeyStorageFlags

Combinación bit a bit de los valores de enumeración que controlan dónde y cómo importar el certificado.A bitwise combination of the enumeration values that control where and how to import the certificate.

Atributos

Comentarios

Nota de seguridad No codifique nunca una contraseña dentro del código fuente.Security Note Never hard code a password within your source code. Las contraseñas codificadas de forma rígida se pueden recuperar de un ensamblado mediante el Ildasm.exe (desensamblador de IL), un editor hexadecimal o simplemente abriendo el ensamblado en un editor de texto como Notepad.exe.Hard-coded passwords can be retrieved from an assembly using the Ildasm.exe (IL Disassembler), a hex editor, or by simply opening up the assembly in a text editor such as Notepad.exe.

Se aplica a

Import(String, String, X509KeyStorageFlags)

Rellena un objeto X509Certificate2 con información de un archivo de certificado, una contraseña y un valor de X509KeyStorageFlags.Populates an X509Certificate2 object with information from a certificate file, a password, and a X509KeyStorageFlags value.

public:
 override void Import(System::String ^ fileName, System::String ^ password, System::Security::Cryptography::X509Certificates::X509KeyStorageFlags keyStorageFlags);
public override void Import (string fileName, string? password, System.Security.Cryptography.X509Certificates.X509KeyStorageFlags keyStorageFlags);
public override void Import (string fileName, string password, System.Security.Cryptography.X509Certificates.X509KeyStorageFlags keyStorageFlags);
override this.Import : string * string * System.Security.Cryptography.X509Certificates.X509KeyStorageFlags -> unit
Public Overrides Sub Import (fileName As String, password As String, keyStorageFlags As X509KeyStorageFlags)

Parámetros

fileName
String

Nombre de un archivo de certificado.The name of a certificate file.

password
String

Contraseña requerida para obtener acceso a los datos del certificado X.509.The password required to access the X.509 certificate data.

keyStorageFlags
X509KeyStorageFlags

Combinación bit a bit de los valores de enumeración que controlan dónde y cómo importar el certificado.A bitwise combination of the enumeration values that control where and how to import the certificate.

Comentarios

Este método se puede usar para rellenar un X509Certificate2 objeto con información de un archivo de certificado, una contraseña y un X509KeyStorageFlags valor.This method can be used populate an X509Certificate2 object with information from a certificate file, a password, and an X509KeyStorageFlags value.

Importante

No codifique nunca una contraseña dentro del código fuente.Never hard code a password within your source code. Las contraseñas codificadas de forma rígida se pueden recuperar de un ensamblado mediante el Ildasm.exe (desensamblador de IL), un editor hexadecimal o simplemente abriendo el ensamblado en un editor de texto como Notepad.exe.Hard-coded passwords can be retrieved from an assembly using the Ildasm.exe (IL Disassembler), a hex editor, or by simply opening up the assembly in a text editor such as Notepad.exe.

Se aplica a