Search code examples
ccryptoapi

Encode UTF8String to ASN1 with CryptoAPI


I use this code to encode UTF8String in ASN1:

const char *charExtensionValue = "test value тест тест with some cyrillic symbols";

CERT_NAME_VALUE myNameValue;
myNameValue.dwValueType = CERT_RDN_UTF8_STRING;
myNameValue.Value.cbData = (DWORD)(strlen(charExtensionValue)+1)*2;
myNameValue.Value.pbData = (LPBYTE)charExtensionValue;

CERT_BLOB encodedBlob;

bool checkASN1Encoding = CryptEncodeObjectEx(X509_ASN_ENCODING | PKCS_7_ASN_ENCODING, X509_ANY_STRING, &myNameValue, CRYPT_ENCODE_ALLOC_FLAG, NULL, &encodedBlob.pbData, &encodedBlob.cbData);

CryptEncodeObjectEx works well, without any errors, but the result is not expected:

OCTET STRING, encapsulates {
   UTF8String "ø§³û¦© Ґѐô´ 

What am I doing wrong?


Solution

  • the docs say CERT_RDN_UTF8_STRING means the value member must be "An array of 16 bit Unicode characters UTF8 encoded on the wire as a sequence of one, two, or three, eight-bit characters." but charExtensionValue points to an array of 8 bit characters. Also you are calculating the string as if it is a UTF-16 string which it is not. – Stuart