Skip to content

Document ordering guarantee for X509Chain.ChainElements collection #11475

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 6 commits into from
Jun 20, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
using System;
using System.Security.Cryptography.X509Certificates;

public class ChainElementsOrdering
{
public static void DemonstrateChainElementsOrdering(X509Certificate2 certificate)
{
//<SNIPPET6>
using var chain = new X509Chain();
chain.Build(certificate);

// chain.ChainElements[0] is the leaf (end-entity) certificate
// chain.ChainElements[^1] is the root (trust anchor) certificate

Console.WriteLine("Certificate chain from leaf to root:");
for (int i = 0; i < chain.ChainElements.Count; i++)
{
var cert = chain.ChainElements[i].Certificate;
var role = i == 0 ? "Leaf" :
i == chain.ChainElements.Count - 1 ? "Root" : "Intermediate";
Console.WriteLine($"[{i}] {role}: {cert.Subject}");
}
//</SNIPPET6>
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -464,9 +464,13 @@

A chain element consists of an <xref:System.Security.Cryptography.X509Certificates.X509Certificate2> object, an <xref:System.Security.Cryptography.X509Certificates.X509ChainStatus> structure, and an extra information string.


The `ChainElements` collection is ordered from the end-entity (leaf) certificate at index 0, through any intermediate certificates, to the trust anchor (root certificate) at the final index. This ordering is consistent across all platforms.

## Examples
The following code example demonstrates the ordering of chain elements:

:::code language="csharp" source="~/snippets/csharp/System.Security.Cryptography.X509Certificates/X509Chain/Overview/chainelements-ordering.cs" id="Snippet6":::

The following code example opens the current user's personal certificate store, allows you to select a certificate, then writes certificate and certificate chain information to the console. The output depends on the certificate you select.

:::code language="csharp" source="~/snippets/csharp/System.Security.Cryptography.X509Certificates/X509Chain/Overview/x509chaintest.cs" id="Snippet4":::
Expand Down