.NET API Documentation

X509Certificate2.NotAfter Property

Gets the date and time after which the certificate is no longer valid.

Declaration
public override DateTime NotAfter { get; }
Property Value
A DateTime object that contains the date and time after which the certificate is no longer valid.
Implements
X509Certificate.NotAfter

Remarks

The NotAfter property returns the expiration date and time for an X.509 certificate. This value is typically represented in Coordinated Universal Time (UTC).

Certificates are used in various security protocols, such as SSL/TLS, to authenticate entities and enable encrypted communication. The expiration date is a critical security parameter that ensures certificates are periodically renewed or revoked.

If the certificate has expired, the NotAfter value will be in the past relative to the current date and time.

Examples

C# Example

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

public class CertificateExpiration
{
    public static void Main(string[] args)
    {
        try
        {
            // Load a certificate (replace with your actual certificate path or store)
            // For demonstration, let's create a dummy certificate. In a real scenario,
            // you would load an existing certificate from a file or the certificate store.
            // This dummy certificate will have a fixed expiration for testing.

            var cert = new X509Certificate2("mycert.pfx", "password"); // Replace with your certificate file and password

            // Alternatively, load from store:
            // X509Store store = new X509Store(StoreName.My, StoreLocation.CurrentUser);
            // store.Open(OpenFlags.ReadOnly);
            // X509Certificate2Collection certCollection = store.Certificates;
            // X509Certificate2 cert = certCollection[0]; // Get the first certificate

            DateTime expirationDate = cert.NotAfter;
            Console.WriteLine($"Certificate expiration date: {expirationDate}");

            if (DateTime.UtcNow > expirationDate)
            {
                Console.WriteLine("This certificate has expired.");
            }
            else
            {
                Console.WriteLine("This certificate is still valid.");
            }
        }
        catch (CryptographicException e)
        {
            Console.WriteLine($"An error occurred while loading the certificate: {e.Message}");
            Console.WriteLine("Please ensure you have a valid certificate file and password.");
        }
        catch (Exception e)
        {
            Console.WriteLine($"An unexpected error occurred: {e.Message}");
        }
    }
}

Requirements

Namespace: System.Net.Security

Assembly: System.Net.Security.dll (in .NET Framework and .NET Core)

Platform: Windows, macOS, Linux

See Also

X509Certificate2 Class | System.Net.Security Namespace | X509Certificate.NotAfter