CertGetNameString函数为什么总是失败
bool GetCertSubject(IN PCCERT_CONTEXT pCertContext, OUT wstring &strSubjectName)
{
BOOL fReturn = FALSE;
LPTSTR szName = NULL;
DWORD dwData = 0;
do
{
// Get Subject name size.
if (!(dwData = CertGetNameString(pCertContext,
CERT_NAME_SIMPLE_DISPLAY_TYPE,
0,
NULL,
NULL,
0)))
{
break;
}
// Allocate memory for subject name.
szName = (LPTSTR)LocalAlloc(LPTR, dwData * sizeof(TCHAR));
if (!szName)
{
break;
}
// Get subject name.
if (!(CertGetNameString(pCertContext,
CERT_NAME_SIMPLE_DISPLAY_TYPE,
0,
NULL,
szName,
dwData)))
{
break;
}
strSubjectName = (PWCHAR)szName;
fReturn = TRUE;
} while (FALSE);
if (szName != NULL)
{
LocalFree(szName);
}
return fReturn;
}
bool GetProcCertSubject(IN wstring strFileName, OUT wstring &strSubjectName)
{
BOOL fResult = FALSE;
HCERTSTORE hStore = NULL;
HCRYPTMSG hMsg = NULL;
PCCERT_CONTEXT pCertContext = NULL;
DWORD dwEncoding, dwContentType, dwFormatType;
PCMSG_SIGNER_INFO pSignerInfo = NULL;
DWORD dwSignerInfo;
CERT_INFO CertInfo;
if (strFileName.length() == 0)
{
return FALSE;
}
do
{
// Get message handle and store handle from the signed file.
fResult = CryptQueryObject(CERT_QUERY_OBJECT_FILE, /*CERT_QUERY_OBJECT_BLOB,*/
strFileName.c_str(),
CERT_QUERY_CONTENT_FLAG_PKCS7_SIGNED_EMBED,
CERT_QUERY_FORMAT_FLAG_BINARY,
0,
&dwEncoding,
&dwContentType,
&dwFormatType,
&hStore,
&hMsg,
NULL);
if (!fResult)
{
break;
}
// Get signer information size.
fResult = CryptMsgGetParam(hMsg,
CMSG_SIGNER_INFO_PARAM,
0,
NULL,
&dwSignerInfo);
if (!fResult)
{
break;
}
// Allocate memory for signer information.
pSignerInfo = (PCMSG_SIGNER_INFO)LocalAlloc(LPTR, dwSignerInfo);
if (!pSignerInfo)
{
fResult = FALSE;
break;
}
// Get Signer Information.
fResult = CryptMsgGetParam(hMsg,
CMSG_SIGNER_INFO_PARAM,
0,
(PVOID)pSignerInfo,
&dwSignerInfo);
if (!fResult)
{
break;
}
CertInfo.Issuer = pSignerInfo->Issuer;
CertInfo.SerialNumber = pSignerInfo->SerialNumber;
pCertContext = CertFindCertificateInStore(hStore,
ENCODING,
0,
CERT_FIND_SUBJECT_CERT,
(PVOID)&CertInfo,
NULL);
if (!pCertContext)
{
fResult = FALSE;
break;
}
fResult = GetCertSubject(pCertContext, strSubjectName);
} while (FALSE);
if (pSignerInfo) LocalFree(pSignerInfo);
if (pCertContext) CertFreeCertificateContext(pCertContext);
if (hStore) CertCloseStore(hStore, 0);
if (hMsg) CryptMsgClose(hMsg);
return fResult;
}