How to properly encode / decode X509_AUTHORITY_KEY_ID

  asn.1, c++, cryptoapi, encode

I’m trying to encode and then decode CERT_AUTHORITY_KEY_ID_INFO structure. But I’m getting an error and I couldn’t find an example online. How to do the round trip properly?

CERT_AUTHORITY_KEY_ID_INFO info;
info.KeyId.cbData = 10;
info.KeyId.pbData = new BYTE[10]{ 1,2,3,4,5,1,2,3,4,5 };
info.CertIssuer.cbData = 10;
info.CertIssuer.pbData = new BYTE[10]{ 2,4,6,8,10,2,4,6,8,10 };
info.CertSerialNumber.cbData = 10;
info.CertSerialNumber.pbData = new BYTE[10]{ 3, 6, 9, 12, 15, 3, 6, 9, 12, 15 };

DWORD dwSize = 0;
CryptEncodeObject(X509_ASN_ENCODING,
    X509_AUTHORITY_KEY_ID,
    (LPVOID)&info,
    NULL, &dwSize);

std::vector<BYTE> pbAuthorityKeyId(dwSize + 1, 0);

CryptEncodeObject(X509_ASN_ENCODING,
    X509_AUTHORITY_KEY_ID,
    (LPVOID)&info,
    &pbAuthorityKeyId[0], &dwSize);

CERT_AUTHORITY_KEY_ID_INFO afterRoundTrip;
DWORD dwSize2 = 0;
LPBYTE buf = NULL;
if (!CryptDecodeObject(X509_ASN_ENCODING, X509_AUTHORITY_KEY_ID, pbAuthorityKeyId.data(), dwSize, 0, nullptr, &dwSize2))
    std::cout << FormatError(GetLastError()) <<std::endl;
CryptDecodeObject(X509_ASN_ENCODING, X509_AUTHORITY_KEY_ID, pbAuthorityKeyId.data(), dwSize, 0, &afterRoundTrip, &dwSize2);

The output is:

ASN1 corrupted data.

Source: Windows Questions C++

LEAVE A COMMENT