使用CryptoApi向证书添加扩展

时间:2016-11-28 12:44:32

标签: c++ c winapi x509certificate cryptoapi

我正在尝试使用CryptoApi为证书请求添加扩展名。这是我使用的代码:

char extensionValue[] = "testValue";


_CRYPTOAPI_BLOB myBlob = {
    (DWORD)strlen(extensionValue),
    (BYTE*)extensionValue
};

wchar_t pszString[1000];
DWORD dwLength = 1000;
bool checkEncodingToBase64Test = CryptBinaryToStringW(myBlob.pbData, myBlob.cbData, CRYPT_STRING_BASE64, (LPWSTR)pszString, &dwLength);


BSTR bstrValue = pszString;
BSTR bstrName = SysAllocString(L"1.2.643.100.111");

HRESULT checkAddingExtention = pEnroll->addExtensionToRequest(0, bstrName, bstrValue);

要检查请求,请使用https://certlogik.com/decoder/ 在这里查看时得到以下结果:

Requested Extensions:
        X509v3 Extended Key Usage: 
            TLS Web Client Authentication, E-mail Protection, 1.2.643.2.2.34.6
        X509v3 Key Usage: 
            Digital Signature, Non Repudiation, Key Encipherment, Data Encipherment
        1.2.643.100.111: 
            testValue

SEQUENCE {:
   OBJECT IDENTIFIER '1 2 643 100 111'
   OCTET STRING 74 65 73 74 56 61 6C 75 65
}

但我需要得到这种结构:

SEQUENCE {
  OBJECT IDENTIFIER '1 2 643 100 111'
  OCTET STRING, encapsulates {
  UTF8String
  'testValue'
  }
}

如何实现这一目标?如何将UTF8字符串放在扩展名中?

1 个答案:

答案 0 :(得分:0)

尝试通过这种方式完成

WCHAR *id = L"testValue";
CERT_NAME_VALUE otherNameValue = { CERT_RDN_UTF8_STRING, (DWORD)wcslen(id) * sizeof(wchar_t), (PBYTE)id };

BYTE *buf;
DWORD size = 0;
CryptEncodeObjectEx(PKCS_7_ASN_ENCODING | X509_ASN_ENCODING, X509_ANY_STRING, &otherNameValue, CRYPT_ENCODE_ALLOC_FLAG, NULL, &buf, &size);

CERT_EXTENSION CertExtension[] = { {"1.2.643.100.111", FALSE, size, buf} };

...
LocalFree(buf);