Skip to content

Instantly share code, notes, and snippets.

@moehuster
Created December 3, 2019 13:03
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save moehuster/c4080924483842eb2179f62d55749e06 to your computer and use it in GitHub Desktop.
Save moehuster/c4080924483842eb2179f62d55749e06 to your computer and use it in GitHub Desktop.
CertStore.cpp
#include <stdio.h>
#include <windows.h>
#include <wincrypt.h>
#include <cryptuiapi.h>
#include <io.h>
#include <tchar.h>
#include <stdlib.h>
#pragma comment (lib, "crypt32.lib")
#pragma comment (lib, "cryptui.lib")
int main(int argc, char* argv[])
{
//--------------------------------------------------------------------
// Declare and initialize variables.
HCERTSTORE hCertStore = NULL;
PCCERT_CONTEXT pCertContext = NULL;
if(hCertStore = CertOpenStore( CERT_STORE_PROV_MEMORY, 0, NULL, 0, NULL )) {
printf("The memory store was created successfully.\n");
}
else {
printf("An error occurred during creation of the memory store!\n");
exit(1);
}
//--------------------------------------------------------------------
// Add cert to store
unsigned char CertEncoded[4096];
FILE *fp = fopen("oca1sm2.cer", "rb");
if (fp == NULL) {
printf("An error occurred during fopen(osa1sm2.cer, rb)!\n");
exit(1);
}
long DataLength = _filelength(_fileno(fp));
fread(CertEncoded, DataLength, 1, fp);
if (!CertAddEncodedCertificateToStore(hCertStore, X509_ASN_ENCODING | PKCS_7_ASN_ENCODING, CertEncoded, DataLength, CERT_STORE_ADD_USE_EXISTING, NULL)) {
printf("An error occurred during CertAddEncodedCertificateToStore!\n");
exit(1);
}
//--------------------------------------------------------------------
// Display a list of the certificates in the store and allow the user to select a certificate.
if(!(pCertContext = CryptUIDlgSelectCertificateFromStore( hCertStore, NULL, NULL, NULL, CRYPTUI_SELECT_LOCATION_COLUMN, 0, NULL))) {
printf("Select Certificate UI failed.\n" );
exit(1);
}
// Use the certificate as needed.
char pszNameString[256];
if(CertGetNameString( pCertContext, CERT_NAME_URL_TYPE, 0, NULL, pszNameString, 128)) {
printf("\nCertificate for %s \n",pszNameString);
}
else fprintf(stderr,"CertGetName failed. \n");
//--------------------------------------------------------------------
// When all processing is completed, clean up.
if(pCertContext) {
CertFreeCertificateContext(pCertContext);
}
if(hCertStore) {
if (!CertCloseStore(hCertStore,0)) {
printf("CertCloseStore failed.\n" );
exit(1);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment