|
New Member
Join Date: Jun 2010
Posts: 1
|
// sorry about the formatting but you can enumerate certificates (PFX and Public Keys like below.
*iNumCerts = 0;
HCERTSTORE hTempStore = 0;
HCERTSTORE hLocalStore = NULL;
HCRYPTPROV *phProv = 0;
PCCERT_CONTEXT pContext = 0;
HCRYPTPROV hCryptProv = 0;
DWORD dwReturnCode = 0;
__try
{__try
{DWORD dwCertStore = CERT_SYSTEM_STORE_CURRENT_USER;
if(!(hLocalStore = CertOpenStore(CERT_STORE_PROV_SYSTEM,
0,
NULL,
dwCertStore,
L"MY")))
{
dwReturnCode = GetLastError();
_tprintf(_T("Failed to open store %s (%d)\n"), lpszStoreName, dwReturnCode);
__leave;
}
while ( (pContext = CertEnumCertificatesInStore(hLocalStore,
pContext)) )
{
BOOL bPfxFile = FALSE;
DWORD dwKeySpec = AT_SIGNATURE;
BOOL bFreeCertKey = TRUE;
// if its a PFX file we get a private key, if standard public CERT not private key available.
bPfxFile = CryptAcquireCertificatePrivateKey(pContext,0,
NULL,
&hCryptProv,
&dwKeySpec,
&bFreeCertKey);
// got private key for this item. Open certificate
if ( !( hTempStore = CertOpenStore(CERT_STORE_PROV_MEMORY,
hCryptProv,
NULL,
(bPfxFile?CERT_STORE_OPEN_EXISTING_FLAG:0), 0)) )
{
if ( bPfxFile )
{
// failed to open certificate store so leave.
CryptReleaseContext(hCryptProv, 0);
hCryptProv = 0;
}
DWORD dwErr = GetLastError();
_tprintf(_T("Warning CertOpenStore failed (%d)\n"), dwErr);
continue;
}
// get friendly name
TCHAR lpszFriendlyName[MAX_PATH] = {'\0'};
DWORD dwSize = sizeof(lpszFriendlyName) * sizeof(TCHAR);
LPSTR dwStrType = szOID_COMMON_NAME;
CertGetNameString(pContext,
CERT_NAME_SIMPLE_DISPLAY_TYPE,
CERT_NAME_STR_ENABLE_PUNYCODE_FLAG,
&dwStrType,
lpszFriendlyName,
dwSize);
CRYPT_DATA_BLOB pPFX = {'\0'};
// add the certificate to our memory store
CertAddCertificateContextToStore(hTempStore,
pContext,
CERT_STORE_ADD_USE_EXISTING,
NULL);
// if its a PFX key we want the private keys
DWORD dwExportFlags = EXPORT_PRIVATE_KEYS|PKCS12_INCLUDE_EXTENDED_PROPERTIES;
if ( bPfxFile )
{
// export the keys to a blob to write out to file
if ( !PFXExportCertStoreEx(hTempStore,
&pPFX,
lpszPassCode,
NULL,
dwExportFlags) )
{
CertCloseStore(hTempStore, 0);
if ( bPfxFile )
{
CryptReleaseContext(hCryptProv, 0);
hCryptProv = 0;
}
hTempStore = 0;
continue;
}
pPFX.pbData = (BYTE *)CryptMemAlloc(pPFX.cbData * sizeof(BYTE));
PFXExportCertStoreEx(hTempStore,
&pPFX,
lpszPassCode,
NULL,
dwExportFlags);
// the pPFX blob now has our binary certificate and size so simply write out to an external file
}
else
{
// this is not a PFX so we can simply write the blob directly.
// pContext->cbCertEncoded;
// pPFX.pbData = pContext->pbCertEncoded;
}
if ( bPfxFile )
CryptMemFree(pPFX.pbData);
CertCloseStore(hTempStore, 0);
if ( bPfxFile )
{
CryptReleaseContext(hCryptProv, 0);
hCryptProv = 0;
}
hTempStore = 0;
}
}
__finally
{
if ( hLocalStore )
CertCloseStore(hLocalStore,0);
return dwReturnCode;
}
}
__except(0)
{
dwReturnCode = GetExceptionCode();
return dwReturnCode;
}
|
|
|
|
|
|