X509Certificate2 Class

System.Net.Security

Represents a Transport Layer Security (TLS) or Secure Sockets Layer (SSL) certificate.

Inheritance Hierarchy

System.Object
System.Net.Security.X509Certificate
System.Net.Security.X509Certificate2

Syntax

public class X509Certificate2 : X509Certificate

Remarks

The X509Certificate2 class represents an X.509 certificate, which is a digital certificate used in public key cryptography. These certificates are typically used to authenticate the identity of an entity, such as a server or a client, during a secure communication session.

In .NET, X509Certificate2 is fundamental for establishing secure connections using protocols like TLS/SSL, which are commonly used in web applications (HTTPS) and other network communications.

Key features and uses of X509Certificate2 include:

When creating or loading an X509Certificate2 object, you can specify whether it includes a private key. Accessing or manipulating the private key requires appropriate permissions.

Constructors

X509Certificate2()

public X509Certificate2()

Initializes a new instance of the X509Certificate2 class.

X509Certificate2(string fileName)

public X509Certificate2(string fileName)

Initializes a new instance of the X509Certificate2 class using the specified certificate file.

X509Certificate2(string fileName, string password)

public X509Certificate2(string fileName, string password)

Initializes a new instance of the X509Certificate2 class using the specified certificate file and password.

X509Certificate2(byte[] rawData)

public X509Certificate2(byte[] rawData)

Initializes a new instance of the X509Certificate2 class using the specified data from a byte array.

Properties

Archived

public bool Archived { get; set; }

Gets or sets a value indicating whether the certificate is archived.

Extensions

public System.Security.Cryptography.X509Certificates.X509ExtensionCollection Extensions { get; }

Gets a collection of extensions contained in the certificate.

Filt

public bool Filt { get; set; }

Gets or sets a value indicating whether the certificate is filtered.

IsSelfSigned

public bool IsSelfSigned { get; }

Gets a value indicating whether the certificate is self-signed.

KeyAlgorithm

public string KeyAlgorithm { get; }

Gets the name of the asymmetric algorithm used by the certificate's public key.

KeyAlgorithmParameters

public string KeyAlgorithmParameters { get; }

Gets the parameters used by the asymmetric algorithm for the certificate's public key.

KeyLength

public int KeyLength { get; }

Gets the length of the public key in bits.

PrivateKey

public System.Security.Cryptography.AsymmetricAlgorithm PrivateKey { get; }

Gets the private key associated with the certificate.

Methods

Export(System.Security.Cryptography.X509Certificates.X509ContentType, System.String)">Export(X509ContentType contentType, string password)

public byte[] Export(System.Security.Cryptography.X509Certificates.X509ContentType contentType, string password)

Exports the certificate (and optionally its private key) to a byte array in the specified format.

GetRawCertificate()

public byte[] GetRawCertificate()

Returns a byte array representation of the X.509 v3 certificate.

Import(byte[])

public void Import(byte[] rawData)

Imports a certificate from a byte array.

Import(string pfx, string password, System.Security.Cryptography.X509Certificates.X509KeyStorageFlags keyStorageFlags)

public void Import(string pfx, string password, System.Security.Cryptography.X509Certificates.X509KeyStorageFlags keyStorageFlags)

Imports a certificate from a Personal Information Exchange (PFX) file.

Example

using System;
using System.Net;
using System.Net.Security;
using System.Security.Cryptography.X509Certificates;
using System.Text;

public class CertificateExample
{
    public static void Main(string[] args)
    {
        try
        {
            // Load a certificate from a file
            string certificatePath = "mycertificate.pfx";
            string certificatePassword = "mypassword";

            X509Certificate2 cert = new X509Certificate2(certificatePath, certificatePassword);

            Console.WriteLine("Certificate Loaded Successfully:");
            Console.WriteLine($"  Subject: {cert.Subject}");
            Console.WriteLine($"  Issuer: {cert.Issuer}");
            Console.WriteLine($"  Expiration Date: {cert.GetExpirationDateString()}");
            Console.WriteLine($"  Has Private Key: {cert.HasPrivateKey}");

            // Example of using the certificate for an SSL connection (conceptual)
            // In a real scenario, this would involve HttpClient or SslStream

            // To trust a specific server certificate for outgoing requests:
            // ServicePointManager.ServerCertificateValidationCallback =
            //     delegate (object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors)
            // {
            //     if (sslPolicyErrors == SslPolicyErrors.None) return true;
            //     // Add custom validation logic here if needed
            //     return false;
            // };

            // You can also create a custom RemoteCertificateValidationCallback
            // for SslStream or HttpClient to validate certificates.

        }
        catch (CryptographicException ex)
        {
            Console.WriteLine($"Cryptography error: {ex.Message}");
        }
        catch (Exception ex)
        {
            Console.WriteLine($"An error occurred: {ex.Message}");
        }
    }
}

See Also