Sunday 13 March 2016

How to get X509Certificate2 certificate intended purposes in C#?

This is very simple. Using  System.Security.Cryptography.X509Certificates we can get all details of X509Certificate2  like certificate serial number, issued to - form, valid to - form, friendly name, intended purpose, certificate format and has private key or not.

I am giving a simple C# code snippet will describe more how to get these details including intended purpose.

byte[] value = .....;
X509Certificate2 x509 = new X509Certificate2(value);
var serialnumber = x509.SerialNumber;
var issuedto = Regex.Match(x509.Subject, "CN=.+?,").Value.Replace("CN=", "").Trim(',');
var issuedby = Regex.Match(x509.Issuer, "O=.+?,").Value.Replace("O=", "").Trim(',');
var validto = x509.NotAfter.ToString("f");
var validfrom = x509.NotBefore.ToString("f");

var intendedpurposes.Text = "";
foreach (var ext in x509.Extensions)
    var eku = ext as X509EnhancedKeyUsageExtension;
    if (eku != null)
        foreach (var oid in eku.EnhancedKeyUsages)
            lbl_intendedpurposes += oid.FriendlyName + ", ";

intendedpurposes = intendedpurposes.Trim(new char[]{',',' '});
var friendlyname.Text = x509.FriendlyName == "" ? "" : x509.FriendlyName;
var certtype.Text = x509.GetFormat();
var haskey.Text = x509.HasPrivateKey.ToString();

These are the intended purpose of certificate:-

  • Ensures the identity of a remote computer
  • Proves your identity to a remote computer
  • Ensures software came from software publisher
  • Protects software from alteration after publication
  • Protects e-mail messages
  • Allows data to be signed with the current time
  • Allows data on disk to be encrypted
  • Allows secure communication on the Internet
  • Permits all key usage policies
  • OCSP Signing
See also
Get x059 certificate extensions in C#