/*--
	listcerts.h

	List certificate test.
--*/


#include "global.h"
#pragma comment(lib, "Crypt32.lib")


int listcerts()
{
	int rv = CSP_OK;
	HCERTSTORE hCertStore; //Handle to a certificate store
	PCCERT_CONTEXT pCertContext = NULL; //

	//Open a handle to the MY\\UniTokenStore certificate store
	if ((hCertStore = CertOpenStore(CERT_STORE_PROV_PHYSICAL, X509_ASN_ENCODING | PKCS_7_ASN_ENCODING, NULL, CERT_SYSTEM_STORE_CURRENT_USER, L"MY\\UniMateStore")) != NULL)
	{
		//Go over each and every certificate within the certificate store
		while ( ((pCertContext = CertEnumCertificatesInStore(hCertStore, pCertContext)) != NULL && rv == 0) )
		{
			char name[MAX_PATH + 1];
			//Get and display the subject name from the	certificate
			if(CertGetNameString(pCertContext, CERT_NAME_SIMPLE_DISPLAY_TYPE, 0, NULL, name, sizeof(name)))
			{
				printf("%s\n", name);
			}
			else
			{
				//Failed to get subject name
				DWORD e = GetLastError();
				printf("ERR: CertGetNameString() error code = 0X%x\n", e);
				rv = CSP_FAILED;
			}
		}
		//Free the certificate context(Note: only the last pCertContext returned should be freed, since CertEnumCertificatesInStore will free the previous ones)
		CertFreeCertificateContext(pCertContext);
		//Close the handle to eTCertStore
		CertCloseStore(hCertStore,0);
	}

	return rv;
}
