遍历证书的源代码

#include <Windows.h>
#include <wchar.h>
#include <Wincrypt.h>
#pragma comment(lib, "Crypt32.lib")

#define CERT_SCCESSED 0;
#define CERT_FAILED  -1;
#define CERT_ENCODING_TYPE  (PKCS_7_ASN_ENCODING | X509_ASN_ENCODING);


int wmain(int argc, WCHAR** argv)
{
	if (2 != argc)
	{
		wprintf(TEXT("For example:self.exe CA \n"));
		return CERT_FAILED;
	}

	if ( 0 != wcscmp(argv[1], TEXT("CA"))   &&
		 0 != wcscmp(argv[1], TEXT("Root")) &&
		 0 != wcscmp(argv[1], TEXT("Trust"))&&
		 0 != wcscmp(argv[1], TEXT("My")))
	{
		return CERT_FAILED;
	}

	DWORD dwSize = 0L;
	WCHAR *pCertName = NULL;
	HCERTSTORE hCertStore = NULL;
	PCCERT_CONTEXT pCertContext = NULL;

	hCertStore = CertOpenStore(CERT_STORE_PROV_SYSTEM,
		0,
		NULL,
		CERT_SYSTEM_STORE_CURRENT_USER,
		argv[1]);

	if (hCertStore)
	{
		wprintf(TEXT("The %s store has been opened. \n"), argv[1]);
	}
	else
	{
		wprintf(TEXT("The store was not opened.\n"));
		return CERT_FAILED;
	}

	while( TRUE )
	{
		pCertContext= CertEnumCertificatesInStore(hCertStore, 
			pCertContext);

		if (!pCertContext)
		{
			break;
		}
		
		dwSize = CertNameToStr(pCertContext->dwCertEncodingType,
			&(pCertContext->pCertInfo->Subject),
			CERT_X500_NAME_STR,
			NULL, 
			0);

		if (dwSize > 0L)
		{
			pCertName = new WCHAR[dwSize+1];
			if (!pCertName)
			{
				wprintf(TEXT("Create memory is failed."));
				break;
			}
			ZeroMemory(pCertName, dwSize+1);

			if (CertGetNameString(pCertContext,
				CERT_NAME_SIMPLE_DISPLAY_TYPE,
				0,
				NULL,
				pCertName,
				dwSize))
			{
				wprintf(TEXT("Cert : %s \n"), pCertName);
			}
			else
			{
				wprintf(TEXT("Get cert name failed. \n"));
			}

			delete [] pCertName;
			pCertName = NULL;
		}
	} 

	if (CertCloseStore(hCertStore, 0))
	{
		wprintf(TEXT("Close the %s store!"), argv[1]);
	}
	else
	{
		wprintf(TEXT("Failed CertCloseStore\n"));
		return CERT_FAILED;
	}

	return CERT_SCCESSED;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值