X509Certificate2.SubjectName Property

System.Net.Security

Gets the subject distinguished name for the certificate.

public X500DistinguishedName SubjectName { get; }

Property Value

A X500DistinguishedName object that contains the subject distinguished name of the certificate.

Remarks

The subject name of an X.509 certificate identifies the entity to which the certificate was issued. It is formatted as a distinguished name (DN) according to the X.500 standard. This property provides access to that distinguished name as an X500DistinguishedName object, which allows for easier parsing and manipulation of the name components.

For example, a subject name might look like: CN=www.example.com, OU=IT, O=Example Corporation, L=Anytown, ST=California, C=US

This property is useful for verifying the identity of the certificate issuer or the subject of the certificate in various security scenarios.

Example

C#


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

public class CertificateSubjectNameExample
{
    public static void Main(string[] args)
    {
        try
        {
            // Assuming you have a certificate loaded, for demonstration we'll try to get one from the store
            X509Store store = new X509Store(StoreName.My, StoreLocation.CurrentUser);
            store.Open(OpenFlags.ReadOnly);

            if (store.Certificates.Count > 0)
            {
                X509Certificate2 certificate = store.Certificates[0]; // Get the first certificate

                Console.WriteLine($"Certificate Subject: {certificate.Subject}");
                Console.WriteLine($"Subject Name: {certificate.SubjectName.Name}");

                // You can also parse specific components
                foreach (var rdn in certificate.SubjectName.Oid.FormattedName.Split(','))
                {
                    if (rdn.TrimStart().StartsWith("CN="))
                    {
                        Console.WriteLine($"Common Name (CN): {rdn.TrimStart().Substring(3)}");
                    }
                    // Add other component parsing as needed
                }
            }
            else
            {
                Console.WriteLine("No certificates found in the CurrentUser My store.");
            }
            store.Close();
        }
        catch (Exception ex)
        {
            Console.WriteLine($"An error occurred: {ex.Message}");
        }
    }
}