Property
public X509ExtensionCollection Extensions { get; }
Gets the collection of extensions in the X.509 certificate.
An extension is a name-value pair that extends the information contained in an X.509 certificate. Extensions are defined by the X.509 standard and can be used to convey additional information that is not part of the standard certificate fields. Common extensions include Subject Alternative Name (SAN), Key Usage, and Extended Key Usage.
The Extensions property returns an X509ExtensionCollection object, which is a collection of X509Extension objects. Each X509Extension object represents a single extension within the certificate.
You can iterate through the Extensions collection to access individual extensions and retrieve their properties, such as the extension's identifier (OID) and its encoded data.
Supported in: 4.8, 4.7.2, 4.7.1, 4.7, 4.6.2, 4.6.1, 4.6, 4.5.2, 4.5.1, 4.5, 4.0, 3.5, 3.0, 2.0
Client: Supported in: 4.8, 4.7.2, 4.7.1, 4.7, 4.6.2, 4.6.1, 4.6, 4.5.2, 4.5.1, 4.5, 3.5
Server: Supported in: 4.8, 4.7.2, 4.7.1, 4.7, 4.6.2, 4.6.1, 4.6, 4.5.2, 4.5.1, 4.5, 4.0
Supported in: 2.1, 2.0
Supported in: 3.1, 3.0, 2.2, 2.1, 2.0
The following example demonstrates how to retrieve and display the extensions from an X.509 certificate.
using System;
using System.Security.Cryptography.X509Certificates;
using System.Text;
public class CertificateExtensionsExample
{
public static void Main(string[] args)
{
try
{
// Load a sample X.509 certificate (replace with your actual certificate loading logic)
// For demonstration, we'll try to load a local machine certificate.
X509Certificate2 cert = null;
X509Store store = new X509Store(StoreName.My, StoreLocation.CurrentUser);
store.Open(OpenFlags.ReadOnly);
if (store.Certificates.Count > 0)
{
cert = store.Certificates[0]; // Select the first certificate
}
store.Close();
if (cert != null)
{
Console.WriteLine($"Certificate Subject: {cert.Subject}");
Console.WriteLine("--- Extensions ---");
if (cert.Extensions.Count == 0)
{
Console.WriteLine("No extensions found in this certificate.");
}
else
{
foreach (X509Extension extension in cert.Extensions)
{
Console.WriteLine($" OID: {extension.Oid.FriendlyName} ({extension.Oid.Value})");
// You can further parse the extension.Format(true) for specific extension types
// For example, for Subject Alternative Name:
if (extension.Oid.FriendlyName == "Subject Alternative Name")
{
var sanExtension = (X509EnhancedKeyUsageExtension)extension; // Type casting might be needed
Console.WriteLine($" Raw data (first 50 chars): {extension.Format(true).Substring(0, Math.Min(extension.Format(true).Length, 50))}...");
}
else
{
Console.WriteLine($" Raw data (first 50 chars): {extension.Format(true).Substring(0, Math.Min(extension.Format(true).Length, 50))}...");
}
}
}
}
else
{
Console.WriteLine("No certificates found in the current user's personal store.");
}
}
catch (Exception ex)
{
Console.WriteLine($"An error occurred: {ex.Message}");
}
}
}