This function actually returns a CTL_CONTEXT pointer (please see CTL_CONTEXT on this site)
[DllImport("crypt32.dll", SetLastError = true)]
public static extern IntPtr CertCreateCTLContext(uint dwMsgAndCertEncodingType, IntPtr pbCtlEncoded, uint cbCtlEncoded);
These constants are used for the dwMsgAndCertEncodingType.
public const int X509_ASN_ENCODING = 0x00000001;
public const int PKCS_7_ASN_ENCODING = 0x00010000;
See sample code for usage.
The CTL_CONTEXT must be freed by calling CertFreeCTLContext. CertDuplicateCTLContext can be called to make a duplicate. CertSetCTLContextProperty and CertGetCTLContextProperty can be called to store and read properties for the CTL.
Please add some!
using (FileStream fileStream = new FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.Read))
{
certData = new Byte[fileStream.Length];
fileStream.Read(certData, 0, (int)fileStream.Length);
}
certDataBlob = Marshal.AllocHGlobal(certData.Length);
try
{
Marshal.Copy(certData, 0, certDataBlob, certData.Length);
IntPtr ctlContextPtr = CertCreateCTLContext(
X509_ASN_ENCODING | PKCS_7_ASN_ENCODING,
certDataBlob, (uint)certData.Length);
if (ctlContextPtr == IntPtr.Zero)
{
throw new Win32Exception(Marshal.GetLastWin32Error(), "CertCreateCTLContext");
}
try
{
CTL_CONTEXT ctlContext = (CTL_CONTEXT)Marshal.PtrToStructure(ctlContextPtr, typeof(CTL_CONTEXT));
}
finally
{
CertFreeCTLContext(ctlContextPtr);
}
}
finally
{
Marshal.FreeHGlobal(certDataBlob);
}