CreateCertificateContext Failed

CertCreateCertificateContext failure can be fixed with first exporting the certificate to DER Encoded Binary X.509 (cer file) manually.

std::vector<BYTE> vec;

PCCERT_CONTEXT pCertContext = NULL;
if (pCertContext = ::CertCreateCertificateContext(
    PKCS_7_ASN_ENCODING | X509_ASN_ENCODING, 
    vec.data(), 
    vec.size()))
{
    std::cout << "Success!\n";
}
else
{
    std::cout << "Failure!\n";
}

If one want to forgo the manual export option, CryptQueryObject can be a solution. Note: CryptQueryObject is marked deprecated by Microsoft but I still have to support older OS like WinXP, so using a newer API is out of options.

CERT_BLOB blob = {};
blob.pbData = vec.data();
blob.cbData = vec.size();

DWORD dwContentType = 0;
pCertContext = NULL;

if(::CryptQueryObject(
    CERT_QUERY_OBJECT_BLOB, 
    reinterpret_cast<LPCVOID>(&blob), 
    CERT_QUERY_CONTENT_FLAG_ALL, 
    CERT_QUERY_FORMAT_FLAG_ALL, 
    0, 
    NULL, 
    &dwContentType, 
    NULL, 
    NULL, 
    NULL, 
    reinterpret_cast<LPCVOID*>(&pCertContext)))
{
    std::cout << "Success!\n";
}
else
{
    std::cout << "Failure!\n";
}

Last but not least, remember to free the certificate context!

if(pCertContext)
    CertFreeCertificateContext(pCertContext);

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: