Retired Microsoft Blog disclaimer

This directory is a mirror of retired "Decrypt My World" MSDN blog and is provided as is. All posting authorship and copyrights belong to respective authors.
Original URL: https://blogs.msdn.microsoft.com/alejacma/2008/05/19/how-to-read-certificate-extensions-with-capicom-c/
Post name: How to read certificate extensions with CAPICOM (C#)
Original author: Alejandro Campos Magencio
Posting date: 2008-05-19T11:14:00+00:00


Hi all, welcome back,


I recently had a customer who needed to retrieveextensions from certificates the easy way in .NET 1.1, and they wanted to use CAPICOM for that. In .NET 2.0 and later we may use X509Certificate2to achieve the same results (I strongly recommend this approach), but in .NET 1.1 we only have X509Certificate class which is much more limited.


Note that the same ideas shown in the same below may be taken into account when using CAPICOM from i.e. VBScript.


The following sample shows how to use CAPICOM from a C# app to read a couple of extensions froma test cert(remember to add CAPICOM as a reference to the project first):

using CAPICOM;

...

// Load the cert
Certificate CAPICOMCertClass = new CertificateClass();
CAPICOMCertClass.Load("C:\\test.cer", null, CAPICOM_KEY_STORAGE_FLAG.CAPICOM_KEY_STORAGE_DEFAULT, CAPICOM_KEY_LOCATION.CAPICOM_CURRENT_USER_KEY);

// Find the extensions we are interested in
foreach (Extension CertExtension in CAPICOMCertClass.Extensions())
{

// Does the extension have a Friendly Name? Yes? Use it!
if (CertExtension.OID.FriendlyName == "Subject Alternative Name")
{
String stringSubjectAltName = CertExtension.EncodedData.Format(true);
MessageBox.Show(stringSubjectAltName);
}

// The extension has no Friendly Name, but we can use its OID instead
if (CertExtension.OID.Value.ToString() == "1.3.6.1.4.1.5734.1.33")
{
// For demostration purposes of Utilities class, let's assume the value of the OID is an hex string which represents the chars of a string but we need the string itself

// This property is in Hexadecimal
String stringOIDHex = CertExtension.EncodedData.Format(true).Replace(" ", "");

// We convert it to binary
Utilities utils = new UtilitiesClass();
String stringOIDBinary = utils.HexToBinary(stringOIDHex);
byte[] OIDBinary = (byte[])utils.BinaryStringToByteArray(stringOIDBinary);

// We convert it to string
String stringOID = System.Text.Encoding.ASCII.GetString(OIDBinary);
MessageBox.Show(stringOID);
}
}



References to the classes I've used: Certificate,Extensions, Extension, OID,Utilities.


I hope this helps.


Cheers,



Alex (Alejandro Campos Magencio)


Share this article:

Comments:

Comments are closed.