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