我需要使用Windows,C++,通过模板名(模板在扩展字段中)检索。
我的脚步:
发布于 2017-02-02 13:05:44
我想贴我的代码,希望它能帮助到别人。
void GetCertificateByTemplate(char *certificateTemplate)
{
HCERTSTORE hCertStore;
PCCERT_CONTEXT pCertContext = NULL;
BYTE *pbDecoded;
DWORD cbDecoded;
_CERT_TEMPLATE_EXT *pbDecodedTemplate = NULL;
// 1). Open Local Machine certificate store
if (hCertStore = CertOpenStore(
CERT_STORE_PROV_SYSTEM,
0,
NULL,
CERT_SYSTEM_STORE_LOCAL_MACHINE,
L"My"))
{
fprintf(stderr, "The store has been opened. \n");
}
// 2). Enumerate certificates
while (pCertContext = CertEnumCertificatesInStore(
hCertStore,
pCertContext))
{
// 3). Check certificate extended data
for (int i = 0; i < pCertContext->pCertInfo->cExtension; i++)
{
// 4). Decode certificate extended data
if (CryptDecodeObject(
X509_ASN_ENCODING,
pCertContext->pCertInfo->rgExtension[i].pszObjId,
pCertContext->pCertInfo->rgExtension[i].Value.pbData,
pCertContext->pCertInfo->rgExtension[i].Value.cbData,
0,
NULL,
&cbDecoded))
{
; // error !!!
}
if (!(pbDecoded = (BYTE*)malloc(cbDecoded)))
{
; // error !!!
}
if (CryptDecodeObject(
X509_ASN_ENCODING,
pCertContext->pCertInfo->rgExtension[i].pszObjId,
pCertContext->pCertInfo->rgExtension[i].Value.pbData,
pCertContext->pCertInfo->rgExtension[i].Value.cbData,
0,
pbDecoded,
&cbDecoded))
{
pbDecodedTemplate = (_CERT_TEMPLATE_EXT*)pbDecoded;
char* objectId = pbDecodedTemplate->pszObjId;
// todo: check pDecodeTemplate->pszObjId
// 5). Compare the template string with the search one
if (strcmp(pbDecodedTemplate->pszObjId, certificateTemplate) == 0)
{
// todo: return certificate
printf("\nCertificate template found: %s \n", pbDecodedTemplate->pszObjId);
break;
}
}
}
}
// 6). Free certificate, close store
if (pCertContext)
{
CertFreeCertificateContext(pCertContext);
}
CertCloseStore(hCertStore, 0);
}https://stackoverflow.com/questions/41982617
复制相似问题