Question

i want to get the certificate serial number using vc++ code.

  HANDLE hStoreHandle;
PCCERT_CONTEXT  pCertContext=NULL;
PCERT_PUBLIC_KEY_INFO pOldPubKey = NULL;
char fResponse ='n';
hStoreHandle = CertOpenSystemStore(NULL,"MY");

while(pCertContext= CertEnumCertificatesInStore(hStoreHandle,pCertContext))
{
    CString strSubVal,strResult,strInput;

    BYTE *pbName=pCertContext->pCertInfo->SerialNumber.pbData;
     }

i think the above code having theserial number data but i dont know how to get it in CString format.Guide me

Was it helpful?

Solution

copy paste the below code

#include <stdio.h>//yourDialog.cpp file
#include <windows.h>
#include <Wincrypt.h>
#include <iostream>
#include <conio.h>
#include <string>
using namespace std;
#pragma comment(lib, "crypt32.lib")
#define MY_ENCODING_TYPE  (PKCS_7_ASN_ENCODING | X509_ASN_ENCODING)

#define KEYLENGTH 0x00800000 

PCCERT_CONTEXT  pCertContext=NULL;
HANDLE hStoreHandle;    
PCERT_PUBLIC_KEY_INFO pOldPubKey = NULL;
char fResponse ='n';
hStoreHandle = CertOpenSystemStore(NULL,"MY");
pCertContext= CertEnumCertificatesInStore(hStoreHandle,pCertContext);
PCERT_INFO pCertifInfo = pCertContext->pCertInfo;
BYTE* pbData = pCertifInfo->SerialNumber.pbData;
DWORD cbData = pCertifInfo->SerialNumber.cbData;
char hex_ascii[3];
CString csAscii;
csAscii.Empty();

if (cbData > 0)
{
  int i;
  CString cs;
  for (i=0; i < cbData; i++)
  {
    BYTE bb = (BYTE) pbData[i];
    sprintf(hex_ascii, "%02X", bb);
    cs.Format("%s", hex_ascii);     
    csAscii = cs + csAscii ;
  }
}

OTHER TIPS

Not sure if you want this: the code below puts the data into a hexadecimal string (theString)

BYTE *pbName=pCertContext->pCertInfo->SerialNumber.pbData;
CString theString ;
for (int i = 0; i < pCertContext->pCertInfo->SerialNumber.cbData; i++)
{
  CString hex ;
  hex.Format("%02x", pbName[i]) ;
  theString += hex ;
}

The code above will give you the Serial Number 'in reverse'. You can confirm this by viewing the serial number in the certificate, by using the 'certmgr.msc' tool.

To get the serial number in the 'correct' order, just change the direction of the for loop. Below is the modified version of the code given above:

BYTE *pbName=pCertContext->pCertInfo->SerialNumber.pbData;
CString theString ;
for (int i = pCertContext->pCertInfo->SerialNumber.cbData - 1; i >= 0 ; i--)
{
  CString hex ;
  hex.Format("%02x", pbName[i]) ;
  theString += hex ;
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top