X509Certificate2.KeyAlgorithm Property
public string KeyAlgorithm { get; }
Description
Gets the name of the algorithm used to perform the asymmetric public-key operation for the certificate.
The KeyAlgorithm property returns a string that represents the Object Identifier (OID) of the public-key algorithm, such as "1.2.840.113549.1.1.5" for SHA1withRSA or "1.2.840.10045.4.3.2" for ECDSA with SHA256.
This property is useful for determining the cryptographic strength and type of the certificate's public key.
Return Value
string
A string representing the OID of the public-key algorithm.
Remarks
When you use the X509Certificate2 class to load a certificate, the KeyAlgorithm property is populated with the OID of the algorithm specified in the certificate's Subject Public Key Information (SPKI) field.
If the certificate does not contain valid public key information or if the algorithm is not recognized, this property may return an empty string or an unknown OID.
Example
C# Example
using System;
using System.Security.Cryptography.X509Certificates;
public class Example
{
public static void Main(string[] args)
{
try
{
// Load a certificate from the CurrentUser's My store
using (X509Store store = new X509Store(StoreName.My, StoreLocation.CurrentUser))
{
store.Open(OpenFlags.ReadOnly);
if (store.Certificates.Count > 0)
{
X509Certificate2 certificate = store.Certificates[0];
Console.WriteLine($"Certificate Subject: {certificate.Subject}");
Console.WriteLine($"Key Algorithm: {certificate.KeyAlgorithm}");
// Optionally, you can map OID to a common name
Console.WriteLine($"Key Algorithm Name: {GetAlgorithmName(certificate.KeyAlgorithm)}");
}
else
{
Console.WriteLine("No certificates found in the CurrentUser's My store.");
}
}
}
catch (Exception ex)
{
Console.WriteLine($"An error occurred: {ex.Message}");
}
}
public static string GetAlgorithmName(string oid)
{
// Basic mapping for common algorithms
switch(oid)
{
case "1.2.840.113549.1.1.1": return "RSA";
case "1.2.840.113549.1.1.5": return "SHA1withRSA";
case "1.2.840.113549.1.1.11": return "SHA256withRSA";
case "1.2.840.10045.4.3.2": return "ECDSA with SHA256";
default: return oid;
}
}
}