1

How to get Serial number of certificate in hex format string using cryptoapi ? I have try using

LPTSTR pszSerial = NULL;
    DWORD cbSerial = 0;
    CryptBinaryToString(pCertContext->pCertInfo->SerialNumber.pbData,pCertContext->pCertInfo->SerialNumber.cbData,CRYPT_STRING_HEX,NULL,&cbSerial);
    pszSerial = new TCHAR[cbSerial];
    CryptBinaryToString(pCertContext->pCertInfo->SerialNumber.pbData,pCertContext->pCertInfo->SerialNumber.cbData,CRYPT_STRING_HEX,pszSerial,&cbSerial);

But the result not what i want, i can get serial number but it reversed.

tandaica0612
  • 369
  • 10
  • 23

3 Answers3

5

I know it's 4 years after question was asked, but I get this page many times when I was looking for this issue solution - so perhaps I'm not the only person and my answer will help somebody ;)

I found information, that serial number is reversed in struct _CERT_INFO, so bytes from certInfo.SerialNumber.pbData should be reversed. Moreover, you should take only certInfo.SerialNumber.cbData bytes (cbData is length of serial number). It's important, because when I was trying to use whole pbData, I was getting many rubbish bytes.

When I have reversed bytes, I convert them to hex. And thats all ;)

My code:

unsigned char* pbData = pCertContext->pCertInfo->SerialNumber.pbData;
int cbData = pCertContext->pCertInfo->SerialNumber.cbData;

std::string serial((char*)pbData);
std::string serialSubstring = serial.substr(0,cbData);
std::reverse(serialSubstring.begin(), serialSubstring.end());
String snInHex(string_to_hex(serialSubstring).c_str());
//now snInHex contains serial number in hexadecimal string

Extra feature - serial number as number! When you need serial number as data (for example, to create xades file):

unsigned int sNumber;
std::stringstream ss;
ss << std::hex << snInHex.c_str();
ss >> sNumber;
//now serial number is stored as number in sNumber

Edit

string_to_hec function was taken from here: C++ convert string to hexadecimal and vice versa

Community
  • 1
  • 1
rzysia
  • 737
  • 1
  • 11
  • 26
0

In my case string_to_hex as not present. So, used below method of conversion.

DWORD dwData = pSignerInfo->SerialNumber.cbData;
char pszHexChar[4];
std::string lSerialNumber = "";
for (DWORD n = 0; n < dwData; n++)
{
    printf("%02x ", pSignerInfo->SerialNumber.pbData[dwData - (n + 1)]);
    sprintf_s(pszHexChar, sizeof(pszHexChar), "%02x ", pSignerInfo->SerialNumber.pbData[dwData - (n + 1)]);
    std::string lHexChar = pszHexChar + '\0';
    lSerialNumber = lSerialNumber + lHexChar;
}
printf("%s", lSerialNumber);
SeeTheC
  • 1,560
  • 12
  • 14
0

The following snippet shows how to reverse the certificate serial number.

for( int i = 0 ; i < pCertContext->pCertInfo->SerialNumber.cbData ; i ++ )
{
    CertSerialNo[i] = *( pCertContext->pCertInfo->SerialNumber.pbData 
                            + pCertContext->pCertInfo->SerialNumber.cbData - i - 1 ) ;
}
Raj
  • 1,113
  • 1
  • 17
  • 34