Sam
Sam

Reputation: 2552

Get the "Key Usage" from Certificate

What API can I use to get the "Key Usage" from a certificate. I Specifically want to know if a given certificate has "Digital Signature" or not. Below screenshot is the detail of a certificate in windows. I need the API that gives me the "Key Usage". The code is for windows and I am writing my code in C++.

enter image description here

Thank you

Sam

Upvotes: 1

Views: 2254

Answers (2)

Sam
Sam

Reputation: 2552

With the help of Josh Poley, I found the answer. Thank you Josh

bool CertHasDigitalSignature(PCCERT_CONTEXT pCert)
{
    bool retVal(false);
    CERT_EXTENSION* keyUsage;

    keyUsage = CertFindExtension(szOID_KEY_USAGE, pCert->pCertInfo->cExtension, pCert->pCertInfo->rgExtension);
    if(NULL != keyUsage)
    {
        DWORD strSz(0);

        if(CryptFormatObject(X509_ASN_ENCODING, 0, 0, NULL, szOID_KEY_USAGE, keyUsage->Value.pbData ,keyUsage->Value.cbData, NULL, &strSz))
        {
            std::wstring Buff;

            Buff.resize((strSz / sizeof(wchar_t)) + 1);
            if(CryptFormatObject(X509_ASN_ENCODING, 0, 0, NULL, szOID_KEY_USAGE, keyUsage->Value.pbData ,keyUsage->Value.cbData, (void*)Buff.data(), &strSz))
            {
                if (std::wstring::npos != Buff.find(L"Digital Signature"))
                    retVal = true;
            }
        }
    }
    return retVal;
}

Upvotes: 2

josh poley
josh poley

Reputation: 7479

Start with CertOpenStore, then call CertFindCertificateInStore in a loop until you find the certificate you are interested in.

The returned CERT_CONTEXT contains a pointer to a CERT_INFO struct. You will then want to walk the rgExtension member which is an array of CERT_EXTENSION objects. The one you care about has pszObjId set to szOID_KEY_USAGE_RESTRICTION, which will then give you this data: CERT_KEY_USAGE_RESTRICTION_INFO where the RestrictedKeyUsage member has the bit flags you are interested in.

You can also look at the szOID_KEY_USAGE extension, which will use the same bit flags, but the msdn documentation states that those fields are

advisory field[s], only, and does not imply that usage of the key is restricted to the purpose indicated

Depending on what you need the information for, you could use either extension.

Upvotes: 3

Related Questions