X509Certificate2.PublicKey Property
System.Net.Security
X509Certificate2
Summary
Gets the public key for the X.509 certificate.
public System.Security.Cryptography.PublicKey PublicKey { get; }
Remarks
The public key is contained in the certificate's subject public key field.
This property returns a PublicKey object that represents the public key of the certificate. This object can be used to access various properties and methods related to the public key, such as the key algorithm and the key itself.
Example
The following code example demonstrates how to retrieve the public key of an X.509 certificate.
using System;
using System.Security.Cryptography.X509Certificates;
public class Example
{
public static void Main(string[] args)
{
try
{
// Load a certificate from the user's personal store
X509Store store = new X509Store(StoreName.My, StoreLocation.CurrentUser);
store.Open(OpenFlags.ReadOnly);
// Assuming there's at least one certificate in the store
if (store.Certificates.Count > 0)
{
X509Certificate2 certificate = store.Certificates[0];
// Get the public key
System.Security.Cryptography.PublicKey publicKey = certificate.PublicKey;
Console.WriteLine($"Certificate Subject: {certificate.Subject}");
Console.WriteLine($"Public Key Algorithm: {publicKey.Oid.FriendlyName}");
Console.WriteLine($"Public Key Length (bytes): {publicKey.Key.Length}");
}
else
{
Console.WriteLine("No certificates found in the personal store.");
}
store.Close();
}
catch (Exception ex)
{
Console.WriteLine($"An error occurred: {ex.Message}");
}
}
}