简体   繁体   English

从证书中获取“密钥用法”

[英]Get the “Key Usage” from Certificate

What API can I use to get the "Key Usage" from a certificate. 我可以使用什么API从证书中获取“密钥用法”。 I Specifically want to know if a given certificate has "Digital Signature" or not. 我特别想知道给定的证书是否具有“数字签名”。 Below screenshot is the detail of a certificate in windows. 屏幕截图下方是Windows中证书的详细信息。 I need the API that gives me the "Key Usage". 我需要给我“密钥用法”的API。 The code is for windows and I am writing my code in C++. 该代码适用于Windows,我正在用C ++编写代码。

在此处输入图片说明

Thank you 谢谢

Sam 山姆

Start with CertOpenStore , then call CertFindCertificateInStore in a loop until you find the certificate you are interested in. CertOpenStore开始,然后循环调用CertFindCertificateInStore ,直到找到您感兴趣的证书。

The returned CERT_CONTEXT contains a pointer to a CERT_INFO struct. 返回的CERT_CONTEXT包含一个指向CERT_INFO结构的指针。 You will then want to walk the rgExtension member which is an array of CERT_EXTENSION objects. 然后,您将需要遍历rgExtension成员,该成员是CERT_EXTENSION对象的数组。 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. 您所关心的是将pszObjId设置为szOID_KEY_USAGE_RESTRICTION ,它将为您提供以下数据: CERT_KEY_USAGE_RESTRICTION_INFO ,其中RestrictedKeyUsage成员具有您感兴趣的位标志。

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 您还可以查看szOID_KEY_USAGE扩展名,该扩展名将使用相同的位标志,但是msdn 文档指出这些字段是

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. 根据需要的信息,可以使用任何扩展名。

With the help of Josh Poley , I found the answer. Josh Poley的帮助下,我找到了答案。 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;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM