X509Certificate2.KeyLength Property
public int KeyLength { get; }
Summary
Gets the key length, in bits, of the public key of the certificate.
Returns
An int that contains the key length, in bits, of the public key of the certificate.
Example
using System;
using System.Security.Cryptography.X509Certificates;
public class Example
{
public static void Main(string[] args)
{
// Load a certificate (replace with your actual certificate loading logic)
try
{
// Example: Load from a file
// X509Certificate2 cert = new X509Certificate2("mycert.pfx", "password");
// Example: Load from the current user's certificate store
X509Store store = new X509Store(StoreName.My, StoreLocation.CurrentUser);
store.Open(OpenFlags.ReadOnly);
X509Certificate2Collection certCollection = store.Certificates;
if (certCollection.Count > 0)
{
X509Certificate2 cert = certCollection[0]; // Get the first certificate
if (cert.HasPrivateKey)
{
int keyLength = cert.KeyLength;
Console.WriteLine($"Certificate '{cert.Subject}' has a public key length of {keyLength} bits.");
}
else
{
Console.WriteLine($"Certificate '{cert.Subject}' does not have a private key associated with it.");
}
}
else
{
Console.WriteLine("No certificates found in the current user's personal store.");
}
store.Close();
}
catch (CryptographicException ex)
{
Console.WriteLine($"An error occurred: {ex.Message}");
}
catch (Exception ex)
{
Console.WriteLine($"An unexpected error occurred: {ex.Message}");
}
}
}