CertAttributes: Accessing X509 Certificate Attributes
CertAttributes is a .NET assembly utility using P/Invoke to CryptoAPI which demonstrates
the rudimentary steps in extracting standard X509 certificate extensions. It is meant
to demonstrate techniques to supplement currently shipping .NET
crypto capability.
The CertAttributes code:
- Searches for a certificate in the CU MY system store using
CertFindCertificateInStore()
- Marshals the returned certificate context pointer to a managed
CERT_CONTEXT structure
- "Walks" an IntPtr through the CERT_CONTEXT to access the SubjectPublicKeyInfo field
- Uses the SubjectPublicKeyInfo pointer to get the certificate public key length via
CertGetPublicKeyLength()
- Continues marching IntPtr through CERT_CONTEXT to access cExtension and rgExtensions fields
- Searches the certificate for common extension OIDs with
CertFindExtension()
- Decodes the encoded extension data using
CryptDecodeObject()
- Demonstrates how to extract information from a decoded certificate extension for the szOID_ENHANCED_KEY_USAGE case.
- Demonstrates extracting struct member data for string arrays (pointer to pointers) using an IntPtr approach.
While it is possible to declare a rather large CERT_CONTEXT structure with its many
in-lined substructures in managed code, the
technique used here involves simply calculating offsets of the necessary fields (in an OS independent manner)
and manually advancing an IntPtr to access the required fields. This technique is used extensively
in advanced P/Invoke and is important to understand if you plan to use P/Invoke regularly.
Because certificate extensions decode to a
wide variety
of different types of structures,
marshaling of decoded data to useable user-friendly data must be handled on an
OID case-by-case basis. CertAttributes demonstrates a simple approach using a String based switch/case
structure.
CertAttributes takes a single argument, a certificate SubjectName substring.
C# Source
Michel I. Gallant
neutron@istar.ca