X509Certificate2.ToString Метод

Определение

Отображает сертификат X.509 в текстовом формате.

Перегрузки

ToString()

Отображает сертификат X.509 в текстовом формате.

ToString(Boolean)

Отображает сертификат X.509 в текстовом формате.

ToString()

Отображает сертификат X.509 в текстовом формате.

public:
 override System::String ^ ToString();
public override string ToString ();
override this.ToString : unit -> string
Public Overrides Function ToString () As String

Возвращаемое значение

Сведения о сертификате.

Примеры

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

#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

Комментарии

Как и в случае со всеми ToString методами, выходные данные могут быть несовместимыми в разных версиях платформа .NET Framework, поэтому результаты метода не должны анализироваться для содержимого. Используйте свойства объекта для X509Certificate2 получения точных сведений о содержимом или используйте ToString метод для получения сведений о сертификате.

Этот метод отображает сертификат в текстовом формате.

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

ToString(Boolean)

Отображает сертификат X.509 в текстовом формате.

public:
 override System::String ^ ToString(bool verbose);
public override string ToString (bool verbose);
override this.ToString : bool -> string
Public Overrides Function ToString (verbose As Boolean) As String

Параметры

verbose
Boolean

Значение true для отображения открытого ключа, закрытого ключа, расширений и т. д.; значение false для отображения сведений, аналогичных классу X509Certificate2, в том числе отпечаток, серийный номер, имена субъекта и поставщика и т. д.

Возвращаемое значение

Сведения о сертификате.

Примеры

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

#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

Комментарии

Как и в случае со всеми ToString методами, выходные данные могут быть несовместимыми в разных версиях платформа .NET Framework, поэтому результаты метода не должны анализироваться для содержимого. Используйте свойства объекта для получения точных X509Certificate2 сведений.

Этот метод отображает сертификат в текстовом формате. verbose Если параметр имеет значение true, отображается текст с открытым ключом, закрытым ключом и расширениями. Если verbose задано значение false, текстовое отображение включает поля, доступные из сертификата X.509, включая отпечаток, серийный номер, имена субъектов и издателей, а также сведения о дате действия.

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