CertCreateCTLContext (crypt32)
Last changed: -24.16.153.89

.
Summary
The CertCreateCTLContext function creates a certificate trust list (CTL) context from an encoded CTL. The created context is not persisted to a certificate store. The function makes a copy of the encoded CTL within the created context.

This function actually returns a CTL_CONTEXT pointer (please see CTL_CONTEXT on this site)

C# Signature:

    [DllImport("crypt32.dll", SetLastError = true)]
    public static extern IntPtr CertCreateCTLContext(uint dwMsgAndCertEncodingType, IntPtr pbCtlEncoded, uint cbCtlEncoded);

VB Signature:

Related Constants

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.

User-Defined Types:

Alternative Managed API:

Notes:

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.

Tips & Tricks:

Please add some!

Sample Code:

    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);
    }

Documentation