X509Certificate2.GetValidityPeriod Method

Retrieves the validity period of the X.509 certificate.

Syntax

public X509Certificate2Collection GetValidityPeriod( X509Certificate2? certificate )

Parameters

Returns

An X509Certificate2Collection object that contains the certificate and any intermediate certificates in the validity period.

Remarks

This method is used to determine the range of time for which an X.509 certificate is considered valid. The validity period is defined by the certificate's Not Before and Not After dates. When you call this method, it returns a collection containing the specified certificate and any intermediate certificates that form a valid chain up to a trusted root. This is crucial for verifying the authenticity and trustworthiness of a certificate.

If the provided certificate parameter is null, the method implicitly operates on the current certificate context. This can be useful in scenarios where the certificate is already loaded or is the primary focus of the operation.

Example

C# Code Example

using System; using System.Net.Security; using System.Security.Cryptography.X509Certificates; public class CertificateExample { public static void Main(string[] args) { try { // Load a certificate (replace with your actual certificate loading logic) // For demonstration, let's try to find a suitable certificate from the user's store X509Certificate2 cert = GetUserCertificate(); if (cert != null) { Console.WriteLine($"Certificate loaded: {cert.SubjectName.Name}"); Console.WriteLine($"Valid from: {cert.NotBefore.ToLocalTime()}"); Console.WriteLine($"Valid to: {cert.NotAfter.ToLocalTime()}"); // Get the validity period X509Certificate2Collection validityPeriod = cert.GetValidityPeriod(); Console.WriteLine("\nValidity Period Certificates:"); foreach (X509Certificate2 certInPeriod in validityPeriod) { Console.WriteLine($"- {certInPeriod.SubjectName.Name}"); } } else { Console.WriteLine("Could not find a suitable certificate to demonstrate."); } } catch (Exception ex) { Console.WriteLine($"An error occurred: {ex.Message}"); } } // Helper method to find a user certificate (example) private static X509Certificate2 GetUserCertificate() { X509Store store = new X509Store(StoreName.My, StoreLocation.CurrentUser); store.Open(OpenFlags.ReadOnly); X509Certificate2Collection certificates = store.Certificates; // Attempt to find a certificate, prioritize those with private keys and valid dates X509Certificate2 foundCert = null; foreach (X509Certificate2 cert in certificates) { if (cert.HasPrivateKey && cert.NotAfter > DateTime.Now && cert.NotBefore < DateTime.Now) { foundCert = cert; break; } } store.Close(); return foundCert; } }