encode.c 171 KB
Newer Older
1
/*
2
 * Copyright 2005-2008 Juan Lang
3 4 5 6 7 8 9 10 11 12 13 14 15
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
16
 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
17
 *
18 19
 * This file implements ASN.1 DER encoding of a limited set of types.
 * It isn't a full ASN.1 implementation.  Microsoft implements BER
Juan Lang's avatar
Juan Lang committed
20 21
 * encoding of many of the basic types in msasn1.dll, but that interface isn't
 * implemented, so I implement them here.
22 23 24 25 26 27 28 29
 *
 * References:
 * "A Layman's Guide to a Subset of ASN.1, BER, and DER", by Burton Kaliski
 * (available online, look for a PDF copy as the HTML versions tend to have
 * translation errors.)
 *
 * RFC3280, http://www.faqs.org/rfcs/rfc3280.html
 *
Juan Lang's avatar
Juan Lang committed
30
 * MSDN, especially "Constants for CryptEncodeObject and CryptDecodeObject"
31
 */
32

33
#include <assert.h>
34 35
#include <stdarg.h>
#include <stdio.h>
36
#include <stdlib.h>
37 38 39

#define NONAMELESSUNION

40 41 42
#include "windef.h"
#include "winbase.h"
#include "wincrypt.h"
43
#include "snmp.h"
44
#include "wine/debug.h"
45
#include "wine/exception.h"
Juan Lang's avatar
Juan Lang committed
46
#include "crypt32_private.h"
47

48 49
WINE_DEFAULT_DEBUG_CHANNEL(cryptasn);
WINE_DECLARE_DEBUG_CHANNEL(crypt);
50

51 52
typedef BOOL (WINAPI *CryptEncodeObjectFunc)(DWORD, LPCSTR, const void *,
 BYTE *, DWORD *);
53 54 55 56 57

/* Prototypes for built-in encoders.  They follow the Ex style prototypes.
 * The dwCertEncodingType and lpszStructType are ignored by the built-in
 * functions, but the parameters are retained to simplify CryptEncodeObjectEx,
 * since it must call functions in external DLLs that follow these signatures.
58
 */
59
BOOL WINAPI CRYPT_AsnEncodeOid(DWORD dwCertEncodingType,
60 61 62 63 64
 LPCSTR lpszStructType, const void *pvStructInfo, DWORD dwFlags,
 PCRYPT_ENCODE_PARA pEncodePara, BYTE *pbEncoded, DWORD *pcbEncoded);
static BOOL WINAPI CRYPT_AsnEncodeExtensions(DWORD dwCertEncodingType,
 LPCSTR lpszStructType, const void *pvStructInfo, DWORD dwFlags,
 PCRYPT_ENCODE_PARA pEncodePara, BYTE *pbEncoded, DWORD *pcbEncoded);
65 66 67
static BOOL WINAPI CRYPT_AsnEncodeSequenceOfAny(DWORD dwCertEncodingType,
 LPCSTR lpszStructType, const void *pvStructInfo, DWORD dwFlags,
 PCRYPT_ENCODE_PARA pEncodePara, BYTE *pbEncoded, DWORD *pcbEncoded);
68 69 70 71 72 73
static BOOL WINAPI CRYPT_AsnEncodeBool(DWORD dwCertEncodingType,
 LPCSTR lpszStructType, const void *pvStructInfo, DWORD dwFlags,
 PCRYPT_ENCODE_PARA pEncodePara, BYTE *pbEncoded, DWORD *pcbEncoded);
static BOOL WINAPI CRYPT_AsnEncodePubKeyInfo(DWORD dwCertEncodingType,
 LPCSTR lpszStructType, const void *pvStructInfo, DWORD dwFlags,
 PCRYPT_ENCODE_PARA pEncodePara, BYTE *pbEncoded, DWORD *pcbEncoded);
74 75 76
static BOOL WINAPI CRYPT_AsnEncodeBits(DWORD dwCertEncodingType,
 LPCSTR lpszStructType, const void *pvStructInfo, DWORD dwFlags,
 PCRYPT_ENCODE_PARA pEncodePara, BYTE *pbEncoded, DWORD *pcbEncoded);
77 78 79
static BOOL WINAPI CRYPT_AsnEncodeBitsSwapBytes(DWORD dwCertEncodingType,
 LPCSTR lpszStructType, const void *pvStructInfo, DWORD dwFlags,
 PCRYPT_ENCODE_PARA pEncodePara, BYTE *pbEncoded, DWORD *pcbEncoded);
80 81 82
static BOOL WINAPI CRYPT_AsnEncodeInt(DWORD dwCertEncodingType,
 LPCSTR lpszStructType, const void *pvStructInfo, DWORD dwFlags,
 PCRYPT_ENCODE_PARA pEncodePara, BYTE *pbEncoded, DWORD *pcbEncoded);
83 84 85
static BOOL WINAPI CRYPT_AsnEncodeInteger(DWORD dwCertEncodingType,
 LPCSTR lpszStructType, const void *pvStructInfo, DWORD dwFlags,
 PCRYPT_ENCODE_PARA pEncodePara, BYTE *pbEncoded, DWORD *pcbEncoded);
86 87 88
static BOOL WINAPI CRYPT_AsnEncodeUnsignedInteger(DWORD dwCertEncodingType,
 LPCSTR lpszStructType, const void *pvStructInfo, DWORD dwFlags,
 PCRYPT_ENCODE_PARA pEncodePara, BYTE *pbEncoded, DWORD *pcbEncoded);
89 90 91
static BOOL WINAPI CRYPT_AsnEncodeChoiceOfTime(DWORD dwCertEncodingType,
 LPCSTR lpszStructType, const void *pvStructInfo, DWORD dwFlags,
 PCRYPT_ENCODE_PARA pEncodePara, BYTE *pbEncoded, DWORD *pcbEncoded);
92 93 94 95 96 97
static BOOL WINAPI CRYPT_AsnEncodeEnhancedKeyUsage(DWORD dwCertEncodingType,
 LPCSTR lpszStructType, const void *pvStructInfo, DWORD dwFlags,
 PCRYPT_ENCODE_PARA pEncodePara, BYTE *pbEncoded, DWORD *pcbEncoded);
static BOOL WINAPI CRYPT_AsnEncodePKCSAttributes(DWORD dwCertEncodingType,
 LPCSTR lpszStructType, const void *pvStructInfo, DWORD dwFlags,
 PCRYPT_ENCODE_PARA pEncodePara, BYTE *pbEncoded, DWORD *pcbEncoded);
98

99
BOOL CRYPT_EncodeEnsureSpace(DWORD dwFlags, const CRYPT_ENCODE_PARA *pEncodePara,
100
 BYTE *pbEncoded, DWORD *pcbEncoded, DWORD bytesNeeded)
101
{
102 103
    BOOL ret = TRUE;

104 105 106 107 108 109 110
    if (dwFlags & CRYPT_ENCODE_ALLOC_FLAG)
    {
        if (pEncodePara && pEncodePara->pfnAlloc)
            *(BYTE **)pbEncoded = pEncodePara->pfnAlloc(bytesNeeded);
        else
            *(BYTE **)pbEncoded = LocalAlloc(0, bytesNeeded);
        if (!*(BYTE **)pbEncoded)
111
            ret = FALSE;
112 113
        else
            *pcbEncoded = bytesNeeded;
114
    }
115 116 117 118 119 120
    else if (bytesNeeded > *pcbEncoded)
    {
        *pcbEncoded = bytesNeeded;
        SetLastError(ERROR_MORE_DATA);
        ret = FALSE;
    }
121 122
    else
        *pcbEncoded = bytesNeeded;
123
    return ret;
124 125
}

126 127 128 129 130 131 132 133
static void CRYPT_FreeSpace(const CRYPT_ENCODE_PARA *pEncodePara, LPVOID pv)
{
    if (pEncodePara && pEncodePara->pfnFree)
        pEncodePara->pfnFree(pv);
    else
        LocalFree(pv);
}

134
BOOL CRYPT_EncodeLen(DWORD len, BYTE *pbEncoded, DWORD *pcbEncoded)
135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175
{
    DWORD bytesNeeded, significantBytes = 0;

    if (len <= 0x7f)
        bytesNeeded = 1;
    else
    {
        DWORD temp;

        for (temp = len, significantBytes = sizeof(temp); !(temp & 0xff000000);
         temp <<= 8, significantBytes--)
            ;
        bytesNeeded = significantBytes + 1;
    }
    if (!pbEncoded)
    {
        *pcbEncoded = bytesNeeded;
        return TRUE;
    }
    if (*pcbEncoded < bytesNeeded)
    {
        SetLastError(ERROR_MORE_DATA);
        return FALSE;
    }
    if (len <= 0x7f)
        *pbEncoded = (BYTE)len;
    else
    {
        DWORD i;

        *pbEncoded++ = significantBytes | 0x80;
        for (i = 0; i < significantBytes; i++)
        {
            *(pbEncoded + significantBytes - i - 1) = (BYTE)(len & 0xff);
            len >>= 8;
        }
    }
    *pcbEncoded = bytesNeeded;
    return TRUE;
}

176
BOOL WINAPI CRYPT_AsnEncodeSequence(DWORD dwCertEncodingType,
177 178
 struct AsnEncodeSequenceItem items[], DWORD cItem, DWORD dwFlags,
 PCRYPT_ENCODE_PARA pEncodePara, BYTE *pbEncoded, DWORD *pcbEncoded)
179 180
{
    BOOL ret;
181
    DWORD i, dataLen = 0;
182

183
    TRACE("%p, %d, %08x, %p, %p, %d\n", items, cItem, dwFlags, pEncodePara,
184
     pbEncoded, pbEncoded ? *pcbEncoded : 0);
185 186 187 188 189
    for (i = 0, ret = TRUE; ret && i < cItem; i++)
    {
        ret = items[i].encodeFunc(dwCertEncodingType, NULL,
         items[i].pvStructInfo, dwFlags & ~CRYPT_ENCODE_ALLOC_FLAG, NULL,
         NULL, &items[i].size);
Juan Lang's avatar
Juan Lang committed
190 191 192
        /* Some functions propagate their errors through the size */
        if (!ret)
            *pcbEncoded = items[i].size;
193 194
        dataLen += items[i].size;
    }
195 196
    if (ret)
    {
197 198 199 200 201 202 203
        DWORD lenBytes, bytesNeeded;

        CRYPT_EncodeLen(dataLen, NULL, &lenBytes);
        bytesNeeded = 1 + lenBytes + dataLen;
        if (!pbEncoded)
            *pcbEncoded = bytesNeeded;
        else
204
        {
205 206 207
            if ((ret = CRYPT_EncodeEnsureSpace(dwFlags, pEncodePara, pbEncoded,
             pcbEncoded, bytesNeeded)))
            {
208 209
                BYTE *out;

210 211
                if (dwFlags & CRYPT_ENCODE_ALLOC_FLAG)
                    pbEncoded = *(BYTE **)pbEncoded;
212 213 214 215
                out = pbEncoded;
                *out++ = ASN_SEQUENCE;
                CRYPT_EncodeLen(dataLen, out, &lenBytes);
                out += lenBytes;
216 217 218 219
                for (i = 0; ret && i < cItem; i++)
                {
                    ret = items[i].encodeFunc(dwCertEncodingType, NULL,
                     items[i].pvStructInfo, dwFlags & ~CRYPT_ENCODE_ALLOC_FLAG,
220
                     NULL, out, &items[i].size);
Juan Lang's avatar
Juan Lang committed
221 222 223
                    /* Some functions propagate their errors through the size */
                    if (!ret)
                        *pcbEncoded = items[i].size;
224
                    out += items[i].size;
225
                }
226 227
                if (!ret && (dwFlags & CRYPT_ENCODE_ALLOC_FLAG))
                    CRYPT_FreeSpace(pEncodePara, pbEncoded);
228
            }
229
        }
230
    }
231
    TRACE("returning %d (%08x)\n", ret, GetLastError());
232 233 234
    return ret;
}

235
BOOL WINAPI CRYPT_AsnEncodeConstructed(DWORD dwCertEncodingType,
236 237 238 239
 LPCSTR lpszStructType, const void *pvStructInfo, DWORD dwFlags,
 PCRYPT_ENCODE_PARA pEncodePara, BYTE *pbEncoded, DWORD *pcbEncoded)
{
    BOOL ret;
240
    const struct AsnConstructedItem *item = pvStructInfo;
241 242 243 244 245 246 247 248 249 250 251 252 253
    DWORD len;

    if ((ret = item->encodeFunc(dwCertEncodingType, lpszStructType,
     item->pvStructInfo, dwFlags & ~CRYPT_ENCODE_ALLOC_FLAG, NULL, NULL, &len)))
    {
        DWORD dataLen, bytesNeeded;

        CRYPT_EncodeLen(len, NULL, &dataLen);
        bytesNeeded = 1 + dataLen + len;
        if (!pbEncoded)
            *pcbEncoded = bytesNeeded;
        else if ((ret = CRYPT_EncodeEnsureSpace(dwFlags, pEncodePara,
         pbEncoded, pcbEncoded, bytesNeeded)))
254
        {
255 256
            BYTE *out;

257 258
            if (dwFlags & CRYPT_ENCODE_ALLOC_FLAG)
                pbEncoded = *(BYTE **)pbEncoded;
259 260 261 262
            out = pbEncoded;
            *out++ = ASN_CONTEXT | ASN_CONSTRUCTOR | item->tag;
            CRYPT_EncodeLen(len, out, &dataLen);
            out += dataLen;
263 264
            ret = item->encodeFunc(dwCertEncodingType, lpszStructType,
             item->pvStructInfo, dwFlags & ~CRYPT_ENCODE_ALLOC_FLAG, NULL,
265
             out, &len);
Juan Lang's avatar
Juan Lang committed
266 267 268 269
            if (!ret)
            {
                /* Some functions propagate their errors through the size */
                *pcbEncoded = len;
270 271
                if (dwFlags & CRYPT_ENCODE_ALLOC_FLAG)
                    CRYPT_FreeSpace(pEncodePara, pbEncoded);
Juan Lang's avatar
Juan Lang committed
272
            }
273 274
        }
    }
Juan Lang's avatar
Juan Lang committed
275 276 277 278 279
    else
    {
        /* Some functions propagate their errors through the size */
        *pcbEncoded = len;
    }
280 281 282
    return ret;
}

283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298
struct AsnEncodeTagSwappedItem
{
    BYTE                    tag;
    const void             *pvStructInfo;
    CryptEncodeObjectExFunc encodeFunc;
};

/* Sort of a wacky hack, it encodes something using the struct
 * AsnEncodeTagSwappedItem's encodeFunc, then replaces the tag byte with the tag
 * given in the struct AsnEncodeTagSwappedItem.
 */
static BOOL WINAPI CRYPT_AsnEncodeSwapTag(DWORD dwCertEncodingType,
 LPCSTR lpszStructType, const void *pvStructInfo, DWORD dwFlags,
 PCRYPT_ENCODE_PARA pEncodePara, BYTE *pbEncoded, DWORD *pcbEncoded)
{
    BOOL ret;
299
    const struct AsnEncodeTagSwappedItem *item = pvStructInfo;
300 301 302 303 304 305 306 307

    ret = item->encodeFunc(dwCertEncodingType, lpszStructType,
     item->pvStructInfo, dwFlags, pEncodePara, pbEncoded, pcbEncoded);
    if (ret && pbEncoded)
        *pbEncoded = item->tag;
    return ret;
}

308 309 310 311
static BOOL WINAPI CRYPT_AsnEncodeCertVersion(DWORD dwCertEncodingType,
 LPCSTR lpszStructType, const void *pvStructInfo, DWORD dwFlags,
 PCRYPT_ENCODE_PARA pEncodePara, BYTE *pbEncoded, DWORD *pcbEncoded)
{
312
    const DWORD *ver = pvStructInfo;
313 314 315 316
    BOOL ret;

    /* CERT_V1 is not encoded */
    if (*ver == CERT_V1)
317
    {
318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334
        *pcbEncoded = 0;
        ret = TRUE;
    }
    else
    {
        struct AsnConstructedItem item = { 0, ver, CRYPT_AsnEncodeInt };

        ret = CRYPT_AsnEncodeConstructed(dwCertEncodingType, X509_INTEGER,
         &item, dwFlags, pEncodePara, pbEncoded, pcbEncoded);
    }
    return ret;
}

static BOOL WINAPI CRYPT_CopyEncodedBlob(DWORD dwCertEncodingType,
 LPCSTR lpszStructType, const void *pvStructInfo, DWORD dwFlags,
 PCRYPT_ENCODE_PARA pEncodePara, BYTE *pbEncoded, DWORD *pcbEncoded)
{
335
    const CRYPT_DER_BLOB *blob = pvStructInfo;
336 337 338 339 340 341 342 343 344
    BOOL ret;

    if (!pbEncoded)
    {
        *pcbEncoded = blob->cbData;
        ret = TRUE;
    }
    else
    {
345 346 347 348 349 350 351 352 353
        if ((ret = CRYPT_EncodeEnsureSpace(dwFlags, pEncodePara, pbEncoded,
         pcbEncoded, blob->cbData)))
        {
            if (dwFlags & CRYPT_ENCODE_ALLOC_FLAG)
                pbEncoded = *(BYTE **)pbEncoded;
            if (blob->cbData)
                memcpy(pbEncoded, blob->pbData, blob->cbData);
            *pcbEncoded = blob->cbData;
        }
354 355 356 357 358 359 360 361 362 363
    }
    return ret;
}

static BOOL WINAPI CRYPT_AsnEncodeValidity(DWORD dwCertEncodingType,
 LPCSTR lpszStructType, const void *pvStructInfo, DWORD dwFlags,
 PCRYPT_ENCODE_PARA pEncodePara, BYTE *pbEncoded, DWORD *pcbEncoded)
{
    BOOL ret;
    /* This has two filetimes in a row, a NotBefore and a NotAfter */
364
    const FILETIME *timePtr = pvStructInfo;
365
    struct AsnEncodeSequenceItem items[] = {
366 367
     { timePtr,     CRYPT_AsnEncodeChoiceOfTime, 0 },
     { timePtr + 1, CRYPT_AsnEncodeChoiceOfTime, 0 },
368 369 370
    };

    ret = CRYPT_AsnEncodeSequence(dwCertEncodingType, items, 
371
     ARRAY_SIZE(items), dwFlags, pEncodePara, pbEncoded,
372 373 374 375
     pcbEncoded);
    return ret;
}

376 377 378 379 380 381 382
/* Like CRYPT_AsnEncodeAlgorithmId, but encodes parameters as an asn.1 NULL
 * if they are empty.
 */
static BOOL WINAPI CRYPT_AsnEncodeAlgorithmIdWithNullParams(
 DWORD dwCertEncodingType, LPCSTR lpszStructType, const void *pvStructInfo,
 DWORD dwFlags, PCRYPT_ENCODE_PARA pEncodePara, BYTE *pbEncoded,
 DWORD *pcbEncoded)
383
{
384
    const CRYPT_ALGORITHM_IDENTIFIER *algo = pvStructInfo;
385 386 387 388 389 390 391 392 393 394 395 396 397 398
    static const BYTE asn1Null[] = { ASN_NULL, 0 };
    static const CRYPT_DATA_BLOB nullBlob = { sizeof(asn1Null),
     (LPBYTE)asn1Null };
    BOOL ret;
    struct AsnEncodeSequenceItem items[2] = {
     { algo->pszObjId, CRYPT_AsnEncodeOid, 0 },
     { NULL,           CRYPT_CopyEncodedBlob, 0 },
    };

    if (algo->Parameters.cbData)
        items[1].pvStructInfo = &algo->Parameters;
    else
        items[1].pvStructInfo = &nullBlob;
    ret = CRYPT_AsnEncodeSequence(dwCertEncodingType, items,
399
     ARRAY_SIZE(items), dwFlags, pEncodePara, pbEncoded,
400 401 402 403 404 405 406
     pcbEncoded);
    return ret;
}

static BOOL WINAPI CRYPT_AsnEncodeAlgorithmId(DWORD dwCertEncodingType,
 LPCSTR lpszStructType, const void *pvStructInfo, DWORD dwFlags,
 PCRYPT_ENCODE_PARA pEncodePara, BYTE *pbEncoded, DWORD *pcbEncoded)
407
{
408
    const CRYPT_ALGORITHM_IDENTIFIER *algo = pvStructInfo;
409 410 411 412 413 414 415
    BOOL ret;
    struct AsnEncodeSequenceItem items[] = {
     { algo->pszObjId,    CRYPT_AsnEncodeOid, 0 },
     { &algo->Parameters, CRYPT_CopyEncodedBlob, 0 },
    };

    ret = CRYPT_AsnEncodeSequence(dwCertEncodingType, items,
416
     ARRAY_SIZE(items), dwFlags, pEncodePara, pbEncoded,
417 418 419 420 421 422 423 424 425 426 427 428
     pcbEncoded);
    return ret;
}

static BOOL WINAPI CRYPT_AsnEncodePubKeyInfo(DWORD dwCertEncodingType,
 LPCSTR lpszStructType, const void *pvStructInfo, DWORD dwFlags,
 PCRYPT_ENCODE_PARA pEncodePara, BYTE *pbEncoded, DWORD *pcbEncoded)
{
    BOOL ret;

    __TRY
    {
429
        const CERT_PUBLIC_KEY_INFO *info = pvStructInfo;
430
        struct AsnEncodeSequenceItem items[] = {
431
         { &info->Algorithm, CRYPT_AsnEncodeAlgorithmIdWithNullParams, 0 },
432 433 434 435 436 437
         { &info->PublicKey, CRYPT_AsnEncodeBits, 0 },
        };

        TRACE("Encoding public key with OID %s\n",
         debugstr_a(info->Algorithm.pszObjId));
        ret = CRYPT_AsnEncodeSequence(dwCertEncodingType, items,
438
         ARRAY_SIZE(items), dwFlags, pEncodePara, pbEncoded,
439 440
         pcbEncoded);
    }
441
    __EXCEPT_PAGE_FAULT
442 443 444 445 446 447 448 449
    {
        SetLastError(STATUS_ACCESS_VIOLATION);
        ret = FALSE;
    }
    __ENDTRY
    return ret;
}

450 451 452 453 454 455 456 457
static BOOL WINAPI CRYPT_AsnEncodeCert(DWORD dwCertEncodingType,
 LPCSTR lpszStructType, const void *pvStructInfo, DWORD dwFlags,
 PCRYPT_ENCODE_PARA pEncodePara, BYTE *pbEncoded, DWORD *pcbEncoded)
{
    BOOL ret;

    __TRY
    {
458
        const CERT_SIGNED_CONTENT_INFO *info = pvStructInfo;
459 460 461 462 463 464 465 466 467
        struct AsnEncodeSequenceItem items[] = {
         { &info->ToBeSigned,         CRYPT_CopyEncodedBlob, 0 },
         { &info->SignatureAlgorithm, CRYPT_AsnEncodeAlgorithmId, 0 },
         { &info->Signature,          CRYPT_AsnEncodeBitsSwapBytes, 0 },
        };

        if (dwFlags & CRYPT_ENCODE_NO_SIGNATURE_BYTE_REVERSAL_FLAG)
            items[2].encodeFunc = CRYPT_AsnEncodeBits;
        ret = CRYPT_AsnEncodeSequence(dwCertEncodingType, items, 
468
         ARRAY_SIZE(items), dwFlags, pEncodePara, pbEncoded,
469 470
         pcbEncoded);
    }
471
    __EXCEPT_PAGE_FAULT
472 473 474 475 476 477 478 479
    {
        SetLastError(STATUS_ACCESS_VIOLATION);
        ret = FALSE;
    }
    __ENDTRY
    return ret;
}

480
BOOL WINAPI CRYPT_AsnEncodePubKeyInfoNoNull(DWORD dwCertEncodingType,
481 482 483 484 485 486 487 488 489 490 491 492 493
 LPCSTR lpszStructType, const void *pvStructInfo, DWORD dwFlags,
 PCRYPT_ENCODE_PARA pEncodePara, BYTE *pbEncoded, DWORD *pcbEncoded)
{
    BOOL ret;
    const CERT_PUBLIC_KEY_INFO *info = pvStructInfo;
    struct AsnEncodeSequenceItem items[] = {
     { &info->Algorithm, CRYPT_AsnEncodeAlgorithmId, 0 },
     { &info->PublicKey, CRYPT_AsnEncodeBits, 0 },
    };

    TRACE("Encoding public key with OID %s\n",
     debugstr_a(info->Algorithm.pszObjId));
    ret = CRYPT_AsnEncodeSequence(dwCertEncodingType, items,
494
     ARRAY_SIZE(items), dwFlags, pEncodePara, pbEncoded,
495 496 497 498
     pcbEncoded);
    return ret;
}

499 500 501 502 503 504 505 506 507 508 509 510
/* Like in Windows, this blithely ignores the validity of the passed-in
 * CERT_INFO, and just encodes it as-is.  The resulting encoded data may not
 * decode properly, see CRYPT_AsnDecodeCertInfo.
 */
static BOOL WINAPI CRYPT_AsnEncodeCertInfo(DWORD dwCertEncodingType,
 LPCSTR lpszStructType, const void *pvStructInfo, DWORD dwFlags,
 PCRYPT_ENCODE_PARA pEncodePara, BYTE *pbEncoded, DWORD *pcbEncoded)
{
    BOOL ret;

    __TRY
    {
511
        const CERT_INFO *info = pvStructInfo;
512 513 514 515 516 517 518
        struct AsnEncodeSequenceItem items[10] = {
         { &info->dwVersion,            CRYPT_AsnEncodeCertVersion, 0 },
         { &info->SerialNumber,         CRYPT_AsnEncodeInteger, 0 },
         { &info->SignatureAlgorithm,   CRYPT_AsnEncodeAlgorithmId, 0 },
         { &info->Issuer,               CRYPT_CopyEncodedBlob, 0 },
         { &info->NotBefore,            CRYPT_AsnEncodeValidity, 0 },
         { &info->Subject,              CRYPT_CopyEncodedBlob, 0 },
519
         { &info->SubjectPublicKeyInfo, CRYPT_AsnEncodePubKeyInfoNoNull, 0 },
520 521
         { 0 }
        };
522 523 524
        struct AsnConstructedItem constructed = { 0 };
        struct AsnEncodeTagSwappedItem swapped[2] = { { 0 } };
        DWORD cItem = 7, cSwapped = 0;
525 526

        if (info->IssuerUniqueId.cbData)
527
        {
528 529 530 531 532 533
            swapped[cSwapped].tag = ASN_CONTEXT | 1;
            swapped[cSwapped].pvStructInfo = &info->IssuerUniqueId;
            swapped[cSwapped].encodeFunc = CRYPT_AsnEncodeBits;
            items[cItem].pvStructInfo = &swapped[cSwapped];
            items[cItem].encodeFunc = CRYPT_AsnEncodeSwapTag;
            cSwapped++;
534 535 536 537
            cItem++;
        }
        if (info->SubjectUniqueId.cbData)
        {
538 539 540 541 542 543
            swapped[cSwapped].tag = ASN_CONTEXT | 2;
            swapped[cSwapped].pvStructInfo = &info->SubjectUniqueId;
            swapped[cSwapped].encodeFunc = CRYPT_AsnEncodeBits;
            items[cItem].pvStructInfo = &swapped[cSwapped];
            items[cItem].encodeFunc = CRYPT_AsnEncodeSwapTag;
            cSwapped++;
544
            cItem++;
545
        }
546 547
        if (info->cExtension)
        {
548 549 550 551
            constructed.tag = 3;
            constructed.pvStructInfo = &info->cExtension;
            constructed.encodeFunc = CRYPT_AsnEncodeExtensions;
            items[cItem].pvStructInfo = &constructed;
552 553 554 555 556 557
            items[cItem].encodeFunc = CRYPT_AsnEncodeConstructed;
            cItem++;
        }

        ret = CRYPT_AsnEncodeSequence(dwCertEncodingType, items, cItem,
         dwFlags, pEncodePara, pbEncoded, pcbEncoded);
558
    }
559
    __EXCEPT_PAGE_FAULT
560 561 562 563 564 565 566 567
    {
        SetLastError(STATUS_ACCESS_VIOLATION);
        ret = FALSE;
    }
    __ENDTRY
    return ret;
}

568
static BOOL CRYPT_AsnEncodeCRLEntry(const CRL_ENTRY *entry,
569 570 571 572 573 574 575 576 577 578
 BYTE *pbEncoded, DWORD *pcbEncoded)
{
    struct AsnEncodeSequenceItem items[3] = {
     { &entry->SerialNumber,   CRYPT_AsnEncodeInteger, 0 },
     { &entry->RevocationDate, CRYPT_AsnEncodeChoiceOfTime, 0 },
     { 0 }
    };
    DWORD cItem = 2;
    BOOL ret;

579
    TRACE("%p, %p, %d\n", entry, pbEncoded, pbEncoded ? *pcbEncoded : 0);
580 581 582 583 584 585 586 587 588 589 590

    if (entry->cExtension)
    {
        items[cItem].pvStructInfo = &entry->cExtension;
        items[cItem].encodeFunc = CRYPT_AsnEncodeExtensions;
        cItem++;
    }

    ret = CRYPT_AsnEncodeSequence(X509_ASN_ENCODING, items, cItem, 0, NULL,
     pbEncoded, pcbEncoded);

591
    TRACE("returning %d (%08x)\n", ret, GetLastError());
592 593 594 595 596 597 598 599
    return ret;
}

static BOOL WINAPI CRYPT_AsnEncodeCRLEntries(DWORD dwCertEncodingType,
 LPCSTR lpszStructType, const void *pvStructInfo, DWORD dwFlags,
 PCRYPT_ENCODE_PARA pEncodePara, BYTE *pbEncoded, DWORD *pcbEncoded)
{
    DWORD bytesNeeded, dataLen, lenBytes, i;
600 601
    const CRL_INFO *info = pvStructInfo;
    const CRL_ENTRY *rgCRLEntry = info->rgCRLEntry;
602 603
    BOOL ret = TRUE;

604
    for (i = 0, dataLen = 0; ret && i < info->cCRLEntry; i++)
605 606 607 608 609 610 611
    {
        DWORD size;

        ret = CRYPT_AsnEncodeCRLEntry(&rgCRLEntry[i], NULL, &size);
        if (ret)
            dataLen += size;
    }
612
    if (ret)
613
    {
614 615 616 617 618
        CRYPT_EncodeLen(dataLen, NULL, &lenBytes);
        bytesNeeded = 1 + lenBytes + dataLen;
        if (!pbEncoded)
            *pcbEncoded = bytesNeeded;
        else
619
        {
620 621
            if ((ret = CRYPT_EncodeEnsureSpace(dwFlags, pEncodePara, pbEncoded,
             pcbEncoded, bytesNeeded)))
622
            {
623 624
                BYTE *out;

625 626
                if (dwFlags & CRYPT_ENCODE_ALLOC_FLAG)
                    pbEncoded = *(BYTE **)pbEncoded;
627 628 629 630
                out = pbEncoded;
                *out++ = ASN_SEQUENCEOF;
                CRYPT_EncodeLen(dataLen, out, &lenBytes);
                out += lenBytes;
631
                for (i = 0; i < info->cCRLEntry; i++)
632 633
                {
                    DWORD size = dataLen;
634

635 636
                    ret = CRYPT_AsnEncodeCRLEntry(&rgCRLEntry[i], out, &size);
                    out += size;
637 638
                    dataLen -= size;
                }
639 640
                if (!ret && (dwFlags & CRYPT_ENCODE_ALLOC_FLAG))
                    CRYPT_FreeSpace(pEncodePara, pbEncoded);
641 642 643 644 645 646 647 648 649 650
            }
        }
    }
    return ret;
}

static BOOL WINAPI CRYPT_AsnEncodeCRLVersion(DWORD dwCertEncodingType,
 LPCSTR lpszStructType, const void *pvStructInfo, DWORD dwFlags,
 PCRYPT_ENCODE_PARA pEncodePara, BYTE *pbEncoded, DWORD *pcbEncoded)
{
651
    const DWORD *ver = pvStructInfo;
652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677
    BOOL ret;

    /* CRL_V1 is not encoded */
    if (*ver == CRL_V1)
    {
        *pcbEncoded = 0;
        ret = TRUE;
    }
    else
        ret = CRYPT_AsnEncodeInt(dwCertEncodingType, X509_INTEGER, ver,
         dwFlags, pEncodePara, pbEncoded, pcbEncoded);
    return ret;
}

/* Like in Windows, this blithely ignores the validity of the passed-in
 * CRL_INFO, and just encodes it as-is.  The resulting encoded data may not
 * decode properly, see CRYPT_AsnDecodeCRLInfo.
 */
static BOOL WINAPI CRYPT_AsnEncodeCRLInfo(DWORD dwCertEncodingType,
 LPCSTR lpszStructType, const void *pvStructInfo, DWORD dwFlags,
 PCRYPT_ENCODE_PARA pEncodePara, BYTE *pbEncoded, DWORD *pcbEncoded)
{
    BOOL ret;

    __TRY
    {
678
        const CRL_INFO *info = pvStructInfo;
679 680 681 682 683 684 685
        struct AsnEncodeSequenceItem items[7] = {
         { &info->dwVersion,          CRYPT_AsnEncodeCRLVersion, 0 },
         { &info->SignatureAlgorithm, CRYPT_AsnEncodeAlgorithmId, 0 },
         { &info->Issuer,             CRYPT_CopyEncodedBlob, 0 },
         { &info->ThisUpdate,         CRYPT_AsnEncodeChoiceOfTime, 0 },
         { 0 }
        };
686 687
        struct AsnConstructedItem constructed[1] = { { 0 } };
        DWORD cItem = 4, cConstructed = 0;
688 689 690 691 692 693 694 695 696

        if (info->NextUpdate.dwLowDateTime || info->NextUpdate.dwHighDateTime)
        {
            items[cItem].pvStructInfo = &info->NextUpdate;
            items[cItem].encodeFunc = CRYPT_AsnEncodeChoiceOfTime;
            cItem++;
        }
        if (info->cCRLEntry)
        {
697
            items[cItem].pvStructInfo = info;
698 699 700 701 702
            items[cItem].encodeFunc = CRYPT_AsnEncodeCRLEntries;
            cItem++;
        }
        if (info->cExtension)
        {
703 704 705 706 707 708
            constructed[cConstructed].tag = 0;
            constructed[cConstructed].pvStructInfo = &info->cExtension;
            constructed[cConstructed].encodeFunc = CRYPT_AsnEncodeExtensions;
            items[cItem].pvStructInfo = &constructed[cConstructed];
            items[cItem].encodeFunc = CRYPT_AsnEncodeConstructed;
            cConstructed++;
709 710 711 712 713 714
            cItem++;
        }

        ret = CRYPT_AsnEncodeSequence(dwCertEncodingType, items, cItem,
         dwFlags, pEncodePara, pbEncoded, pcbEncoded);
    }
715
    __EXCEPT_PAGE_FAULT
716 717 718 719 720 721 722 723
    {
        SetLastError(STATUS_ACCESS_VIOLATION);
        ret = FALSE;
    }
    __ENDTRY
    return ret;
}

724 725 726 727 728 729 730 731 732 733 734
static BOOL CRYPT_AsnEncodeExtension(CERT_EXTENSION *ext, BYTE *pbEncoded,
 DWORD *pcbEncoded)
{
    BOOL ret;
    struct AsnEncodeSequenceItem items[3] = {
     { ext->pszObjId, CRYPT_AsnEncodeOid, 0 },
     { NULL, NULL, 0 },
     { NULL, NULL, 0 },
    };
    DWORD cItem = 1;

735
    TRACE("%p, %p, %d\n", ext, pbEncoded, pbEncoded ? *pcbEncoded : 0);
736 737 738 739 740 741 742 743 744 745 746 747 748

    if (ext->fCritical)
    {
        items[cItem].pvStructInfo = &ext->fCritical;
        items[cItem].encodeFunc = CRYPT_AsnEncodeBool;
        cItem++;
    }
    items[cItem].pvStructInfo = &ext->Value;
    items[cItem].encodeFunc = CRYPT_AsnEncodeOctets;
    cItem++;

    ret = CRYPT_AsnEncodeSequence(X509_ASN_ENCODING, items, cItem, 0, NULL,
     pbEncoded, pcbEncoded);
749
    TRACE("returning %d (%08x)\n", ret, GetLastError());
750 751 752 753 754 755 756 757 758 759 760 761
    return ret;
}

static BOOL WINAPI CRYPT_AsnEncodeExtensions(DWORD dwCertEncodingType,
 LPCSTR lpszStructType, const void *pvStructInfo, DWORD dwFlags,
 PCRYPT_ENCODE_PARA pEncodePara, BYTE *pbEncoded, DWORD *pcbEncoded)
{
    BOOL ret;

    __TRY
    {
        DWORD bytesNeeded, dataLen, lenBytes, i;
762
        const CERT_EXTENSIONS *exts = pvStructInfo;
763 764 765 766 767 768 769 770 771 772

        ret = TRUE;
        for (i = 0, dataLen = 0; ret && i < exts->cExtension; i++)
        {
            DWORD size;

            ret = CRYPT_AsnEncodeExtension(&exts->rgExtension[i], NULL, &size);
            if (ret)
                dataLen += size;
        }
773
        if (ret)
774
        {
775 776 777 778 779
            CRYPT_EncodeLen(dataLen, NULL, &lenBytes);
            bytesNeeded = 1 + lenBytes + dataLen;
            if (!pbEncoded)
                *pcbEncoded = bytesNeeded;
            else
780
            {
781 782
                if ((ret = CRYPT_EncodeEnsureSpace(dwFlags, pEncodePara,
                 pbEncoded, pcbEncoded, bytesNeeded)))
783
                {
784 785
                    BYTE *out;

786 787
                    if (dwFlags & CRYPT_ENCODE_ALLOC_FLAG)
                        pbEncoded = *(BYTE **)pbEncoded;
788 789 790 791
                    out = pbEncoded;
                    *out++ = ASN_SEQUENCEOF;
                    CRYPT_EncodeLen(dataLen, out, &lenBytes);
                    out += lenBytes;
792 793 794
                    for (i = 0; i < exts->cExtension; i++)
                    {
                        DWORD size = dataLen;
795

796
                        ret = CRYPT_AsnEncodeExtension(&exts->rgExtension[i],
797 798
                         out, &size);
                        out += size;
799 800
                        dataLen -= size;
                    }
801 802
                    if (!ret && (dwFlags & CRYPT_ENCODE_ALLOC_FLAG))
                        CRYPT_FreeSpace(pEncodePara, pbEncoded);
803 804 805 806
                }
            }
        }
    }
807
    __EXCEPT_PAGE_FAULT
808 809 810 811 812 813 814 815
    {
        SetLastError(STATUS_ACCESS_VIOLATION);
        ret = FALSE;
    }
    __ENDTRY
    return ret;
}

816
BOOL WINAPI CRYPT_AsnEncodeOid(DWORD dwCertEncodingType,
817 818
 LPCSTR lpszStructType, const void *pvStructInfo, DWORD dwFlags,
 PCRYPT_ENCODE_PARA pEncodePara, BYTE *pbEncoded, DWORD *pcbEncoded)
819
{
820
    LPCSTR pszObjId = pvStructInfo;
821
    DWORD bytesNeeded = 0, lenBytes;
822 823 824 825
    BOOL ret = TRUE;
    int firstPos = 0;
    BYTE firstByte = 0;

826 827
    TRACE("%s\n", debugstr_a(pszObjId));

828 829 830 831 832
    if (pszObjId)
    {
        const char *ptr;
        int val1, val2;

833
        if (sscanf(pszObjId, "%d.%d%n", &val1, &val2, &firstPos) != 2)
834 835 836 837 838 839 840
        {
            SetLastError(CRYPT_E_ASN1_ERROR);
            return FALSE;
        }
        bytesNeeded++;
        firstByte = val1 * 40 + val2;
        ptr = pszObjId + firstPos;
841 842 843 844 845
        if (*ptr == '.')
        {
            ptr++;
            firstPos++;
        }
846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872
        while (ret && *ptr)
        {
            int pos;

            /* note I assume each component is at most 32-bits long in base 2 */
            if (sscanf(ptr, "%d%n", &val1, &pos) == 1)
            {
                if (val1 >= 0x10000000)
                    bytesNeeded += 5;
                else if (val1 >= 0x200000)
                    bytesNeeded += 4;
                else if (val1 >= 0x4000)
                    bytesNeeded += 3;
                else if (val1 >= 0x80)
                    bytesNeeded += 2;
                else
                    bytesNeeded += 1;
                ptr += pos;
                if (*ptr == '.')
                    ptr++;
            }
            else
            {
                SetLastError(CRYPT_E_ASN1_ERROR);
                return FALSE;
            }
        }
873
        CRYPT_EncodeLen(bytesNeeded, NULL, &lenBytes);
874
    }
875 876 877
    else
        lenBytes = 1;
    bytesNeeded += 1 + lenBytes;
878 879
    if (pbEncoded)
    {
880
        if (*pcbEncoded < bytesNeeded)
881 882 883 884 885 886 887
        {
            SetLastError(ERROR_MORE_DATA);
            ret = FALSE;
        }
        else
        {
            *pbEncoded++ = ASN_OBJECTIDENTIFIER;
888 889
            CRYPT_EncodeLen(bytesNeeded - 1 - lenBytes, pbEncoded, &lenBytes);
            pbEncoded += lenBytes;
890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933
            if (pszObjId)
            {
                const char *ptr;
                int val, pos;

                *pbEncoded++ = firstByte;
                ptr = pszObjId + firstPos;
                while (ret && *ptr)
                {
                    sscanf(ptr, "%d%n", &val, &pos);
                    {
                        unsigned char outBytes[5];
                        int numBytes, i;

                        if (val >= 0x10000000)
                            numBytes = 5;
                        else if (val >= 0x200000)
                            numBytes = 4;
                        else if (val >= 0x4000)
                            numBytes = 3;
                        else if (val >= 0x80)
                            numBytes = 2;
                        else
                            numBytes = 1;
                        for (i = numBytes; i > 0; i--)
                        {
                            outBytes[i - 1] = val & 0x7f;
                            val >>= 7;
                        }
                        for (i = 0; i < numBytes - 1; i++)
                            *pbEncoded++ = outBytes[i] | 0x80;
                        *pbEncoded++ = outBytes[i];
                        ptr += pos;
                        if (*ptr == '.')
                            ptr++;
                    }
                }
            }
        }
    }
    *pcbEncoded = bytesNeeded;
    return ret;
}

934
static BOOL CRYPT_AsnEncodeStringCoerce(const CERT_NAME_VALUE *value,
935
 BYTE tag, DWORD dwFlags, const CRYPT_ENCODE_PARA *pEncodePara, BYTE *pbEncoded,
936 937 938 939 940 941
 DWORD *pcbEncoded)
{
    BOOL ret = TRUE;
    LPCSTR str = (LPCSTR)value->Value.pbData;
    DWORD bytesNeeded, lenBytes, encodedLen;

942
    encodedLen = value->Value.cbData ? value->Value.cbData : strlen(str);
943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963
    CRYPT_EncodeLen(encodedLen, NULL, &lenBytes);
    bytesNeeded = 1 + lenBytes + encodedLen;
    if (!pbEncoded)
        *pcbEncoded = bytesNeeded;
    else
    {
        if ((ret = CRYPT_EncodeEnsureSpace(dwFlags, pEncodePara,
         pbEncoded, pcbEncoded, bytesNeeded)))
        {
            if (dwFlags & CRYPT_ENCODE_ALLOC_FLAG)
                pbEncoded = *(BYTE **)pbEncoded;
            *pbEncoded++ = tag;
            CRYPT_EncodeLen(encodedLen, pbEncoded, &lenBytes);
            pbEncoded += lenBytes;
            memcpy(pbEncoded, str, encodedLen);
        }
    }
    return ret;
}

static BOOL CRYPT_AsnEncodeBMPString(const CERT_NAME_VALUE *value,
964
 DWORD dwFlags, const CRYPT_ENCODE_PARA *pEncodePara, BYTE *pbEncoded,
965 966 967 968 969 970
 DWORD *pcbEncoded)
{
    BOOL ret = TRUE;
    LPCWSTR str = (LPCWSTR)value->Value.pbData;
    DWORD bytesNeeded, lenBytes, strLen;

971 972 973 974 975 976
    if (value->Value.cbData)
        strLen = value->Value.cbData / sizeof(WCHAR);
    else if (value->Value.pbData)
        strLen = lstrlenW(str);
    else
        strLen = 0;
977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003
    CRYPT_EncodeLen(strLen * 2, NULL, &lenBytes);
    bytesNeeded = 1 + lenBytes + strLen * 2;
    if (!pbEncoded)
        *pcbEncoded = bytesNeeded;
    else
    {
        if ((ret = CRYPT_EncodeEnsureSpace(dwFlags, pEncodePara,
         pbEncoded, pcbEncoded, bytesNeeded)))
        {
            DWORD i;

            if (dwFlags & CRYPT_ENCODE_ALLOC_FLAG)
                pbEncoded = *(BYTE **)pbEncoded;
            *pbEncoded++ = ASN_BMPSTRING;
            CRYPT_EncodeLen(strLen * 2, pbEncoded, &lenBytes);
            pbEncoded += lenBytes;
            for (i = 0; i < strLen; i++)
            {
                *pbEncoded++ = (str[i] & 0xff00) >> 8;
                *pbEncoded++ = str[i] & 0x00ff;
            }
        }
    }
    return ret;
}

static BOOL CRYPT_AsnEncodeUTF8String(const CERT_NAME_VALUE *value,
1004
 DWORD dwFlags, const CRYPT_ENCODE_PARA *pEncodePara, BYTE *pbEncoded,
1005 1006 1007 1008 1009 1010
 DWORD *pcbEncoded)
{
    BOOL ret = TRUE;
    LPCWSTR str = (LPCWSTR)value->Value.pbData;
    DWORD bytesNeeded, lenBytes, encodedLen, strLen;

1011 1012 1013
    if (value->Value.cbData)
        strLen = value->Value.cbData / sizeof(WCHAR);
    else if (str)
1014
        strLen = lstrlenW(str);
1015 1016
    else
        strLen = 0;
1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039
    encodedLen = WideCharToMultiByte(CP_UTF8, 0, str, strLen, NULL, 0, NULL,
     NULL);
    CRYPT_EncodeLen(encodedLen, NULL, &lenBytes);
    bytesNeeded = 1 + lenBytes + encodedLen;
    if (!pbEncoded)
        *pcbEncoded = bytesNeeded;
    else
    {
        if ((ret = CRYPT_EncodeEnsureSpace(dwFlags, pEncodePara,
         pbEncoded, pcbEncoded, bytesNeeded)))
        {
            if (dwFlags & CRYPT_ENCODE_ALLOC_FLAG)
                pbEncoded = *(BYTE **)pbEncoded;
            *pbEncoded++ = ASN_UTF8STRING;
            CRYPT_EncodeLen(encodedLen, pbEncoded, &lenBytes);
            pbEncoded += lenBytes;
            WideCharToMultiByte(CP_UTF8, 0, str, strLen, (LPSTR)pbEncoded,
             bytesNeeded - lenBytes - 1, NULL, NULL);
        }
    }
    return ret;
}

1040
static BOOL WINAPI CRYPT_AsnEncodeNameValue(DWORD dwCertEncodingType,
1041 1042
 LPCSTR lpszStructType, const void *pvStructInfo, DWORD dwFlags,
 PCRYPT_ENCODE_PARA pEncodePara, BYTE *pbEncoded, DWORD *pcbEncoded)
1043 1044 1045
{
    BOOL ret = TRUE;

1046
    __TRY
1047
    {
1048
        const CERT_NAME_VALUE *value = pvStructInfo;
1049 1050

        switch (value->dwValueType)
1051
        {
1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064
        case CERT_RDN_ANY_TYPE:
            /* explicitly disallowed */
            SetLastError(E_INVALIDARG);
            ret = FALSE;
            break;
        case CERT_RDN_ENCODED_BLOB:
            ret = CRYPT_CopyEncodedBlob(dwCertEncodingType, NULL,
             &value->Value, dwFlags, pEncodePara, pbEncoded, pcbEncoded);
            break;
        case CERT_RDN_OCTET_STRING:
            ret = CRYPT_AsnEncodeStringCoerce(value, ASN_OCTETSTRING,
             dwFlags, pEncodePara, pbEncoded, pcbEncoded);
            break;
1065
        case CERT_RDN_NUMERIC_STRING:
1066 1067
            ret = CRYPT_AsnEncodeStringCoerce(value, ASN_NUMERICSTRING,
             dwFlags, pEncodePara, pbEncoded, pcbEncoded);
1068 1069
            break;
        case CERT_RDN_PRINTABLE_STRING:
1070 1071 1072 1073 1074 1075
            ret = CRYPT_AsnEncodeStringCoerce(value, ASN_PRINTABLESTRING,
             dwFlags, pEncodePara, pbEncoded, pcbEncoded);
            break;
        case CERT_RDN_TELETEX_STRING:
            ret = CRYPT_AsnEncodeStringCoerce(value, ASN_T61STRING,
             dwFlags, pEncodePara, pbEncoded, pcbEncoded);
1076
            break;
1077 1078 1079
        case CERT_RDN_VIDEOTEX_STRING:
            ret = CRYPT_AsnEncodeStringCoerce(value,
             ASN_VIDEOTEXSTRING, dwFlags, pEncodePara, pbEncoded, pcbEncoded);
1080 1081
            break;
        case CERT_RDN_IA5_STRING:
1082 1083
            ret = CRYPT_AsnEncodeStringCoerce(value, ASN_IA5STRING,
             dwFlags, pEncodePara, pbEncoded, pcbEncoded);
1084
            break;
1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099
        case CERT_RDN_GRAPHIC_STRING:
            ret = CRYPT_AsnEncodeStringCoerce(value, ASN_GRAPHICSTRING,
             dwFlags, pEncodePara, pbEncoded, pcbEncoded);
            break;
        case CERT_RDN_VISIBLE_STRING:
            ret = CRYPT_AsnEncodeStringCoerce(value, ASN_VISIBLESTRING,
             dwFlags, pEncodePara, pbEncoded, pcbEncoded);
            break;
        case CERT_RDN_GENERAL_STRING:
            ret = CRYPT_AsnEncodeStringCoerce(value, ASN_GENERALSTRING,
             dwFlags, pEncodePara, pbEncoded, pcbEncoded);
            break;
        case CERT_RDN_UNIVERSAL_STRING:
            FIXME("CERT_RDN_UNIVERSAL_STRING: unimplemented\n");
            SetLastError(CRYPT_E_ASN1_CHOICE);
1100 1101
            ret = FALSE;
            break;
1102 1103 1104 1105 1106 1107 1108 1109
        case CERT_RDN_BMP_STRING:
            ret = CRYPT_AsnEncodeBMPString(value, dwFlags, pEncodePara,
             pbEncoded, pcbEncoded);
            break;
        case CERT_RDN_UTF8_STRING:
            ret = CRYPT_AsnEncodeUTF8String(value, dwFlags, pEncodePara,
             pbEncoded, pcbEncoded);
            break;
1110
        default:
1111
            SetLastError(CRYPT_E_ASN1_CHOICE);
1112
            ret = FALSE;
1113 1114
        }
    }
1115 1116 1117 1118 1119 1120
    __EXCEPT_PAGE_FAULT
    {
        SetLastError(STATUS_ACCESS_VIOLATION);
        ret = FALSE;
    }
    __ENDTRY
1121 1122 1123
    return ret;
}

1124
static BOOL CRYPT_AsnEncodeRdnAttr(DWORD dwCertEncodingType,
1125
 const CERT_RDN_ATTR *attr, CryptEncodeObjectExFunc nameValueEncodeFunc,
1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138
 BYTE *pbEncoded, DWORD *pcbEncoded)
{
    DWORD bytesNeeded = 0, lenBytes, size;
    BOOL ret;

    ret = CRYPT_AsnEncodeOid(dwCertEncodingType, NULL, attr->pszObjId,
     0, NULL, NULL, &size);
    if (ret)
    {
        bytesNeeded += size;
        /* hack: a CERT_RDN_ATTR is identical to a CERT_NAME_VALUE beginning
         * with dwValueType, so "cast" it to get its encoded size
         */
1139 1140
        ret = nameValueEncodeFunc(dwCertEncodingType, NULL, &attr->dwValueType,
         0, NULL, NULL, &size);
1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165
        if (ret)
        {
            bytesNeeded += size;
            CRYPT_EncodeLen(bytesNeeded, NULL, &lenBytes);
            bytesNeeded += 1 + lenBytes;
            if (pbEncoded)
            {
                if (*pcbEncoded < bytesNeeded)
                {
                    SetLastError(ERROR_MORE_DATA);
                    ret = FALSE;
                }
                else
                {
                    *pbEncoded++ = ASN_SEQUENCE;
                    CRYPT_EncodeLen(bytesNeeded - lenBytes - 1, pbEncoded,
                     &lenBytes);
                    pbEncoded += lenBytes;
                    size = bytesNeeded - 1 - lenBytes;
                    ret = CRYPT_AsnEncodeOid(dwCertEncodingType, NULL,
                     attr->pszObjId, 0, NULL, pbEncoded, &size);
                    if (ret)
                    {
                        pbEncoded += size;
                        size = bytesNeeded - 1 - lenBytes - size;
1166 1167
                        ret = nameValueEncodeFunc(dwCertEncodingType, NULL,
                         &attr->dwValueType, 0, NULL, pbEncoded, &size);
1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184
                        if (!ret)
                            *pcbEncoded = size;
                    }
                }
            }
            if (ret)
                *pcbEncoded = bytesNeeded;
        }
        else
        {
            /* Have to propagate index of failing character */
            *pcbEncoded = size;
        }
    }
    return ret;
}

1185
static int __cdecl BLOBComp(const void *l, const void *r)
1186
{
1187
    const CRYPT_DER_BLOB *a = l, *b = r;
1188 1189 1190 1191 1192 1193 1194
    int ret;

    if (!(ret = memcmp(a->pbData, b->pbData, min(a->cbData, b->cbData))))
        ret = a->cbData - b->cbData;
    return ret;
}

1195
/* This encodes a SET OF, which in DER must be lexicographically sorted.
1196
 */
1197 1198 1199 1200
static BOOL WINAPI CRYPT_DEREncodeSet(DWORD dwCertEncodingType,
 LPCSTR lpszStructType, const void *pvStructInfo, DWORD dwFlags,
 PCRYPT_ENCODE_PARA pEncodePara, BYTE *pbEncoded, DWORD *pcbEncoded)
{
1201
    const CRYPT_BLOB_ARRAY *set = pvStructInfo;
1202
    DWORD bytesNeeded = 0, lenBytes, i;
1203
    BOOL ret;
1204

1205 1206
    for (i = 0; i < set->cBlob; i++)
        bytesNeeded += set->rgBlob[i].cbData;
1207 1208
    CRYPT_EncodeLen(bytesNeeded, NULL, &lenBytes);
    bytesNeeded += 1 + lenBytes;
1209
    if (!pbEncoded)
1210 1211 1212 1213
    {
        *pcbEncoded = bytesNeeded;
        ret = TRUE;
    }
1214 1215 1216 1217 1218
    else if ((ret = CRYPT_EncodeEnsureSpace(dwFlags, pEncodePara,
     pbEncoded, pcbEncoded, bytesNeeded)))
    {
        if (dwFlags & CRYPT_ENCODE_ALLOC_FLAG)
            pbEncoded = *(BYTE **)pbEncoded;
1219
        qsort(set->rgBlob, set->cBlob, sizeof(CRYPT_DER_BLOB), BLOBComp);
1220 1221 1222
        *pbEncoded++ = ASN_CONSTRUCTOR | ASN_SETOF;
        CRYPT_EncodeLen(bytesNeeded - lenBytes - 1, pbEncoded, &lenBytes);
        pbEncoded += lenBytes;
Juan Lang's avatar
Juan Lang committed
1223
        for (i = 0; i < set->cBlob; i++)
1224
        {
1225 1226
            memcpy(pbEncoded, set->rgBlob[i].pbData, set->rgBlob[i].cbData);
            pbEncoded += set->rgBlob[i].cbData;
1227 1228
        }
    }
1229 1230 1231
    return ret;
}

1232 1233 1234 1235 1236
struct DERSetDescriptor
{
    DWORD                   cItems;
    const void             *items;
    size_t                  itemSize;
1237
    size_t                  itemOffset;
1238 1239 1240 1241 1242 1243 1244
    CryptEncodeObjectExFunc encode;
};

static BOOL WINAPI CRYPT_DEREncodeItemsAsSet(DWORD dwCertEncodingType,
 LPCSTR lpszStructType, const void *pvStructInfo, DWORD dwFlags,
 PCRYPT_ENCODE_PARA pEncodePara, BYTE *pbEncoded, DWORD *pcbEncoded)
{
1245
    const struct DERSetDescriptor *desc = pvStructInfo;
1246
    CRYPT_BLOB_ARRAY setOf = { 0, NULL };
1247 1248 1249 1250 1251
    BOOL ret = TRUE;
    DWORD i;

    if (desc->cItems)
    {
1252 1253
        setOf.rgBlob = CryptMemAlloc(desc->cItems * sizeof(CRYPT_DER_BLOB));
        if (!setOf.rgBlob)
1254 1255 1256
            ret = FALSE;
        else
        {
1257 1258
            setOf.cBlob = desc->cItems;
            memset(setOf.rgBlob, 0, setOf.cBlob * sizeof(CRYPT_DER_BLOB));
1259 1260
        }
    }
1261
    for (i = 0; ret && i < setOf.cBlob; i++)
1262 1263 1264
    {
        ret = desc->encode(dwCertEncodingType, lpszStructType,
         (const BYTE *)desc->items + i * desc->itemSize + desc->itemOffset,
1265
         0, NULL, NULL, &setOf.rgBlob[i].cbData);
1266 1267
        if (ret)
        {
1268 1269
            setOf.rgBlob[i].pbData = CryptMemAlloc(setOf.rgBlob[i].cbData);
            if (!setOf.rgBlob[i].pbData)
1270 1271 1272 1273
                ret = FALSE;
            else
                ret = desc->encode(dwCertEncodingType, lpszStructType,
                 (const BYTE *)desc->items + i * desc->itemSize +
1274 1275
                 desc->itemOffset, 0, NULL, setOf.rgBlob[i].pbData,
                 &setOf.rgBlob[i].cbData);
1276 1277 1278
        }
        /* Some functions propagate their errors through the size */
        if (!ret)
1279
            *pcbEncoded = setOf.rgBlob[i].cbData;
1280 1281 1282 1283 1284
    }
    if (ret)
    {
        DWORD bytesNeeded = 0, lenBytes;

1285 1286
        for (i = 0; i < setOf.cBlob; i++)
            bytesNeeded += setOf.rgBlob[i].cbData;
1287 1288 1289 1290 1291 1292 1293 1294 1295
        CRYPT_EncodeLen(bytesNeeded, NULL, &lenBytes);
        bytesNeeded += 1 + lenBytes;
        if (!pbEncoded)
            *pcbEncoded = bytesNeeded;
        else if ((ret = CRYPT_EncodeEnsureSpace(dwFlags, pEncodePara,
         pbEncoded, pcbEncoded, bytesNeeded)))
        {
            if (dwFlags & CRYPT_ENCODE_ALLOC_FLAG)
                pbEncoded = *(BYTE **)pbEncoded;
1296
            qsort(setOf.rgBlob, setOf.cBlob, sizeof(CRYPT_DER_BLOB),
1297 1298 1299 1300
             BLOBComp);
            *pbEncoded++ = ASN_CONSTRUCTOR | ASN_SETOF;
            CRYPT_EncodeLen(bytesNeeded - lenBytes - 1, pbEncoded, &lenBytes);
            pbEncoded += lenBytes;
1301
            for (i = 0; i < setOf.cBlob; i++)
1302
            {
1303 1304 1305
                memcpy(pbEncoded, setOf.rgBlob[i].pbData,
                 setOf.rgBlob[i].cbData);
                pbEncoded += setOf.rgBlob[i].cbData;
1306 1307 1308
            }
        }
    }
1309 1310 1311
    for (i = 0; i < setOf.cBlob; i++)
        CryptMemFree(setOf.rgBlob[i].pbData);
    CryptMemFree(setOf.rgBlob);
1312 1313 1314
    return ret;
}

1315
static BOOL CRYPT_AsnEncodeRdn(DWORD dwCertEncodingType, const CERT_RDN *rdn,
1316 1317 1318 1319
 CryptEncodeObjectExFunc nameValueEncodeFunc, BYTE *pbEncoded,
 DWORD *pcbEncoded)
{
    BOOL ret;
1320
    CRYPT_BLOB_ARRAY setOf = { 0, NULL };
1321 1322 1323

    __TRY
    {
1324
        DWORD i;
1325 1326 1327 1328

        ret = TRUE;
        if (rdn->cRDNAttr)
        {
1329
            setOf.rgBlob = CryptMemAlloc(rdn->cRDNAttr *
1330
             sizeof(CRYPT_DER_BLOB));
1331
            if (!setOf.rgBlob)
1332 1333
                ret = FALSE;
            else
1334 1335
            {
                setOf.cBlob = rdn->cRDNAttr;
1336
                memset(setOf.rgBlob, 0, setOf.cBlob * sizeof(CRYPT_DER_BLOB));
1337
            }
1338 1339 1340
        }
        for (i = 0; ret && i < rdn->cRDNAttr; i++)
        {
1341
            setOf.rgBlob[i].cbData = 0;
1342
            ret = CRYPT_AsnEncodeRdnAttr(dwCertEncodingType, &rdn->rgRDNAttr[i],
1343
             nameValueEncodeFunc, NULL, &setOf.rgBlob[i].cbData);
1344 1345
            if (ret)
            {
1346 1347
                setOf.rgBlob[i].pbData = CryptMemAlloc(setOf.rgBlob[i].cbData);
                if (!setOf.rgBlob[i].pbData)
1348 1349
                    ret = FALSE;
                else
1350 1351
                    ret = CRYPT_AsnEncodeRdnAttr(dwCertEncodingType,
                     &rdn->rgRDNAttr[i], nameValueEncodeFunc,
1352
                     setOf.rgBlob[i].pbData, &setOf.rgBlob[i].cbData);
1353 1354 1355 1356
            }
            if (!ret)
            {
                /* Have to propagate index of failing character */
1357
                *pcbEncoded = setOf.rgBlob[i].cbData;
1358 1359
            }
        }
1360 1361 1362
        if (ret)
            ret = CRYPT_DEREncodeSet(X509_ASN_ENCODING, NULL, &setOf, 0, NULL,
             pbEncoded, pcbEncoded);
1363 1364
        for (i = 0; i < setOf.cBlob; i++)
            CryptMemFree(setOf.rgBlob[i].pbData);
1365 1366 1367 1368 1369 1370 1371
    }
    __EXCEPT_PAGE_FAULT
    {
        SetLastError(STATUS_ACCESS_VIOLATION);
        ret = FALSE;
    }
    __ENDTRY
1372
    CryptMemFree(setOf.rgBlob);
1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384
    return ret;
}

static BOOL WINAPI CRYPT_AsnEncodeUnicodeNameValue(DWORD dwCertEncodingType,
 LPCSTR lpszStructType, const void *pvStructInfo, DWORD dwFlags,
 PCRYPT_ENCODE_PARA pEncodePara, BYTE *pbEncoded, DWORD *pcbEncoded);

static BOOL WINAPI CRYPT_AsnEncodeOrCopyUnicodeNameValue(
 DWORD dwCertEncodingType, LPCSTR lpszStructType, const void *pvStructInfo,
 DWORD dwFlags, PCRYPT_ENCODE_PARA pEncodePara, BYTE *pbEncoded,
 DWORD *pcbEncoded)
{
1385
    const CERT_NAME_VALUE *value = pvStructInfo;
1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404
    BOOL ret;

    if (value->dwValueType == CERT_RDN_ENCODED_BLOB)
        ret = CRYPT_CopyEncodedBlob(dwCertEncodingType, NULL, &value->Value,
         dwFlags, pEncodePara, pbEncoded, pcbEncoded);
    else
        ret = CRYPT_AsnEncodeUnicodeNameValue(dwCertEncodingType, NULL, value,
         dwFlags, pEncodePara, pbEncoded, pcbEncoded);
    return ret;
}

static BOOL WINAPI CRYPT_AsnEncodeUnicodeName(DWORD dwCertEncodingType,
 LPCSTR lpszStructType, const void *pvStructInfo, DWORD dwFlags,
 PCRYPT_ENCODE_PARA pEncodePara, BYTE *pbEncoded, DWORD *pcbEncoded)
{
    BOOL ret = TRUE;

    __TRY
    {
1405
        const CERT_NAME_INFO *info = pvStructInfo;
1406 1407
        DWORD bytesNeeded = 0, lenBytes, size, i;

1408
        TRACE("encoding name with %d RDNs\n", info->cRDN);
1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429
        ret = TRUE;
        for (i = 0; ret && i < info->cRDN; i++)
        {
            ret = CRYPT_AsnEncodeRdn(dwCertEncodingType, &info->rgRDN[i],
             CRYPT_AsnEncodeOrCopyUnicodeNameValue, NULL, &size);
            if (ret)
                bytesNeeded += size;
            else
                *pcbEncoded = size;
        }
        CRYPT_EncodeLen(bytesNeeded, NULL, &lenBytes);
        bytesNeeded += 1 + lenBytes;
        if (ret)
        {
            if (!pbEncoded)
                *pcbEncoded = bytesNeeded;
            else
            {
                if ((ret = CRYPT_EncodeEnsureSpace(dwFlags, pEncodePara,
                 pbEncoded, pcbEncoded, bytesNeeded)))
                {
1430 1431
                    BYTE *out;

1432 1433
                    if (dwFlags & CRYPT_ENCODE_ALLOC_FLAG)
                        pbEncoded = *(BYTE **)pbEncoded;
1434 1435 1436 1437
                    out = pbEncoded;
                    *out++ = ASN_SEQUENCEOF;
                    CRYPT_EncodeLen(bytesNeeded - lenBytes - 1, out, &lenBytes);
                    out += lenBytes;
1438 1439 1440 1441 1442
                    for (i = 0; ret && i < info->cRDN; i++)
                    {
                        size = bytesNeeded;
                        ret = CRYPT_AsnEncodeRdn(dwCertEncodingType,
                         &info->rgRDN[i], CRYPT_AsnEncodeOrCopyUnicodeNameValue,
1443
                         out, &size);
1444 1445
                        if (ret)
                        {
1446
                            out += size;
1447 1448 1449 1450 1451
                            bytesNeeded -= size;
                        }
                        else
                            *pcbEncoded = size;
                    }
1452 1453
                    if (!ret && (dwFlags & CRYPT_ENCODE_ALLOC_FLAG))
                        CRYPT_FreeSpace(pEncodePara, pbEncoded);
1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466
                }
            }
        }
    }
    __EXCEPT_PAGE_FAULT
    {
        SetLastError(STATUS_ACCESS_VIOLATION);
        ret = FALSE;
    }
    __ENDTRY
    return ret;
}

1467 1468 1469 1470
static BOOL WINAPI CRYPT_AsnEncodeCTLVersion(DWORD dwCertEncodingType,
 LPCSTR lpszStructType, const void *pvStructInfo, DWORD dwFlags,
 PCRYPT_ENCODE_PARA pEncodePara, BYTE *pbEncoded, DWORD *pcbEncoded)
{
1471
    const DWORD *ver = pvStructInfo;
1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493
    BOOL ret;

    /* CTL_V1 is not encoded */
    if (*ver == CTL_V1)
    {
        *pcbEncoded = 0;
        ret = TRUE;
    }
    else
        ret = CRYPT_AsnEncodeInt(dwCertEncodingType, X509_INTEGER, ver,
         dwFlags, pEncodePara, pbEncoded, pcbEncoded);
    return ret;
}

/* Like CRYPT_AsnEncodeAlgorithmId, but encodes parameters as an asn.1 NULL
 * if they are empty and the OID is not empty (otherwise omits them.)
 */
static BOOL WINAPI CRYPT_AsnEncodeCTLSubjectAlgorithm(
 DWORD dwCertEncodingType, LPCSTR lpszStructType, const void *pvStructInfo,
 DWORD dwFlags, PCRYPT_ENCODE_PARA pEncodePara, BYTE *pbEncoded,
 DWORD *pcbEncoded)
{
1494
    const CRYPT_ALGORITHM_IDENTIFIER *algo = pvStructInfo;
1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518
    BOOL ret;
    struct AsnEncodeSequenceItem items[2] = {
     { algo->pszObjId, CRYPT_AsnEncodeOid, 0 },
    };
    DWORD cItem = 1;

    if (algo->pszObjId)
    {
        static const BYTE asn1Null[] = { ASN_NULL, 0 };
        static const CRYPT_DATA_BLOB nullBlob = { sizeof(asn1Null),
         (LPBYTE)asn1Null };

        if (algo->Parameters.cbData)
            items[cItem].pvStructInfo = &algo->Parameters;
        else
            items[cItem].pvStructInfo = &nullBlob;
        items[cItem].encodeFunc = CRYPT_CopyEncodedBlob;
        cItem++;
    }
    ret = CRYPT_AsnEncodeSequence(dwCertEncodingType, items, cItem,
     dwFlags, pEncodePara, pbEncoded, pcbEncoded);
    return ret;
}

1519
static BOOL CRYPT_AsnEncodeCTLEntry(const CTL_ENTRY *entry,
1520 1521 1522 1523 1524 1525 1526 1527 1528
 BYTE *pbEncoded, DWORD *pcbEncoded)
{
    struct AsnEncodeSequenceItem items[2] = {
     { &entry->SubjectIdentifier, CRYPT_AsnEncodeOctets, 0 },
     { &entry->cAttribute,        CRYPT_AsnEncodePKCSAttributes, 0 },
    };
    BOOL ret;

    ret = CRYPT_AsnEncodeSequence(X509_ASN_ENCODING, items,
1529
     ARRAY_SIZE(items), 0, NULL, pbEncoded, pcbEncoded);
1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544
    return ret;
}

struct CTLEntries
{
    DWORD      cEntry;
    CTL_ENTRY *rgEntry;
};

static BOOL WINAPI CRYPT_AsnEncodeCTLEntries(DWORD dwCertEncodingType,
 LPCSTR lpszStructType, const void *pvStructInfo, DWORD dwFlags,
 PCRYPT_ENCODE_PARA pEncodePara, BYTE *pbEncoded, DWORD *pcbEncoded)
{
    BOOL ret;
    DWORD bytesNeeded, dataLen, lenBytes, i;
1545
    const struct CTLEntries *entries = pvStructInfo;
1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566

    ret = TRUE;
    for (i = 0, dataLen = 0; ret && i < entries->cEntry; i++)
    {
        DWORD size;

        ret = CRYPT_AsnEncodeCTLEntry(&entries->rgEntry[i], NULL, &size);
        if (ret)
            dataLen += size;
    }
    if (ret)
    {
        CRYPT_EncodeLen(dataLen, NULL, &lenBytes);
        bytesNeeded = 1 + lenBytes + dataLen;
        if (!pbEncoded)
            *pcbEncoded = bytesNeeded;
        else
        {
            if ((ret = CRYPT_EncodeEnsureSpace(dwFlags, pEncodePara,
             pbEncoded, pcbEncoded, bytesNeeded)))
            {
1567 1568
                BYTE *out;

1569 1570
                if (dwFlags & CRYPT_ENCODE_ALLOC_FLAG)
                    pbEncoded = *(BYTE **)pbEncoded;
1571 1572 1573 1574
                out = pbEncoded;
                *out++ = ASN_SEQUENCEOF;
                CRYPT_EncodeLen(dataLen, out, &lenBytes);
                out += lenBytes;
1575 1576 1577 1578 1579
                for (i = 0; ret && i < entries->cEntry; i++)
                {
                    DWORD size = dataLen;

                    ret = CRYPT_AsnEncodeCTLEntry(&entries->rgEntry[i],
1580 1581
                     out, &size);
                    out += size;
1582 1583
                    dataLen -= size;
                }
1584 1585
                if (!ret && (dwFlags & CRYPT_ENCODE_ALLOC_FLAG))
                    CRYPT_FreeSpace(pEncodePara, pbEncoded);
1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599
            }
        }
    }
    return ret;
}

static BOOL WINAPI CRYPT_AsnEncodeCTL(DWORD dwCertEncodingType,
 LPCSTR lpszStructType, const void *pvStructInfo, DWORD dwFlags,
 PCRYPT_ENCODE_PARA pEncodePara, BYTE *pbEncoded, DWORD *pcbEncoded)
{
    BOOL ret = FALSE;

    __TRY
    {
1600
        const CTL_INFO *info = pvStructInfo;
1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657
        struct AsnEncodeSequenceItem items[9] = {
         { &info->dwVersion,        CRYPT_AsnEncodeCTLVersion, 0 },
         { &info->SubjectUsage,     CRYPT_AsnEncodeEnhancedKeyUsage, 0 },
        };
        struct AsnConstructedItem constructed = { 0 };
        DWORD cItem = 2;

        if (info->ListIdentifier.cbData)
        {
            items[cItem].pvStructInfo = &info->ListIdentifier;
            items[cItem].encodeFunc = CRYPT_AsnEncodeOctets;
            cItem++;
        }
        if (info->SequenceNumber.cbData)
        {
            items[cItem].pvStructInfo = &info->SequenceNumber;
            items[cItem].encodeFunc = CRYPT_AsnEncodeInteger;
            cItem++;
        }
        items[cItem].pvStructInfo = &info->ThisUpdate;
        items[cItem].encodeFunc = CRYPT_AsnEncodeChoiceOfTime;
        cItem++;
        if (info->NextUpdate.dwLowDateTime || info->NextUpdate.dwHighDateTime)
        {
            items[cItem].pvStructInfo = &info->NextUpdate;
            items[cItem].encodeFunc = CRYPT_AsnEncodeChoiceOfTime;
            cItem++;
        }
        items[cItem].pvStructInfo = &info->SubjectAlgorithm;
        items[cItem].encodeFunc = CRYPT_AsnEncodeCTLSubjectAlgorithm;
        cItem++;
        if (info->cCTLEntry)
        {
            items[cItem].pvStructInfo = &info->cCTLEntry;
            items[cItem].encodeFunc = CRYPT_AsnEncodeCTLEntries;
            cItem++;
        }
        if (info->cExtension)
        {
            constructed.tag = 0;
            constructed.pvStructInfo = &info->cExtension;
            constructed.encodeFunc = CRYPT_AsnEncodeExtensions;
            items[cItem].pvStructInfo = &constructed;
            items[cItem].encodeFunc = CRYPT_AsnEncodeConstructed;
            cItem++;
        }
        ret = CRYPT_AsnEncodeSequence(dwCertEncodingType, items, cItem,
         dwFlags, pEncodePara, pbEncoded, pcbEncoded);
    }
    __EXCEPT_PAGE_FAULT
    {
        SetLastError(STATUS_ACCESS_VIOLATION);
    }
    __ENDTRY
    return ret;
}

1658
static BOOL CRYPT_AsnEncodeSMIMECapability(DWORD dwCertEncodingType,
1659 1660 1661 1662 1663 1664 1665
 LPCSTR lpszStructType, const void *pvStructInfo, DWORD dwFlags,
 PCRYPT_ENCODE_PARA pEncodePara, BYTE *pbEncoded, DWORD *pcbEncoded)
{
    BOOL ret = FALSE;

    __TRY
    {
1666
        const CRYPT_SMIME_CAPABILITY *capability = pvStructInfo;
1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677

        if (!capability->pszObjId)
            SetLastError(E_INVALIDARG);
        else
        {
            struct AsnEncodeSequenceItem items[] = {
             { capability->pszObjId, CRYPT_AsnEncodeOid, 0 },
             { &capability->Parameters, CRYPT_CopyEncodedBlob, 0 },
            };

            ret = CRYPT_AsnEncodeSequence(dwCertEncodingType, items,
1678
             ARRAY_SIZE(items), dwFlags, pEncodePara, pbEncoded,
1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698
             pcbEncoded);
        }
    }
    __EXCEPT_PAGE_FAULT
    {
        SetLastError(STATUS_ACCESS_VIOLATION);
    }
    __ENDTRY
    return ret;
}

static BOOL WINAPI CRYPT_AsnEncodeSMIMECapabilities(DWORD dwCertEncodingType,
 LPCSTR lpszStructType, const void *pvStructInfo, DWORD dwFlags,
 PCRYPT_ENCODE_PARA pEncodePara, BYTE *pbEncoded, DWORD *pcbEncoded)
{
    BOOL ret = FALSE;

    __TRY
    {
        DWORD bytesNeeded, dataLen, lenBytes, i;
1699
        const CRYPT_SMIME_CAPABILITIES *capabilities = pvStructInfo;
1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710

        ret = TRUE;
        for (i = 0, dataLen = 0; ret && i < capabilities->cCapability; i++)
        {
            DWORD size;

            ret = CRYPT_AsnEncodeSMIMECapability(dwCertEncodingType, NULL,
             &capabilities->rgCapability[i], 0, NULL, NULL, &size);
            if (ret)
                dataLen += size;
        }
1711
        if (ret)
1712
        {
1713 1714 1715 1716 1717
            CRYPT_EncodeLen(dataLen, NULL, &lenBytes);
            bytesNeeded = 1 + lenBytes + dataLen;
            if (!pbEncoded)
                *pcbEncoded = bytesNeeded;
            else
1718
            {
1719 1720
                if ((ret = CRYPT_EncodeEnsureSpace(dwFlags, pEncodePara,
                 pbEncoded, pcbEncoded, bytesNeeded)))
1721
                {
1722 1723
                    BYTE *out;

1724 1725
                    if (dwFlags & CRYPT_ENCODE_ALLOC_FLAG)
                        pbEncoded = *(BYTE **)pbEncoded;
1726 1727 1728 1729
                    out = pbEncoded;
                    *out++ = ASN_SEQUENCEOF;
                    CRYPT_EncodeLen(dataLen, out, &lenBytes);
                    out += lenBytes;
1730 1731 1732
                    for (i = 0; i < capabilities->cCapability; i++)
                    {
                        DWORD size = dataLen;
1733

1734 1735
                        ret = CRYPT_AsnEncodeSMIMECapability(dwCertEncodingType,
                         NULL, &capabilities->rgCapability[i], 0, NULL,
1736 1737
                         out, &size);
                        out += size;
1738 1739
                        dataLen -= size;
                    }
1740 1741
                    if (!ret && (dwFlags & CRYPT_ENCODE_ALLOC_FLAG))
                        CRYPT_FreeSpace(pEncodePara, pbEncoded);
1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753
                }
            }
        }
    }
    __EXCEPT_PAGE_FAULT
    {
        SetLastError(STATUS_ACCESS_VIOLATION);
    }
    __ENDTRY
    return ret;
}

1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781
static BOOL WINAPI CRYPT_AsnEncodeNoticeNumbers(DWORD dwCertEncodingType,
 LPCSTR lpszStructType, const void *pvStructInfo, DWORD dwFlags,
 PCRYPT_ENCODE_PARA pEncodePara, BYTE *pbEncoded, DWORD *pcbEncoded)
{
    const CERT_POLICY_QUALIFIER_NOTICE_REFERENCE *noticeRef = pvStructInfo;
    DWORD bytesNeeded, dataLen, lenBytes, i;
    BOOL ret = TRUE;

    for (i = 0, dataLen = 0; ret && i < noticeRef->cNoticeNumbers; i++)
    {
        DWORD size;

        ret = CRYPT_AsnEncodeInt(dwCertEncodingType, X509_INTEGER,
         &noticeRef->rgNoticeNumbers[i], 0, NULL, NULL, &size);
        if (ret)
            dataLen += size;
    }
    if (ret)
    {
        CRYPT_EncodeLen(dataLen, NULL, &lenBytes);
        bytesNeeded = 1 + lenBytes + dataLen;
        if (!pbEncoded)
            *pcbEncoded = bytesNeeded;
        else
        {
            if ((ret = CRYPT_EncodeEnsureSpace(dwFlags, pEncodePara, pbEncoded,
             pcbEncoded, bytesNeeded)))
            {
1782 1783
                BYTE *out;

1784 1785
                if (dwFlags & CRYPT_ENCODE_ALLOC_FLAG)
                    pbEncoded = *(BYTE **)pbEncoded;
1786 1787 1788 1789
                out = pbEncoded;
                *out++ = ASN_SEQUENCE;
                CRYPT_EncodeLen(dataLen, out, &lenBytes);
                out += lenBytes;
1790 1791 1792 1793 1794
                for (i = 0; i < noticeRef->cNoticeNumbers; i++)
                {
                    DWORD size = dataLen;

                    ret = CRYPT_AsnEncodeInt(dwCertEncodingType, X509_INTEGER,
1795 1796
                     &noticeRef->rgNoticeNumbers[i], 0, NULL, out, &size);
                    out += size;
1797 1798
                    dataLen -= size;
                }
1799 1800
                if (!ret && (dwFlags & CRYPT_ENCODE_ALLOC_FLAG))
                    CRYPT_FreeSpace(pEncodePara, pbEncoded);
1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820
            }
        }
    }
    return ret;
}

static BOOL WINAPI CRYPT_AsnEncodeNoticeReference(DWORD dwCertEncodingType,
 LPCSTR lpszStructType, const void *pvStructInfo, DWORD dwFlags,
 PCRYPT_ENCODE_PARA pEncodePara, BYTE *pbEncoded, DWORD *pcbEncoded)
{
    const CERT_POLICY_QUALIFIER_NOTICE_REFERENCE *noticeRef = pvStructInfo;
    BOOL ret;
    CERT_NAME_VALUE orgValue = { CERT_RDN_IA5_STRING,
     { 0, (LPBYTE)noticeRef->pszOrganization } };
    struct AsnEncodeSequenceItem items[] = {
     { &orgValue, CRYPT_AsnEncodeNameValue, 0 },
     { noticeRef, CRYPT_AsnEncodeNoticeNumbers, 0 },
    };

    ret = CRYPT_AsnEncodeSequence(dwCertEncodingType, items,
1821
     ARRAY_SIZE(items), dwFlags, pEncodePara, pbEncoded,
1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865
     pcbEncoded);
    return ret;
}

static BOOL WINAPI CRYPT_AsnEncodePolicyQualifierUserNotice(
 DWORD dwCertEncodingType, LPCSTR lpszStructType, const void *pvStructInfo,
 DWORD dwFlags, PCRYPT_ENCODE_PARA pEncodePara, BYTE *pbEncoded,
 DWORD *pcbEncoded)
{
    BOOL ret = FALSE;

    __TRY
    {
        const CERT_POLICY_QUALIFIER_USER_NOTICE *notice = pvStructInfo;
        struct AsnEncodeSequenceItem items[2];
        CERT_NAME_VALUE displayTextValue;
        DWORD cItem = 0;

        if (notice->pNoticeReference)
        {
            items[cItem].encodeFunc = CRYPT_AsnEncodeNoticeReference;
            items[cItem].pvStructInfo = notice->pNoticeReference;
            cItem++;
        }
        if (notice->pszDisplayText)
        {
            displayTextValue.dwValueType = CERT_RDN_BMP_STRING;
            displayTextValue.Value.cbData = 0;
            displayTextValue.Value.pbData = (LPBYTE)notice->pszDisplayText;
            items[cItem].encodeFunc = CRYPT_AsnEncodeNameValue;
            items[cItem].pvStructInfo = &displayTextValue;
            cItem++;
        }
        ret = CRYPT_AsnEncodeSequence(dwCertEncodingType, items, cItem,
         dwFlags, pEncodePara, pbEncoded, pcbEncoded);
    }
    __EXCEPT_PAGE_FAULT
    {
        SetLastError(STATUS_ACCESS_VIOLATION);
    }
    __ENDTRY
    return ret;
}

1866 1867 1868 1869 1870 1871 1872 1873
static BOOL WINAPI CRYPT_AsnEncodePKCSAttribute(DWORD dwCertEncodingType,
 LPCSTR lpszStructType, const void *pvStructInfo, DWORD dwFlags,
 PCRYPT_ENCODE_PARA pEncodePara, BYTE *pbEncoded, DWORD *pcbEncoded)
{
    BOOL ret = FALSE;

    __TRY
    {
1874
        const CRYPT_ATTRIBUTE *attr = pvStructInfo;
1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885

        if (!attr->pszObjId)
            SetLastError(E_INVALIDARG);
        else
        {
            struct AsnEncodeSequenceItem items[2] = {
             { attr->pszObjId, CRYPT_AsnEncodeOid, 0 },
             { &attr->cValue, CRYPT_DEREncodeSet, 0 },
            };

            ret = CRYPT_AsnEncodeSequence(dwCertEncodingType, items,
1886
             ARRAY_SIZE(items), dwFlags, pEncodePara, pbEncoded,
1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897
             pcbEncoded);
        }
    }
    __EXCEPT_PAGE_FAULT
    {
        SetLastError(STATUS_ACCESS_VIOLATION);
    }
    __ENDTRY
    return ret;
}

1898 1899 1900 1901 1902 1903 1904 1905
static BOOL WINAPI CRYPT_AsnEncodePKCSAttributes(DWORD dwCertEncodingType,
 LPCSTR lpszStructType, const void *pvStructInfo, DWORD dwFlags,
 PCRYPT_ENCODE_PARA pEncodePara, BYTE *pbEncoded, DWORD *pcbEncoded)
{
    BOOL ret = FALSE;

    __TRY
    {
1906
        const CRYPT_ATTRIBUTES *attributes = pvStructInfo;
1907 1908
        struct DERSetDescriptor desc = { attributes->cAttr, attributes->rgAttr,
         sizeof(CRYPT_ATTRIBUTE), 0, CRYPT_AsnEncodePKCSAttribute };
1909

1910 1911
        ret = CRYPT_DEREncodeItemsAsSet(X509_ASN_ENCODING, lpszStructType,
         &desc, dwFlags, pEncodePara, pbEncoded, pcbEncoded);
1912 1913 1914 1915 1916 1917 1918 1919 1920
    }
    __EXCEPT_PAGE_FAULT
    {
        SetLastError(STATUS_ACCESS_VIOLATION);
    }
    __ENDTRY
    return ret;
}

1921 1922 1923 1924 1925
/* Like CRYPT_AsnEncodePKCSContentInfo, but allows the OID to be NULL */
static BOOL WINAPI CRYPT_AsnEncodePKCSContentInfoInternal(
 DWORD dwCertEncodingType, LPCSTR lpszStructType, const void *pvStructInfo,
 DWORD dwFlags, PCRYPT_ENCODE_PARA pEncodePara, BYTE *pbEncoded,
 DWORD *pcbEncoded)
1926
{
1927
    const CRYPT_CONTENT_INFO *info = pvStructInfo;
1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947
    struct AsnEncodeSequenceItem items[2] = {
     { info->pszObjId, CRYPT_AsnEncodeOid, 0 },
     { NULL, NULL, 0 },
    };
    struct AsnConstructedItem constructed = { 0 };
    DWORD cItem = 1;

    if (info->Content.cbData)
    {
        constructed.tag = 0;
        constructed.pvStructInfo = &info->Content;
        constructed.encodeFunc = CRYPT_CopyEncodedBlob;
        items[cItem].pvStructInfo = &constructed;
        items[cItem].encodeFunc = CRYPT_AsnEncodeConstructed;
        cItem++;
    }
    return CRYPT_AsnEncodeSequence(dwCertEncodingType, items,
     cItem, dwFlags, pEncodePara, pbEncoded, pcbEncoded);
}

1948
BOOL CRYPT_AsnEncodePKCSDigestedData(const CRYPT_DIGESTED_DATA *digestedData,
1949 1950 1951 1952 1953 1954 1955 1956 1957 1958
 void *pvData, DWORD *pcbData)
{
    struct AsnEncodeSequenceItem items[] = {
     { &digestedData->version, CRYPT_AsnEncodeInt, 0 },
     { &digestedData->DigestAlgorithm, CRYPT_AsnEncodeAlgorithmIdWithNullParams,
       0 },
     { &digestedData->ContentInfo, CRYPT_AsnEncodePKCSContentInfoInternal, 0 },
     { &digestedData->hash, CRYPT_AsnEncodeOctets, 0 },
    };

1959
    return CRYPT_AsnEncodeSequence(X509_ASN_ENCODING, items, ARRAY_SIZE(items), 0, NULL, pvData, pcbData);
1960 1961
}

1962 1963 1964 1965 1966 1967 1968 1969
static BOOL WINAPI CRYPT_AsnEncodePKCSContentInfo(DWORD dwCertEncodingType,
 LPCSTR lpszStructType, const void *pvStructInfo, DWORD dwFlags,
 PCRYPT_ENCODE_PARA pEncodePara, BYTE *pbEncoded, DWORD *pcbEncoded)
{
    BOOL ret = FALSE;

    __TRY
    {
1970
        const CRYPT_CONTENT_INFO *info = pvStructInfo;
1971 1972 1973 1974

        if (!info->pszObjId)
            SetLastError(E_INVALIDARG);
        else
1975 1976 1977
            ret = CRYPT_AsnEncodePKCSContentInfoInternal(dwCertEncodingType,
             lpszStructType, pvStructInfo, dwFlags, pEncodePara, pbEncoded,
             pcbEncoded);
1978 1979 1980 1981 1982 1983 1984 1985 1986
    }
    __EXCEPT_PAGE_FAULT
    {
        SetLastError(STATUS_ACCESS_VIOLATION);
    }
    __ENDTRY
    return ret;
}

1987
static BOOL CRYPT_AsnEncodeUnicodeStringCoerce(const CERT_NAME_VALUE *value,
1988
 BYTE tag, DWORD dwFlags, const CRYPT_ENCODE_PARA *pEncodePara, BYTE *pbEncoded,
1989 1990 1991 1992 1993 1994
 DWORD *pcbEncoded)
{
    BOOL ret = TRUE;
    LPCWSTR str = (LPCWSTR)value->Value.pbData;
    DWORD bytesNeeded, lenBytes, encodedLen;

1995 1996 1997
    if (value->Value.cbData)
        encodedLen = value->Value.cbData / sizeof(WCHAR);
    else if (str)
1998
        encodedLen = lstrlenW(str);
1999 2000
    else
        encodedLen = 0;
2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024
    CRYPT_EncodeLen(encodedLen, NULL, &lenBytes);
    bytesNeeded = 1 + lenBytes + encodedLen;
    if (!pbEncoded)
        *pcbEncoded = bytesNeeded;
    else
    {
        if ((ret = CRYPT_EncodeEnsureSpace(dwFlags, pEncodePara,
         pbEncoded, pcbEncoded, bytesNeeded)))
        {
            DWORD i;

            if (dwFlags & CRYPT_ENCODE_ALLOC_FLAG)
                pbEncoded = *(BYTE **)pbEncoded;
            *pbEncoded++ = tag;
            CRYPT_EncodeLen(encodedLen, pbEncoded, &lenBytes);
            pbEncoded += lenBytes;
            for (i = 0; i < encodedLen; i++)
                *pbEncoded++ = (BYTE)str[i];
        }
    }
    return ret;
}

static BOOL CRYPT_AsnEncodeNumericString(const CERT_NAME_VALUE *value,
2025
 DWORD dwFlags, const CRYPT_ENCODE_PARA *pEncodePara, BYTE *pbEncoded,
2026 2027 2028 2029 2030 2031
 DWORD *pcbEncoded)
{
    BOOL ret = TRUE;
    LPCWSTR str = (LPCWSTR)value->Value.pbData;
    DWORD bytesNeeded, lenBytes, encodedLen;

2032 2033 2034
    if (value->Value.cbData)
        encodedLen = value->Value.cbData / sizeof(WCHAR);
    else if (str)
2035
        encodedLen = lstrlenW(str);
2036 2037
    else
        encodedLen = 0;
2038 2039 2040 2041 2042 2043 2044 2045 2046 2047
    CRYPT_EncodeLen(encodedLen, NULL, &lenBytes);
    bytesNeeded = 1 + lenBytes + encodedLen;
    if (!pbEncoded)
        *pcbEncoded = bytesNeeded;
    else
    {
        if ((ret = CRYPT_EncodeEnsureSpace(dwFlags, pEncodePara,
         pbEncoded, pcbEncoded, bytesNeeded)))
        {
            DWORD i;
2048
            BYTE *ptr;
2049 2050

            if (dwFlags & CRYPT_ENCODE_ALLOC_FLAG)
2051 2052 2053 2054 2055 2056
                ptr = *(BYTE **)pbEncoded;
            else
                ptr = pbEncoded;
            *ptr++ = ASN_NUMERICSTRING;
            CRYPT_EncodeLen(encodedLen, ptr, &lenBytes);
            ptr += lenBytes;
2057 2058
            for (i = 0; ret && i < encodedLen; i++)
            {
2059
                if ('0' <= str[i] && str[i] <= '9')
2060
                    *ptr++ = (BYTE)str[i];
2061 2062 2063 2064 2065 2066 2067
                else
                {
                    *pcbEncoded = i;
                    SetLastError(CRYPT_E_INVALID_NUMERIC_STRING);
                    ret = FALSE;
                }
            }
2068
            if (!ret && (dwFlags & CRYPT_ENCODE_ALLOC_FLAG))
2069
                CRYPT_FreeSpace(pEncodePara, *(BYTE **)pbEncoded);
2070 2071 2072 2073 2074
        }
    }
    return ret;
}

2075
static inline BOOL isprintableW(WCHAR wc)
2076
{
2077
    return wc && wcschr( L"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789 '()+,-./:=?", wc );
2078 2079 2080
}

static BOOL CRYPT_AsnEncodePrintableString(const CERT_NAME_VALUE *value,
2081
 DWORD dwFlags, const CRYPT_ENCODE_PARA *pEncodePara, BYTE *pbEncoded,
2082 2083 2084 2085 2086 2087
 DWORD *pcbEncoded)
{
    BOOL ret = TRUE;
    LPCWSTR str = (LPCWSTR)value->Value.pbData;
    DWORD bytesNeeded, lenBytes, encodedLen;

2088 2089 2090
    if (value->Value.cbData)
        encodedLen = value->Value.cbData / sizeof(WCHAR);
    else if (str)
2091
        encodedLen = lstrlenW(str);
2092 2093
    else
        encodedLen = 0;
2094 2095 2096 2097 2098 2099 2100 2101 2102 2103
    CRYPT_EncodeLen(encodedLen, NULL, &lenBytes);
    bytesNeeded = 1 + lenBytes + encodedLen;
    if (!pbEncoded)
        *pcbEncoded = bytesNeeded;
    else
    {
        if ((ret = CRYPT_EncodeEnsureSpace(dwFlags, pEncodePara,
         pbEncoded, pcbEncoded, bytesNeeded)))
        {
            DWORD i;
2104
            BYTE *ptr;
2105 2106

            if (dwFlags & CRYPT_ENCODE_ALLOC_FLAG)
2107 2108 2109 2110 2111 2112
                ptr = *(BYTE **)pbEncoded;
            else
                ptr = pbEncoded;
            *ptr++ = ASN_PRINTABLESTRING;
            CRYPT_EncodeLen(encodedLen, ptr, &lenBytes);
            ptr += lenBytes;
2113 2114 2115
            for (i = 0; ret && i < encodedLen; i++)
            {
                if (isprintableW(str[i]))
2116
                    *ptr++ = (BYTE)str[i];
2117 2118 2119 2120 2121 2122 2123
                else
                {
                    *pcbEncoded = i;
                    SetLastError(CRYPT_E_INVALID_PRINTABLE_STRING);
                    ret = FALSE;
                }
            }
2124
            if (!ret && (dwFlags & CRYPT_ENCODE_ALLOC_FLAG))
2125
                CRYPT_FreeSpace(pEncodePara, *(BYTE **)pbEncoded);
2126 2127 2128 2129 2130 2131
        }
    }
    return ret;
}

static BOOL CRYPT_AsnEncodeIA5String(const CERT_NAME_VALUE *value,
2132
 DWORD dwFlags, const CRYPT_ENCODE_PARA *pEncodePara, BYTE *pbEncoded,
2133 2134 2135 2136 2137 2138
 DWORD *pcbEncoded)
{
    BOOL ret = TRUE;
    LPCWSTR str = (LPCWSTR)value->Value.pbData;
    DWORD bytesNeeded, lenBytes, encodedLen;

2139 2140 2141
    if (value->Value.cbData)
        encodedLen = value->Value.cbData / sizeof(WCHAR);
    else if (str)
2142
        encodedLen = lstrlenW(str);
2143 2144
    else
        encodedLen = 0;
2145 2146 2147 2148 2149 2150 2151 2152 2153 2154
    CRYPT_EncodeLen(encodedLen, NULL, &lenBytes);
    bytesNeeded = 1 + lenBytes + encodedLen;
    if (!pbEncoded)
        *pcbEncoded = bytesNeeded;
    else
    {
        if ((ret = CRYPT_EncodeEnsureSpace(dwFlags, pEncodePara,
         pbEncoded, pcbEncoded, bytesNeeded)))
        {
            DWORD i;
2155
            BYTE *ptr;
2156 2157

            if (dwFlags & CRYPT_ENCODE_ALLOC_FLAG)
2158 2159 2160 2161 2162 2163
                ptr = *(BYTE **)pbEncoded;
            else
                ptr = pbEncoded;
            *ptr++ = ASN_IA5STRING;
            CRYPT_EncodeLen(encodedLen, ptr, &lenBytes);
            ptr += lenBytes;
2164 2165 2166
            for (i = 0; ret && i < encodedLen; i++)
            {
                if (str[i] <= 0x7f)
2167
                    *ptr++ = (BYTE)str[i];
2168 2169 2170 2171 2172 2173 2174
                else
                {
                    *pcbEncoded = i;
                    SetLastError(CRYPT_E_INVALID_IA5_STRING);
                    ret = FALSE;
                }
            }
2175
            if (!ret && (dwFlags & CRYPT_ENCODE_ALLOC_FLAG))
2176
                CRYPT_FreeSpace(pEncodePara, *(BYTE **)pbEncoded);
2177 2178 2179 2180 2181 2182
        }
    }
    return ret;
}

static BOOL CRYPT_AsnEncodeUniversalString(const CERT_NAME_VALUE *value,
2183
 DWORD dwFlags, const CRYPT_ENCODE_PARA *pEncodePara, BYTE *pbEncoded,
2184 2185 2186 2187 2188 2189 2190
 DWORD *pcbEncoded)
{
    BOOL ret = TRUE;
    LPCWSTR str = (LPCWSTR)value->Value.pbData;
    DWORD bytesNeeded, lenBytes, strLen;

    /* FIXME: doesn't handle composite characters */
2191 2192 2193
    if (value->Value.cbData)
        strLen = value->Value.cbData / sizeof(WCHAR);
    else if (str)
2194
        strLen = lstrlenW(str);
2195 2196
    else
        strLen = 0;
2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232
    CRYPT_EncodeLen(strLen * 4, NULL, &lenBytes);
    bytesNeeded = 1 + lenBytes + strLen * 4;
    if (!pbEncoded)
        *pcbEncoded = bytesNeeded;
    else
    {
        if ((ret = CRYPT_EncodeEnsureSpace(dwFlags, pEncodePara,
         pbEncoded, pcbEncoded, bytesNeeded)))
        {
            DWORD i;

            if (dwFlags & CRYPT_ENCODE_ALLOC_FLAG)
                pbEncoded = *(BYTE **)pbEncoded;
            *pbEncoded++ = ASN_UNIVERSALSTRING;
            CRYPT_EncodeLen(strLen * 4, pbEncoded, &lenBytes);
            pbEncoded += lenBytes;
            for (i = 0; i < strLen; i++)
            {
                *pbEncoded++ = 0;
                *pbEncoded++ = 0;
                *pbEncoded++ = (BYTE)((str[i] & 0xff00) >> 8);
                *pbEncoded++ = (BYTE)(str[i] & 0x00ff);
            }
        }
    }
    return ret;
}

static BOOL WINAPI CRYPT_AsnEncodeUnicodeNameValue(DWORD dwCertEncodingType,
 LPCSTR lpszStructType, const void *pvStructInfo, DWORD dwFlags,
 PCRYPT_ENCODE_PARA pEncodePara, BYTE *pbEncoded, DWORD *pcbEncoded)
{
    BOOL ret = FALSE;

    __TRY
    {
2233
        const CERT_NAME_VALUE *value = pvStructInfo;
2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297

        switch (value->dwValueType)
        {
        case CERT_RDN_ANY_TYPE:
        case CERT_RDN_ENCODED_BLOB:
        case CERT_RDN_OCTET_STRING:
            SetLastError(CRYPT_E_NOT_CHAR_STRING);
            break;
        case CERT_RDN_NUMERIC_STRING:
            ret = CRYPT_AsnEncodeNumericString(value, dwFlags, pEncodePara,
             pbEncoded, pcbEncoded);
            break;
        case CERT_RDN_PRINTABLE_STRING:
            ret = CRYPT_AsnEncodePrintableString(value, dwFlags, pEncodePara,
             pbEncoded, pcbEncoded);
            break;
        case CERT_RDN_TELETEX_STRING:
            ret = CRYPT_AsnEncodeUnicodeStringCoerce(value, ASN_T61STRING,
             dwFlags, pEncodePara, pbEncoded, pcbEncoded);
            break;
        case CERT_RDN_VIDEOTEX_STRING:
            ret = CRYPT_AsnEncodeUnicodeStringCoerce(value,
             ASN_VIDEOTEXSTRING, dwFlags, pEncodePara, pbEncoded, pcbEncoded);
            break;
        case CERT_RDN_IA5_STRING:
            ret = CRYPT_AsnEncodeIA5String(value, dwFlags, pEncodePara,
             pbEncoded, pcbEncoded);
            break;
        case CERT_RDN_GRAPHIC_STRING:
            ret = CRYPT_AsnEncodeUnicodeStringCoerce(value, ASN_GRAPHICSTRING,
             dwFlags, pEncodePara, pbEncoded, pcbEncoded);
            break;
        case CERT_RDN_VISIBLE_STRING:
            ret = CRYPT_AsnEncodeUnicodeStringCoerce(value, ASN_VISIBLESTRING,
             dwFlags, pEncodePara, pbEncoded, pcbEncoded);
            break;
        case CERT_RDN_GENERAL_STRING:
            ret = CRYPT_AsnEncodeUnicodeStringCoerce(value, ASN_GENERALSTRING,
             dwFlags, pEncodePara, pbEncoded, pcbEncoded);
            break;
        case CERT_RDN_UNIVERSAL_STRING:
            ret = CRYPT_AsnEncodeUniversalString(value, dwFlags, pEncodePara,
             pbEncoded, pcbEncoded);
            break;
        case CERT_RDN_BMP_STRING:
            ret = CRYPT_AsnEncodeBMPString(value, dwFlags, pEncodePara,
             pbEncoded, pcbEncoded);
            break;
        case CERT_RDN_UTF8_STRING:
            ret = CRYPT_AsnEncodeUTF8String(value, dwFlags, pEncodePara,
             pbEncoded, pcbEncoded);
            break;
        default:
            SetLastError(CRYPT_E_ASN1_CHOICE);
        }
    }
    __EXCEPT_PAGE_FAULT
    {
        SetLastError(STATUS_ACCESS_VIOLATION);
    }
    __ENDTRY
    return ret;
}

2298 2299 2300 2301 2302 2303
static BOOL WINAPI CRYPT_AsnEncodeName(DWORD dwCertEncodingType,
 LPCSTR lpszStructType, const void *pvStructInfo, DWORD dwFlags,
 PCRYPT_ENCODE_PARA pEncodePara, BYTE *pbEncoded, DWORD *pcbEncoded)
{
    BOOL ret;

2304
    __TRY
2305
    {
2306
        const CERT_NAME_INFO *info = pvStructInfo;
2307 2308
        DWORD bytesNeeded = 0, lenBytes, size, i;

2309
        TRACE("encoding name with %d RDNs\n", info->cRDN);
2310
        ret = TRUE;
2311 2312
        for (i = 0; ret && i < info->cRDN; i++)
        {
2313 2314
            ret = CRYPT_AsnEncodeRdn(dwCertEncodingType, &info->rgRDN[i],
             CRYPT_AsnEncodeNameValue, NULL, &size);
2315
            if (ret)
2316 2317 2318 2319 2320 2321 2322 2323 2324
                bytesNeeded += size;
        }
        CRYPT_EncodeLen(bytesNeeded, NULL, &lenBytes);
        bytesNeeded += 1 + lenBytes;
        if (ret)
        {
            if (!pbEncoded)
                *pcbEncoded = bytesNeeded;
            else
2325
            {
2326 2327 2328
                if ((ret = CRYPT_EncodeEnsureSpace(dwFlags, pEncodePara,
                 pbEncoded, pcbEncoded, bytesNeeded)))
                {
2329 2330
                    BYTE *out;

2331 2332
                    if (dwFlags & CRYPT_ENCODE_ALLOC_FLAG)
                        pbEncoded = *(BYTE **)pbEncoded;
2333 2334 2335 2336
                    out = pbEncoded;
                    *out++ = ASN_SEQUENCEOF;
                    CRYPT_EncodeLen(bytesNeeded - lenBytes - 1, out, &lenBytes);
                    out += lenBytes;
2337 2338 2339 2340
                    for (i = 0; ret && i < info->cRDN; i++)
                    {
                        size = bytesNeeded;
                        ret = CRYPT_AsnEncodeRdn(dwCertEncodingType,
2341
                         &info->rgRDN[i], CRYPT_AsnEncodeNameValue, out, &size);
2342 2343
                        if (ret)
                        {
2344
                            out += size;
2345 2346 2347
                            bytesNeeded -= size;
                        }
                    }
2348 2349
                    if (!ret && (dwFlags & CRYPT_ENCODE_ALLOC_FLAG))
                        CRYPT_FreeSpace(pEncodePara, pbEncoded);
2350
                }
2351 2352 2353
            }
        }
    }
2354
    __EXCEPT_PAGE_FAULT
2355 2356 2357 2358 2359
    {
        SetLastError(STATUS_ACCESS_VIOLATION);
        ret = FALSE;
    }
    __ENDTRY
2360 2361 2362
    return ret;
}

2363
static BOOL WINAPI CRYPT_AsnEncodeBool(DWORD dwCertEncodingType,
2364 2365 2366
 LPCSTR lpszStructType, const void *pvStructInfo, DWORD dwFlags,
 PCRYPT_ENCODE_PARA pEncodePara, BYTE *pbEncoded, DWORD *pcbEncoded)
{
2367
    BOOL val = *(const BOOL *)pvStructInfo, ret;
2368

2369
    TRACE("%d\n", val);
2370

2371 2372 2373
    if (!pbEncoded)
    {
        *pcbEncoded = 3;
2374
        ret = TRUE;
2375
    }
2376
    else if (*pcbEncoded < 3)
2377 2378 2379
    {
        *pcbEncoded = 3;
        SetLastError(ERROR_MORE_DATA);
2380
        ret = FALSE;
2381
    }
2382 2383 2384 2385 2386 2387 2388 2389
    else
    {
        *pcbEncoded = 3;
        *pbEncoded++ = ASN_BOOL;
        *pbEncoded++ = 1;
        *pbEncoded++ = val ? 0xff : 0;
        ret = TRUE;
    }
2390
    TRACE("returning %d (%08x)\n", ret, GetLastError());
2391
    return ret;
2392 2393
}

2394 2395 2396
static BOOL WINAPI CRYPT_AsnEncodeAltNameEntry(DWORD dwCertEncodingType,
 LPCSTR lpszStructType, const void *pvStructInfo, DWORD dwFlags,
 PCRYPT_ENCODE_PARA pEncodePara, BYTE *pbEncoded, DWORD *pcbEncoded)
2397
{
2398
    const CERT_ALT_NAME_ENTRY *entry = pvStructInfo;
2399 2400
    BOOL ret;
    DWORD dataLen;
2401
    BYTE tag;
2402 2403 2404 2405 2406 2407 2408

    ret = TRUE;
    switch (entry->dwAltNameChoice)
    {
    case CERT_ALT_NAME_RFC822_NAME:
    case CERT_ALT_NAME_DNS_NAME:
    case CERT_ALT_NAME_URL:
2409
        tag = ASN_CONTEXT | (entry->dwAltNameChoice - 1);
2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428
        if (entry->u.pwszURL)
        {
            DWORD i;

            /* Not + 1: don't encode the NULL-terminator */
            dataLen = lstrlenW(entry->u.pwszURL);
            for (i = 0; ret && i < dataLen; i++)
            {
                if (entry->u.pwszURL[i] > 0x7f)
                {
                    SetLastError(CRYPT_E_INVALID_IA5_STRING);
                    ret = FALSE;
                    *pcbEncoded = i;
                }
            }
        }
        else
            dataLen = 0;
        break;
2429 2430 2431 2432
    case CERT_ALT_NAME_DIRECTORY_NAME:
        tag = ASN_CONTEXT | ASN_CONSTRUCTOR | (entry->dwAltNameChoice - 1);
        dataLen = entry->u.DirectoryName.cbData;
        break;
2433
    case CERT_ALT_NAME_IP_ADDRESS:
2434
        tag = ASN_CONTEXT | (entry->dwAltNameChoice - 1);
2435 2436 2437
        dataLen = entry->u.IPAddress.cbData;
        break;
    case CERT_ALT_NAME_REGISTERED_ID:
2438 2439 2440 2441 2442 2443 2444 2445
    {
        struct AsnEncodeTagSwappedItem swapped =
         { ASN_CONTEXT | (entry->dwAltNameChoice - 1), entry->u.pszRegisteredID,
           CRYPT_AsnEncodeOid };

        return CRYPT_AsnEncodeSwapTag(0, NULL, &swapped, 0, NULL, pbEncoded,
         pcbEncoded);
    }
2446
    case CERT_ALT_NAME_OTHER_NAME:
2447
        FIXME("name type %d unimplemented\n", entry->dwAltNameChoice);
2448 2449
        return FALSE;
    default:
2450
        SetLastError(E_INVALIDARG);
2451 2452 2453 2454 2455 2456 2457 2458 2459 2460 2461 2462 2463 2464 2465 2466 2467 2468
        return FALSE;
    }
    if (ret)
    {
        DWORD bytesNeeded, lenBytes;

        CRYPT_EncodeLen(dataLen, NULL, &lenBytes);
        bytesNeeded = 1 + dataLen + lenBytes;
        if (!pbEncoded)
            *pcbEncoded = bytesNeeded;
        else if (*pcbEncoded < bytesNeeded)
        {
            SetLastError(ERROR_MORE_DATA);
            *pcbEncoded = bytesNeeded;
            ret = FALSE;
        }
        else
        {
2469
            *pbEncoded++ = tag;
2470 2471 2472 2473 2474 2475 2476 2477 2478 2479 2480 2481 2482 2483
            CRYPT_EncodeLen(dataLen, pbEncoded, &lenBytes);
            pbEncoded += lenBytes;
            switch (entry->dwAltNameChoice)
            {
            case CERT_ALT_NAME_RFC822_NAME:
            case CERT_ALT_NAME_DNS_NAME:
            case CERT_ALT_NAME_URL:
            {
                DWORD i;

                for (i = 0; i < dataLen; i++)
                    *pbEncoded++ = (BYTE)entry->u.pwszURL[i];
                break;
            }
2484 2485 2486
            case CERT_ALT_NAME_DIRECTORY_NAME:
                memcpy(pbEncoded, entry->u.DirectoryName.pbData, dataLen);
                break;
2487 2488 2489 2490 2491 2492 2493 2494
            case CERT_ALT_NAME_IP_ADDRESS:
                memcpy(pbEncoded, entry->u.IPAddress.pbData, dataLen);
                break;
            }
            if (ret)
                *pcbEncoded = bytesNeeded;
        }
    }
2495
    TRACE("returning %d (%08x)\n", ret, GetLastError());
2496 2497 2498
    return ret;
}

2499 2500 2501 2502 2503 2504 2505 2506
static BOOL WINAPI CRYPT_AsnEncodeAuthorityKeyId(DWORD dwCertEncodingType,
 LPCSTR lpszStructType, const void *pvStructInfo, DWORD dwFlags,
 PCRYPT_ENCODE_PARA pEncodePara, BYTE *pbEncoded, DWORD *pcbEncoded)
{
    BOOL ret;

    __TRY
    {
2507
        const CERT_AUTHORITY_KEY_ID_INFO *info = pvStructInfo;
2508 2509 2510 2511 2512 2513 2514 2515 2516
        struct AsnEncodeSequenceItem items[3] = { { 0 } };
        struct AsnEncodeTagSwappedItem swapped[3] = { { 0 } };
        struct AsnConstructedItem constructed = { 0 };
        DWORD cItem = 0, cSwapped = 0;

        if (info->KeyId.cbData)
        {
            swapped[cSwapped].tag = ASN_CONTEXT | 0;
            swapped[cSwapped].pvStructInfo = &info->KeyId;
2517
            swapped[cSwapped].encodeFunc = CRYPT_AsnEncodeOctets;
2518 2519 2520 2521 2522 2523 2524 2525 2526 2527 2528 2529 2530 2531 2532 2533 2534 2535 2536 2537 2538 2539 2540 2541 2542 2543 2544 2545 2546 2547 2548 2549 2550 2551 2552 2553
            items[cItem].pvStructInfo = &swapped[cSwapped];
            items[cItem].encodeFunc = CRYPT_AsnEncodeSwapTag;
            cSwapped++;
            cItem++;
        }
        if (info->CertIssuer.cbData)
        {
            constructed.tag = 1;
            constructed.pvStructInfo = &info->CertIssuer;
            constructed.encodeFunc = CRYPT_CopyEncodedBlob;
            items[cItem].pvStructInfo = &constructed;
            items[cItem].encodeFunc = CRYPT_AsnEncodeConstructed;
            cItem++;
        }
        if (info->CertSerialNumber.cbData)
        {
            swapped[cSwapped].tag = ASN_CONTEXT | 2;
            swapped[cSwapped].pvStructInfo = &info->CertSerialNumber;
            swapped[cSwapped].encodeFunc = CRYPT_AsnEncodeInteger;
            items[cItem].pvStructInfo = &swapped[cSwapped];
            items[cItem].encodeFunc = CRYPT_AsnEncodeSwapTag;
            cSwapped++;
            cItem++;
        }
        ret = CRYPT_AsnEncodeSequence(X509_ASN_ENCODING, items, cItem, dwFlags,
         pEncodePara, pbEncoded, pcbEncoded);
    }
    __EXCEPT_PAGE_FAULT
    {
        SetLastError(STATUS_ACCESS_VIOLATION);
        ret = FALSE;
    }
    __ENDTRY
    return ret;
}

2554 2555 2556 2557 2558 2559 2560 2561
static BOOL WINAPI CRYPT_AsnEncodeAltName(DWORD dwCertEncodingType,
 LPCSTR lpszStructType, const void *pvStructInfo, DWORD dwFlags,
 PCRYPT_ENCODE_PARA pEncodePara, BYTE *pbEncoded, DWORD *pcbEncoded)
{
    BOOL ret;

    __TRY
    {
2562
        const CERT_ALT_NAME_INFO *info = pvStructInfo;
2563 2564 2565 2566 2567 2568 2569 2570 2571 2572
        DWORD bytesNeeded, dataLen, lenBytes, i;

        ret = TRUE;
        /* FIXME: should check that cAltEntry is not bigger than 0xff, since we
         * can't encode an erroneous entry index if it's bigger than this.
         */
        for (i = 0, dataLen = 0; ret && i < info->cAltEntry; i++)
        {
            DWORD len;

2573 2574
            ret = CRYPT_AsnEncodeAltNameEntry(dwCertEncodingType, NULL,
             &info->rgAltEntry[i], 0, NULL, NULL, &len);
2575 2576
            if (ret)
                dataLen += len;
2577 2578 2579 2580 2581 2582 2583 2584 2585
            else if (GetLastError() == CRYPT_E_INVALID_IA5_STRING)
            {
                /* CRYPT_AsnEncodeAltNameEntry encoded the index of
                 * the bad character, now set the index of the bad
                 * entry
                 */
                *pcbEncoded = (BYTE)i <<
                 CERT_ALT_NAME_ENTRY_ERR_INDEX_SHIFT | len;
            }
2586 2587 2588 2589 2590 2591 2592 2593 2594 2595 2596 2597 2598 2599 2600
        }
        if (ret)
        {
            CRYPT_EncodeLen(dataLen, NULL, &lenBytes);
            bytesNeeded = 1 + lenBytes + dataLen;
            if (!pbEncoded)
            {
                *pcbEncoded = bytesNeeded;
                ret = TRUE;
            }
            else
            {
                if ((ret = CRYPT_EncodeEnsureSpace(dwFlags, pEncodePara,
                 pbEncoded, pcbEncoded, bytesNeeded)))
                {
2601 2602
                    BYTE *out;

2603 2604
                    if (dwFlags & CRYPT_ENCODE_ALLOC_FLAG)
                        pbEncoded = *(BYTE **)pbEncoded;
2605 2606 2607 2608
                    out = pbEncoded;
                    *out++ = ASN_SEQUENCEOF;
                    CRYPT_EncodeLen(dataLen, out, &lenBytes);
                    out += lenBytes;
2609 2610 2611 2612
                    for (i = 0; ret && i < info->cAltEntry; i++)
                    {
                        DWORD len = dataLen;

2613
                        ret = CRYPT_AsnEncodeAltNameEntry(dwCertEncodingType,
2614
                         NULL, &info->rgAltEntry[i], 0, NULL, out, &len);
2615 2616
                        if (ret)
                        {
2617
                            out += len;
2618 2619 2620
                            dataLen -= len;
                        }
                    }
2621 2622
                    if (!ret && (dwFlags & CRYPT_ENCODE_ALLOC_FLAG))
                        CRYPT_FreeSpace(pEncodePara, pbEncoded);
2623 2624 2625 2626
                }
            }
        }
    }
2627
    __EXCEPT_PAGE_FAULT
2628 2629 2630 2631 2632 2633 2634 2635
    {
        SetLastError(STATUS_ACCESS_VIOLATION);
        ret = FALSE;
    }
    __ENDTRY
    return ret;
}

2636 2637 2638 2639 2640 2641 2642 2643
static BOOL WINAPI CRYPT_AsnEncodeAuthorityKeyId2(DWORD dwCertEncodingType,
 LPCSTR lpszStructType, const void *pvStructInfo, DWORD dwFlags,
 PCRYPT_ENCODE_PARA pEncodePara, BYTE *pbEncoded, DWORD *pcbEncoded)
{
    BOOL ret;

    __TRY
    {
2644
        const CERT_AUTHORITY_KEY_ID2_INFO *info = pvStructInfo;
2645 2646 2647 2648 2649 2650 2651 2652
        struct AsnEncodeSequenceItem items[3] = { { 0 } };
        struct AsnEncodeTagSwappedItem swapped[3] = { { 0 } };
        DWORD cItem = 0, cSwapped = 0;

        if (info->KeyId.cbData)
        {
            swapped[cSwapped].tag = ASN_CONTEXT | 0;
            swapped[cSwapped].pvStructInfo = &info->KeyId;
2653
            swapped[cSwapped].encodeFunc = CRYPT_AsnEncodeOctets;
2654 2655 2656 2657 2658 2659 2660 2661 2662 2663 2664 2665 2666 2667 2668 2669 2670 2671 2672 2673 2674 2675 2676 2677 2678 2679 2680 2681 2682 2683 2684 2685 2686 2687 2688 2689 2690
            items[cItem].pvStructInfo = &swapped[cSwapped];
            items[cItem].encodeFunc = CRYPT_AsnEncodeSwapTag;
            cSwapped++;
            cItem++;
        }
        if (info->AuthorityCertIssuer.cAltEntry)
        {
            swapped[cSwapped].tag = ASN_CONTEXT | ASN_CONSTRUCTOR | 1;
            swapped[cSwapped].pvStructInfo = &info->AuthorityCertIssuer;
            swapped[cSwapped].encodeFunc = CRYPT_AsnEncodeAltName;
            items[cItem].pvStructInfo = &swapped[cSwapped];
            items[cItem].encodeFunc = CRYPT_AsnEncodeSwapTag;
            cSwapped++;
            cItem++;
        }
        if (info->AuthorityCertSerialNumber.cbData)
        {
            swapped[cSwapped].tag = ASN_CONTEXT | 2;
            swapped[cSwapped].pvStructInfo = &info->AuthorityCertSerialNumber;
            swapped[cSwapped].encodeFunc = CRYPT_AsnEncodeInteger;
            items[cItem].pvStructInfo = &swapped[cSwapped];
            items[cItem].encodeFunc = CRYPT_AsnEncodeSwapTag;
            cSwapped++;
            cItem++;
        }
        ret = CRYPT_AsnEncodeSequence(X509_ASN_ENCODING, items, cItem, dwFlags,
         pEncodePara, pbEncoded, pcbEncoded);
    }
    __EXCEPT_PAGE_FAULT
    {
        SetLastError(STATUS_ACCESS_VIOLATION);
        ret = FALSE;
    }
    __ENDTRY
    return ret;
}

2691
static BOOL CRYPT_AsnEncodeAccessDescription(
2692 2693 2694 2695 2696 2697 2698 2699 2700 2701 2702 2703
 const CERT_ACCESS_DESCRIPTION *descr, BYTE *pbEncoded, DWORD *pcbEncoded)
{
    struct AsnEncodeSequenceItem items[] = {
     { descr->pszAccessMethod, CRYPT_AsnEncodeOid, 0 },
     { &descr->AccessLocation, CRYPT_AsnEncodeAltNameEntry, 0 },
    };

    if (!descr->pszAccessMethod)
    {
        SetLastError(E_INVALIDARG);
        return FALSE;
    }
2704
    return CRYPT_AsnEncodeSequence(X509_ASN_ENCODING, items, ARRAY_SIZE(items), 0, NULL, pbEncoded, pcbEncoded);
2705 2706 2707 2708 2709 2710 2711 2712 2713 2714 2715
}

static BOOL WINAPI CRYPT_AsnEncodeAuthorityInfoAccess(DWORD dwCertEncodingType,
 LPCSTR lpszStructType, const void *pvStructInfo, DWORD dwFlags,
 PCRYPT_ENCODE_PARA pEncodePara, BYTE *pbEncoded, DWORD *pcbEncoded)
{
    BOOL ret;

    __TRY
    {
        DWORD bytesNeeded, dataLen, lenBytes, i;
2716
        const CERT_AUTHORITY_INFO_ACCESS *info = pvStructInfo;
2717 2718 2719 2720 2721 2722 2723 2724 2725 2726 2727 2728 2729 2730 2731 2732 2733 2734 2735 2736 2737 2738

        ret = TRUE;
        for (i = 0, dataLen = 0; ret && i < info->cAccDescr; i++)
        {
            DWORD size;

            ret = CRYPT_AsnEncodeAccessDescription(&info->rgAccDescr[i], NULL,
             &size);
            if (ret)
                dataLen += size;
        }
        if (ret)
        {
            CRYPT_EncodeLen(dataLen, NULL, &lenBytes);
            bytesNeeded = 1 + lenBytes + dataLen;
            if (!pbEncoded)
                *pcbEncoded = bytesNeeded;
            else
            {
                if ((ret = CRYPT_EncodeEnsureSpace(dwFlags, pEncodePara,
                 pbEncoded, pcbEncoded, bytesNeeded)))
                {
2739 2740
                    BYTE *out;

2741 2742
                    if (dwFlags & CRYPT_ENCODE_ALLOC_FLAG)
                        pbEncoded = *(BYTE **)pbEncoded;
2743 2744 2745 2746
                    out = pbEncoded;
                    *out++ = ASN_SEQUENCEOF;
                    CRYPT_EncodeLen(dataLen, out, &lenBytes);
                    out += lenBytes;
2747 2748 2749 2750 2751
                    for (i = 0; i < info->cAccDescr; i++)
                    {
                        DWORD size = dataLen;

                        ret = CRYPT_AsnEncodeAccessDescription(
2752 2753
                         &info->rgAccDescr[i], out, &size);
                        out += size;
2754 2755
                        dataLen -= size;
                    }
2756 2757
                    if (!ret && (dwFlags & CRYPT_ENCODE_ALLOC_FLAG))
                        CRYPT_FreeSpace(pEncodePara, pbEncoded);
2758 2759 2760 2761 2762 2763 2764 2765 2766 2767 2768 2769 2770
                }
            }
        }
    }
    __EXCEPT_PAGE_FAULT
    {
        SetLastError(STATUS_ACCESS_VIOLATION);
        ret = FALSE;
    }
    __ENDTRY
    return ret;
}

2771 2772 2773 2774 2775 2776 2777 2778
static BOOL WINAPI CRYPT_AsnEncodeBasicConstraints(DWORD dwCertEncodingType,
 LPCSTR lpszStructType, const void *pvStructInfo, DWORD dwFlags,
 PCRYPT_ENCODE_PARA pEncodePara, BYTE *pbEncoded, DWORD *pcbEncoded)
{
    BOOL ret;

    __TRY
    {
2779
        const CERT_BASIC_CONSTRAINTS_INFO *info = pvStructInfo;
2780 2781 2782 2783 2784 2785 2786 2787 2788 2789 2790 2791 2792 2793 2794 2795 2796 2797 2798 2799 2800 2801 2802 2803 2804 2805 2806 2807 2808 2809
        struct AsnEncodeSequenceItem items[3] = {
         { &info->SubjectType, CRYPT_AsnEncodeBits, 0 },
         { 0 }
        };
        DWORD cItem = 1;

        if (info->fPathLenConstraint)
        {
            items[cItem].pvStructInfo = &info->dwPathLenConstraint;
            items[cItem].encodeFunc = CRYPT_AsnEncodeInt;
            cItem++;
        }
        if (info->cSubtreesConstraint)
        {
            items[cItem].pvStructInfo = &info->cSubtreesConstraint;
            items[cItem].encodeFunc = CRYPT_AsnEncodeSequenceOfAny;
            cItem++;
        }
        ret = CRYPT_AsnEncodeSequence(dwCertEncodingType, items, cItem,
         dwFlags, pEncodePara, pbEncoded, pcbEncoded);
    }
    __EXCEPT_PAGE_FAULT
    {
        SetLastError(STATUS_ACCESS_VIOLATION);
        ret = FALSE;
    }
    __ENDTRY
    return ret;
}

2810 2811 2812 2813
static BOOL WINAPI CRYPT_AsnEncodeBasicConstraints2(DWORD dwCertEncodingType,
 LPCSTR lpszStructType, const void *pvStructInfo, DWORD dwFlags,
 PCRYPT_ENCODE_PARA pEncodePara, BYTE *pbEncoded, DWORD *pcbEncoded)
{
2814
    BOOL ret;
2815

2816
    __TRY
2817
    {
2818
        const CERT_BASIC_CONSTRAINTS2_INFO *info = pvStructInfo;
2819 2820
        struct AsnEncodeSequenceItem items[2] = { { 0 } };
        DWORD cItem = 0;
2821 2822 2823

        if (info->fCA)
        {
2824 2825 2826
            items[cItem].pvStructInfo = &info->fCA;
            items[cItem].encodeFunc = CRYPT_AsnEncodeBool;
            cItem++;
2827 2828 2829
        }
        if (info->fPathLenConstraint)
        {
2830 2831 2832
            items[cItem].pvStructInfo = &info->dwPathLenConstraint;
            items[cItem].encodeFunc = CRYPT_AsnEncodeInt;
            cItem++;
2833
        }
2834 2835
        ret = CRYPT_AsnEncodeSequence(dwCertEncodingType, items, cItem,
         dwFlags, pEncodePara, pbEncoded, pcbEncoded);
2836
    }
2837
    __EXCEPT_PAGE_FAULT
2838
    {
2839 2840
        SetLastError(STATUS_ACCESS_VIOLATION);
        ret = FALSE;
2841
    }
2842
    __ENDTRY
2843 2844 2845
    return ret;
}

2846 2847 2848 2849
static BOOL WINAPI CRYPT_AsnEncodeCertPolicyQualifiers(DWORD dwCertEncodingType,
 LPCSTR lpszStructType, const void *pvStructInfo, DWORD dwFlags,
 PCRYPT_ENCODE_PARA pEncodePara, BYTE *pbEncoded, DWORD *pcbEncoded)
{
2850
    const CERT_POLICY_INFO *info = pvStructInfo;
2851 2852
    BOOL ret;

2853
    if (!info->cPolicyQualifier)
2854 2855 2856 2857 2858 2859 2860 2861 2862 2863 2864 2865 2866
    {
        *pcbEncoded = 0;
        ret = TRUE;
    }
    else
    {
        struct AsnEncodeSequenceItem items[2] = {
         { NULL, CRYPT_AsnEncodeOid, 0 },
         { NULL, CRYPT_CopyEncodedBlob, 0 },
        };
        DWORD bytesNeeded = 0, lenBytes, size, i;

        ret = TRUE;
2867
        for (i = 0; ret && i < info->cPolicyQualifier; i++)
2868
        {
2869 2870 2871
            items[0].pvStructInfo =
             info->rgPolicyQualifier[i].pszPolicyQualifierId;
            items[1].pvStructInfo = &info->rgPolicyQualifier[i].Qualifier;
2872
            ret = CRYPT_AsnEncodeSequence(dwCertEncodingType, items, ARRAY_SIZE(items),
2873 2874 2875 2876 2877 2878 2879 2880 2881 2882 2883 2884 2885 2886 2887
             dwFlags & ~CRYPT_ENCODE_ALLOC_FLAG, NULL, NULL, &size);
            if (ret)
                bytesNeeded += size;
        }
        CRYPT_EncodeLen(bytesNeeded, NULL, &lenBytes);
        bytesNeeded += 1 + lenBytes;
        if (ret)
        {
            if (!pbEncoded)
                *pcbEncoded = bytesNeeded;
            else
            {
                if ((ret = CRYPT_EncodeEnsureSpace(dwFlags, pEncodePara,
                 pbEncoded, pcbEncoded, bytesNeeded)))
                {
2888 2889
                    BYTE *out;

2890 2891
                    if (dwFlags & CRYPT_ENCODE_ALLOC_FLAG)
                        pbEncoded = *(BYTE **)pbEncoded;
2892 2893 2894 2895
                    out = pbEncoded;
                    *out++ = ASN_SEQUENCEOF;
                    CRYPT_EncodeLen(bytesNeeded - lenBytes - 1, out, &lenBytes);
                    out += lenBytes;
2896
                    for (i = 0; ret && i < info->cPolicyQualifier; i++)
2897 2898
                    {
                        items[0].pvStructInfo =
2899
                         info->rgPolicyQualifier[i].pszPolicyQualifierId;
2900
                        items[1].pvStructInfo =
2901
                         &info->rgPolicyQualifier[i].Qualifier;
2902
                        size = bytesNeeded;
2903
                        ret = CRYPT_AsnEncodeSequence(dwCertEncodingType, items, ARRAY_SIZE(items),
2904
                         dwFlags & ~CRYPT_ENCODE_ALLOC_FLAG, NULL, out, &size);
2905 2906
                        if (ret)
                        {
2907
                            out += size;
2908 2909 2910
                            bytesNeeded -= size;
                        }
                    }
2911 2912
                    if (!ret && (dwFlags & CRYPT_ENCODE_ALLOC_FLAG))
                        CRYPT_FreeSpace(pEncodePara, pbEncoded);
2913 2914 2915 2916 2917 2918 2919 2920 2921 2922 2923 2924 2925
                }
            }
        }
    }
    return ret;
}

static BOOL CRYPT_AsnEncodeCertPolicy(DWORD dwCertEncodingType,
 const CERT_POLICY_INFO *info, DWORD dwFlags, BYTE *pbEncoded,
 DWORD *pcbEncoded)
{
    struct AsnEncodeSequenceItem items[2] = {
     { info->pszPolicyIdentifier, CRYPT_AsnEncodeOid, 0 },
2926
     { info,                      CRYPT_AsnEncodeCertPolicyQualifiers, 0 },
2927 2928 2929 2930 2931 2932 2933 2934
    };
    BOOL ret;

    if (!info->pszPolicyIdentifier)
    {
        SetLastError(E_INVALIDARG);
        return FALSE;
    }
2935
    ret = CRYPT_AsnEncodeSequence(dwCertEncodingType, items, ARRAY_SIZE(items), dwFlags, NULL, pbEncoded, pcbEncoded);
2936 2937 2938 2939 2940 2941 2942 2943 2944 2945 2946 2947 2948 2949 2950 2951 2952 2953 2954 2955 2956 2957 2958 2959 2960 2961 2962 2963 2964 2965 2966 2967 2968 2969
    return ret;
}

static BOOL WINAPI CRYPT_AsnEncodeCertPolicies(DWORD dwCertEncodingType,
 LPCSTR lpszStructType, const void *pvStructInfo, DWORD dwFlags,
 PCRYPT_ENCODE_PARA pEncodePara, BYTE *pbEncoded, DWORD *pcbEncoded)
{
    BOOL ret = FALSE;

    __TRY
    {
        const CERT_POLICIES_INFO *info = pvStructInfo;
        DWORD bytesNeeded = 0, lenBytes, size, i;

        ret = TRUE;
        for (i = 0; ret && i < info->cPolicyInfo; i++)
        {
            ret = CRYPT_AsnEncodeCertPolicy(dwCertEncodingType,
             &info->rgPolicyInfo[i], dwFlags & ~CRYPT_ENCODE_ALLOC_FLAG, NULL,
             &size);
            if (ret)
                bytesNeeded += size;
        }
        CRYPT_EncodeLen(bytesNeeded, NULL, &lenBytes);
        bytesNeeded += 1 + lenBytes;
        if (ret)
        {
            if (!pbEncoded)
                *pcbEncoded = bytesNeeded;
            else
            {
                if ((ret = CRYPT_EncodeEnsureSpace(dwFlags, pEncodePara,
                 pbEncoded, pcbEncoded, bytesNeeded)))
                {
2970 2971
                    BYTE *out;

2972 2973
                    if (dwFlags & CRYPT_ENCODE_ALLOC_FLAG)
                        pbEncoded = *(BYTE **)pbEncoded;
2974 2975 2976 2977
                    out = pbEncoded;
                    *out++ = ASN_SEQUENCEOF;
                    CRYPT_EncodeLen(bytesNeeded - lenBytes - 1, out, &lenBytes);
                    out += lenBytes;
2978 2979 2980 2981 2982
                    for (i = 0; ret && i < info->cPolicyInfo; i++)
                    {
                        size = bytesNeeded;
                        ret = CRYPT_AsnEncodeCertPolicy(dwCertEncodingType,
                         &info->rgPolicyInfo[i],
2983
                         dwFlags & ~CRYPT_ENCODE_ALLOC_FLAG, out, &size);
2984 2985
                        if (ret)
                        {
2986
                            out += size;
2987 2988 2989
                            bytesNeeded -= size;
                        }
                    }
2990 2991
                    if (!ret && (dwFlags & CRYPT_ENCODE_ALLOC_FLAG))
                        CRYPT_FreeSpace(pEncodePara, pbEncoded);
2992 2993 2994 2995 2996 2997 2998 2999 3000 3001 3002 3003
                }
            }
        }
    }
    __EXCEPT_PAGE_FAULT
    {
        SetLastError(STATUS_ACCESS_VIOLATION);
    }
    __ENDTRY
    return ret;
}

3004 3005 3006 3007 3008 3009 3010 3011 3012 3013 3014 3015 3016 3017
static BOOL CRYPT_AsnEncodeCertPolicyMapping(DWORD dwCertEncodingType,
 const CERT_POLICY_MAPPING *mapping, DWORD dwFlags, BYTE *pbEncoded,
 DWORD *pcbEncoded)
{
    struct AsnEncodeSequenceItem items[] = {
     { mapping->pszIssuerDomainPolicy,  CRYPT_AsnEncodeOid, 0 },
     { mapping->pszSubjectDomainPolicy, CRYPT_AsnEncodeOid, 0 },
    };

    if (!mapping->pszIssuerDomainPolicy || !mapping->pszSubjectDomainPolicy)
    {
        SetLastError(E_INVALIDARG);
        return FALSE;
    }
3018
    return CRYPT_AsnEncodeSequence(dwCertEncodingType, items, ARRAY_SIZE(items), dwFlags, NULL, pbEncoded, pcbEncoded);
3019 3020 3021 3022 3023 3024 3025 3026 3027 3028 3029 3030 3031 3032 3033 3034 3035 3036 3037 3038 3039 3040 3041 3042 3043 3044 3045 3046 3047 3048 3049 3050 3051
}

static BOOL WINAPI CRYPT_AsnEncodeCertPolicyMappings(DWORD dwCertEncodingType,
 LPCSTR lpszStructType, const void *pvStructInfo, DWORD dwFlags,
 PCRYPT_ENCODE_PARA pEncodePara, BYTE *pbEncoded, DWORD *pcbEncoded)
{
    BOOL ret = FALSE;

    __TRY
    {
        const CERT_POLICY_MAPPINGS_INFO *info = pvStructInfo;
        DWORD bytesNeeded = 0, lenBytes, size, i;

        ret = TRUE;
        for (i = 0; ret && i < info->cPolicyMapping; i++)
        {
            ret = CRYPT_AsnEncodeCertPolicyMapping(dwCertEncodingType,
             &info->rgPolicyMapping[i], dwFlags & ~CRYPT_ENCODE_ALLOC_FLAG,
             NULL, &size);
            if (ret)
                bytesNeeded += size;
        }
        CRYPT_EncodeLen(bytesNeeded, NULL, &lenBytes);
        bytesNeeded += 1 + lenBytes;
        if (ret)
        {
            if (!pbEncoded)
                *pcbEncoded = bytesNeeded;
            else
            {
                if ((ret = CRYPT_EncodeEnsureSpace(dwFlags, pEncodePara,
                 pbEncoded, pcbEncoded, bytesNeeded)))
                {
3052 3053
                    BYTE *out;

3054 3055
                    if (dwFlags & CRYPT_ENCODE_ALLOC_FLAG)
                        pbEncoded = *(BYTE **)pbEncoded;
3056 3057 3058 3059
                    out = pbEncoded;
                    *out++ = ASN_SEQUENCEOF;
                    CRYPT_EncodeLen(bytesNeeded - lenBytes - 1, out, &lenBytes);
                    out += lenBytes;
3060 3061 3062 3063 3064
                    for (i = 0; ret && i < info->cPolicyMapping; i++)
                    {
                        size = bytesNeeded;
                        ret = CRYPT_AsnEncodeCertPolicyMapping(
                         dwCertEncodingType, &info->rgPolicyMapping[i],
3065
                         dwFlags & ~CRYPT_ENCODE_ALLOC_FLAG, out, &size);
3066 3067
                        if (ret)
                        {
3068
                            out += size;
3069 3070 3071
                            bytesNeeded -= size;
                        }
                    }
3072 3073
                    if (!ret && (dwFlags & CRYPT_ENCODE_ALLOC_FLAG))
                        CRYPT_FreeSpace(pEncodePara, pbEncoded);
3074 3075 3076 3077 3078 3079 3080 3081 3082 3083 3084 3085
                }
            }
        }
    }
    __EXCEPT_PAGE_FAULT
    {
        SetLastError(STATUS_ACCESS_VIOLATION);
    }
    __ENDTRY
    return ret;
}

3086 3087 3088 3089 3090 3091 3092 3093 3094 3095 3096 3097 3098 3099 3100 3101 3102 3103 3104 3105 3106 3107 3108 3109 3110 3111 3112 3113 3114 3115 3116 3117 3118 3119 3120 3121 3122 3123 3124 3125 3126 3127 3128 3129 3130 3131 3132
static BOOL WINAPI CRYPT_AsnEncodeCertPolicyConstraints(
 DWORD dwCertEncodingType, LPCSTR lpszStructType, const void *pvStructInfo,
 DWORD dwFlags, PCRYPT_ENCODE_PARA pEncodePara, BYTE *pbEncoded,
 DWORD *pcbEncoded)
{
    BOOL ret = FALSE;

    __TRY
    {
        const CERT_POLICY_CONSTRAINTS_INFO *info = pvStructInfo;
        struct AsnEncodeSequenceItem items[2];
        struct AsnEncodeTagSwappedItem swapped[2];
        DWORD cItem = 0, cSwapped = 0;

        if (info->fRequireExplicitPolicy)
        {
            swapped[cSwapped].tag = ASN_CONTEXT | 0;
            swapped[cSwapped].pvStructInfo =
             &info->dwRequireExplicitPolicySkipCerts;
            swapped[cSwapped].encodeFunc = CRYPT_AsnEncodeInt;
            items[cItem].pvStructInfo = &swapped[cSwapped];
            items[cItem].encodeFunc = CRYPT_AsnEncodeSwapTag;
            cSwapped++;
            cItem++;
        }
        if (info->fInhibitPolicyMapping)
        {
            swapped[cSwapped].tag = ASN_CONTEXT | 1;
            swapped[cSwapped].pvStructInfo =
             &info->dwInhibitPolicyMappingSkipCerts;
            swapped[cSwapped].encodeFunc = CRYPT_AsnEncodeInt;
            items[cItem].pvStructInfo = &swapped[cSwapped];
            items[cItem].encodeFunc = CRYPT_AsnEncodeSwapTag;
            cSwapped++;
            cItem++;
        }
        ret = CRYPT_AsnEncodeSequence(dwCertEncodingType, items, cItem,
         dwFlags, NULL, pbEncoded, pcbEncoded);
    }
    __EXCEPT_PAGE_FAULT
    {
        SetLastError(STATUS_ACCESS_VIOLATION);
    }
    __ENDTRY
    return ret;
}

3133 3134 3135 3136 3137 3138 3139 3140
static BOOL WINAPI CRYPT_AsnEncodeRsaPubKey(DWORD dwCertEncodingType,
 LPCSTR lpszStructType, const void *pvStructInfo, DWORD dwFlags,
 PCRYPT_ENCODE_PARA pEncodePara, BYTE *pbEncoded, DWORD *pcbEncoded)
{
    BOOL ret;

    __TRY
    {
3141
        const BLOBHEADER *hdr = pvStructInfo;
3142 3143 3144

        if (hdr->bType != PUBLICKEYBLOB)
        {
3145
            SetLastError(E_INVALIDARG);
3146 3147 3148 3149 3150 3151 3152 3153 3154
            ret = FALSE;
        }
        else
        {
            const RSAPUBKEY *rsaPubKey = (const RSAPUBKEY *)
             ((const BYTE *)pvStructInfo + sizeof(BLOBHEADER));
            CRYPT_INTEGER_BLOB blob = { rsaPubKey->bitlen / 8,
             (BYTE *)pvStructInfo + sizeof(BLOBHEADER) + sizeof(RSAPUBKEY) };
            struct AsnEncodeSequenceItem items[] = { 
3155
             { &blob, CRYPT_AsnEncodeUnsignedInteger, 0 },
3156 3157 3158 3159
             { &rsaPubKey->pubexp, CRYPT_AsnEncodeInt, 0 },
            };

            ret = CRYPT_AsnEncodeSequence(dwCertEncodingType, items,
3160
             ARRAY_SIZE(items), dwFlags, pEncodePara, pbEncoded, pcbEncoded);
3161 3162
        }
    }
3163
    __EXCEPT_PAGE_FAULT
3164 3165 3166 3167 3168 3169 3170 3171
    {
        SetLastError(STATUS_ACCESS_VIOLATION);
        ret = FALSE;
    }
    __ENDTRY
    return ret;
}

3172
BOOL WINAPI CRYPT_AsnEncodeOctets(DWORD dwCertEncodingType,
3173 3174 3175
 LPCSTR lpszStructType, const void *pvStructInfo, DWORD dwFlags,
 PCRYPT_ENCODE_PARA pEncodePara, BYTE *pbEncoded, DWORD *pcbEncoded)
{
3176
    BOOL ret;
3177

3178
    __TRY
3179
    {
3180
        const CRYPT_DATA_BLOB *blob = pvStructInfo;
3181 3182
        DWORD bytesNeeded, lenBytes;

3183
        TRACE("(%d, %p), %08x, %p, %p, %d\n", blob->cbData, blob->pbData,
3184
         dwFlags, pEncodePara, pbEncoded, pbEncoded ? *pcbEncoded : 0);
3185

3186 3187 3188 3189 3190 3191 3192 3193 3194 3195 3196 3197 3198 3199 3200 3201 3202 3203 3204 3205 3206
        CRYPT_EncodeLen(blob->cbData, NULL, &lenBytes);
        bytesNeeded = 1 + lenBytes + blob->cbData;
        if (!pbEncoded)
        {
            *pcbEncoded = bytesNeeded;
            ret = TRUE;
        }
        else
        {
            if ((ret = CRYPT_EncodeEnsureSpace(dwFlags, pEncodePara, pbEncoded,
             pcbEncoded, bytesNeeded)))
            {
                if (dwFlags & CRYPT_ENCODE_ALLOC_FLAG)
                    pbEncoded = *(BYTE **)pbEncoded;
                *pbEncoded++ = ASN_OCTETSTRING;
                CRYPT_EncodeLen(blob->cbData, pbEncoded, &lenBytes);
                pbEncoded += lenBytes;
                if (blob->cbData)
                    memcpy(pbEncoded, blob->pbData, blob->cbData);
            }
        }
3207
    }
3208
    __EXCEPT_PAGE_FAULT
3209
    {
3210 3211
        SetLastError(STATUS_ACCESS_VIOLATION);
        ret = FALSE;
3212
    }
3213
    __ENDTRY
3214
    TRACE("returning %d (%08x)\n", ret, GetLastError());
3215
    return ret;
3216 3217 3218 3219 3220 3221
}

static BOOL WINAPI CRYPT_AsnEncodeBits(DWORD dwCertEncodingType,
 LPCSTR lpszStructType, const void *pvStructInfo, DWORD dwFlags,
 PCRYPT_ENCODE_PARA pEncodePara, BYTE *pbEncoded, DWORD *pcbEncoded)
{
3222
    BOOL ret;
3223

3224
    __TRY
3225
    {
3226
        const CRYPT_BIT_BLOB *blob = pvStructInfo;
3227 3228
        DWORD bytesNeeded, lenBytes, dataBytes;
        BYTE unusedBits;
3229

3230
        /* yep, MS allows cUnusedBits to be >= 8 */
3231 3232 3233 3234 3235 3236
        if (!blob->cUnusedBits)
        {
            dataBytes = blob->cbData;
            unusedBits = 0;
        }
        else if (blob->cbData * 8 > blob->cUnusedBits)
3237 3238 3239 3240 3241 3242 3243 3244 3245 3246 3247 3248 3249
        {
            dataBytes = (blob->cbData * 8 - blob->cUnusedBits) / 8 + 1;
            unusedBits = blob->cUnusedBits >= 8 ? blob->cUnusedBits / 8 :
             blob->cUnusedBits;
        }
        else
        {
            dataBytes = 0;
            unusedBits = 0;
        }
        CRYPT_EncodeLen(dataBytes + 1, NULL, &lenBytes);
        bytesNeeded = 1 + lenBytes + dataBytes + 1;
        if (!pbEncoded)
3250
        {
3251 3252 3253 3254 3255 3256 3257 3258 3259 3260 3261 3262 3263 3264 3265 3266 3267 3268 3269 3270 3271 3272 3273 3274 3275 3276
            *pcbEncoded = bytesNeeded;
            ret = TRUE;
        }
        else
        {
            if ((ret = CRYPT_EncodeEnsureSpace(dwFlags, pEncodePara, pbEncoded,
             pcbEncoded, bytesNeeded)))
            {
                if (dwFlags & CRYPT_ENCODE_ALLOC_FLAG)
                    pbEncoded = *(BYTE **)pbEncoded;
                *pbEncoded++ = ASN_BITSTRING;
                CRYPT_EncodeLen(dataBytes + 1, pbEncoded, &lenBytes);
                pbEncoded += lenBytes;
                *pbEncoded++ = unusedBits;
                if (dataBytes)
                {
                    BYTE mask = 0xff << unusedBits;

                    if (dataBytes > 1)
                    {
                        memcpy(pbEncoded, blob->pbData, dataBytes - 1);
                        pbEncoded += dataBytes - 1;
                    }
                    *pbEncoded = *(blob->pbData + dataBytes - 1) & mask;
                }
            }
3277 3278
        }
    }
3279
    __EXCEPT_PAGE_FAULT
3280 3281 3282 3283 3284 3285
    {
        SetLastError(STATUS_ACCESS_VIOLATION);
        ret = FALSE;
    }
    __ENDTRY
    return ret;
3286 3287
}

3288 3289 3290 3291 3292 3293 3294 3295
static BOOL WINAPI CRYPT_AsnEncodeBitsSwapBytes(DWORD dwCertEncodingType,
 LPCSTR lpszStructType, const void *pvStructInfo, DWORD dwFlags,
 PCRYPT_ENCODE_PARA pEncodePara, BYTE *pbEncoded, DWORD *pcbEncoded)
{
    BOOL ret;

    __TRY
    {
3296
        const CRYPT_BIT_BLOB *blob = pvStructInfo;
3297 3298 3299 3300 3301
        CRYPT_BIT_BLOB newBlob = { blob->cbData, NULL, blob->cUnusedBits };

        ret = TRUE;
        if (newBlob.cbData)
        {
3302
            newBlob.pbData = CryptMemAlloc(newBlob.cbData);
3303 3304 3305 3306 3307 3308 3309 3310 3311 3312 3313 3314 3315
            if (newBlob.pbData)
            {
                DWORD i;

                for (i = 0; i < newBlob.cbData; i++)
                    newBlob.pbData[newBlob.cbData - i - 1] = blob->pbData[i];
            }
            else
                ret = FALSE;
        }
        if (ret)
            ret = CRYPT_AsnEncodeBits(dwCertEncodingType, lpszStructType,
             &newBlob, dwFlags, pEncodePara, pbEncoded, pcbEncoded);
3316
        CryptMemFree(newBlob.pbData);
3317
    }
3318
    __EXCEPT_PAGE_FAULT
3319 3320 3321 3322 3323 3324 3325 3326
    {
        SetLastError(STATUS_ACCESS_VIOLATION);
        ret = FALSE;
    }
    __ENDTRY
    return ret;
}

3327
static BOOL WINAPI CRYPT_AsnEncodeInt(DWORD dwCertEncodingType,
3328 3329
 LPCSTR lpszStructType, const void *pvStructInfo, DWORD dwFlags,
 PCRYPT_ENCODE_PARA pEncodePara, BYTE *pbEncoded, DWORD *pcbEncoded)
3330
{
3331
    CRYPT_INTEGER_BLOB blob = { sizeof(INT), (BYTE *)pvStructInfo };
3332

3333 3334
    return CRYPT_AsnEncodeInteger(dwCertEncodingType, X509_MULTI_BYTE_INTEGER,
     &blob, dwFlags, pEncodePara, pbEncoded, pcbEncoded);
3335 3336
}

3337 3338 3339 3340
static BOOL WINAPI CRYPT_AsnEncodeInteger(DWORD dwCertEncodingType,
 LPCSTR lpszStructType, const void *pvStructInfo, DWORD dwFlags,
 PCRYPT_ENCODE_PARA pEncodePara, BYTE *pbEncoded, DWORD *pcbEncoded)
{
3341
    BOOL ret;
3342

3343
    __TRY
3344
    {
3345 3346
        DWORD significantBytes, lenBytes, bytesNeeded;
        BYTE padByte = 0;
3347
        BOOL pad = FALSE;
3348
        const CRYPT_INTEGER_BLOB *blob = pvStructInfo;
3349

3350 3351
        significantBytes = blob->cbData;
        if (significantBytes)
3352
        {
3353
            if (blob->pbData[significantBytes - 1] & 0x80)
3354
            {
3355 3356 3357 3358 3359 3360 3361 3362 3363 3364 3365 3366 3367 3368 3369 3370 3371 3372 3373 3374 3375 3376 3377
                /* negative, lop off leading (little-endian) 0xffs */
                for (; significantBytes > 0 &&
                 blob->pbData[significantBytes - 1] == 0xff; significantBytes--)
                    ;
                if (blob->pbData[significantBytes - 1] < 0x80)
                {
                    padByte = 0xff;
                    pad = TRUE;
                }
            }
            else
            {
                /* positive, lop off leading (little-endian) zeroes */
                for (; significantBytes > 0 &&
                 !blob->pbData[significantBytes - 1]; significantBytes--)
                    ;
                if (significantBytes == 0)
                    significantBytes = 1;
                if (blob->pbData[significantBytes - 1] > 0x7f)
                {
                    padByte = 0;
                    pad = TRUE;
                }
3378 3379
            }
        }
3380 3381
        if (pad)
            CRYPT_EncodeLen(significantBytes + 1, NULL, &lenBytes);
3382
        else
3383 3384 3385 3386 3387
            CRYPT_EncodeLen(significantBytes, NULL, &lenBytes);
        bytesNeeded = 1 + lenBytes + significantBytes;
        if (pad)
            bytesNeeded++;
        if (!pbEncoded)
3388
        {
3389 3390 3391 3392 3393 3394 3395
            *pcbEncoded = bytesNeeded;
            ret = TRUE;
        }
        else
        {
            if ((ret = CRYPT_EncodeEnsureSpace(dwFlags, pEncodePara, pbEncoded,
             pcbEncoded, bytesNeeded)))
3396
            {
3397 3398 3399 3400 3401 3402 3403 3404 3405 3406 3407 3408 3409 3410 3411 3412
                if (dwFlags & CRYPT_ENCODE_ALLOC_FLAG)
                    pbEncoded = *(BYTE **)pbEncoded;
                *pbEncoded++ = ASN_INTEGER;
                if (pad)
                {
                    CRYPT_EncodeLen(significantBytes + 1, pbEncoded, &lenBytes);
                    pbEncoded += lenBytes;
                    *pbEncoded++ = padByte;
                }
                else
                {
                    CRYPT_EncodeLen(significantBytes, pbEncoded, &lenBytes);
                    pbEncoded += lenBytes;
                }
                for (; significantBytes > 0; significantBytes--)
                    *(pbEncoded++) = blob->pbData[significantBytes - 1];
3413 3414 3415
            }
        }
    }
3416
    __EXCEPT_PAGE_FAULT
3417
    {
3418 3419
        SetLastError(STATUS_ACCESS_VIOLATION);
        ret = FALSE;
3420
    }
3421 3422
    __ENDTRY
    return ret;
3423 3424 3425 3426 3427 3428
}

static BOOL WINAPI CRYPT_AsnEncodeUnsignedInteger(DWORD dwCertEncodingType,
 LPCSTR lpszStructType, const void *pvStructInfo, DWORD dwFlags,
 PCRYPT_ENCODE_PARA pEncodePara, BYTE *pbEncoded, DWORD *pcbEncoded)
{
3429
    BOOL ret;
3430

3431
    __TRY
3432
    {
3433
        DWORD significantBytes, lenBytes, bytesNeeded;
3434
        BOOL pad = FALSE;
3435
        const CRYPT_INTEGER_BLOB *blob = pvStructInfo;
3436

3437 3438 3439 3440 3441 3442 3443 3444 3445 3446 3447 3448 3449 3450 3451 3452 3453 3454 3455 3456 3457 3458 3459 3460 3461 3462 3463 3464 3465 3466 3467 3468 3469 3470 3471 3472 3473 3474 3475 3476 3477 3478 3479 3480 3481 3482 3483
        significantBytes = blob->cbData;
        if (significantBytes)
        {
            /* positive, lop off leading (little-endian) zeroes */
            for (; significantBytes > 0 && !blob->pbData[significantBytes - 1];
             significantBytes--)
                ;
            if (significantBytes == 0)
                significantBytes = 1;
            if (blob->pbData[significantBytes - 1] > 0x7f)
                pad = TRUE;
        }
        if (pad)
            CRYPT_EncodeLen(significantBytes + 1, NULL, &lenBytes);
        else
            CRYPT_EncodeLen(significantBytes, NULL, &lenBytes);
        bytesNeeded = 1 + lenBytes + significantBytes;
        if (pad)
            bytesNeeded++;
        if (!pbEncoded)
        {
            *pcbEncoded = bytesNeeded;
            ret = TRUE;
        }
        else
        {
            if ((ret = CRYPT_EncodeEnsureSpace(dwFlags, pEncodePara, pbEncoded,
             pcbEncoded, bytesNeeded)))
            {
                if (dwFlags & CRYPT_ENCODE_ALLOC_FLAG)
                    pbEncoded = *(BYTE **)pbEncoded;
                *pbEncoded++ = ASN_INTEGER;
                if (pad)
                {
                    CRYPT_EncodeLen(significantBytes + 1, pbEncoded, &lenBytes);
                    pbEncoded += lenBytes;
                    *pbEncoded++ = 0;
                }
                else
                {
                    CRYPT_EncodeLen(significantBytes, pbEncoded, &lenBytes);
                    pbEncoded += lenBytes;
                }
                for (; significantBytes > 0; significantBytes--)
                    *(pbEncoded++) = blob->pbData[significantBytes - 1];
            }
        }
3484
    }
3485
    __EXCEPT_PAGE_FAULT
3486
    {
3487 3488
        SetLastError(STATUS_ACCESS_VIOLATION);
        ret = FALSE;
3489
    }
3490 3491
    __ENDTRY
    return ret;
3492 3493
}

3494 3495 3496 3497 3498 3499 3500 3501 3502 3503 3504 3505 3506 3507 3508 3509 3510 3511 3512 3513 3514
static BOOL WINAPI CRYPT_AsnEncodeEnumerated(DWORD dwCertEncodingType,
 LPCSTR lpszStructType, const void *pvStructInfo, DWORD dwFlags,
 PCRYPT_ENCODE_PARA pEncodePara, BYTE *pbEncoded, DWORD *pcbEncoded)
{
    CRYPT_INTEGER_BLOB blob;
    BOOL ret;

    /* Encode as an unsigned integer, then change the tag to enumerated */
    blob.cbData = sizeof(DWORD);
    blob.pbData = (BYTE *)pvStructInfo;
    ret = CRYPT_AsnEncodeUnsignedInteger(dwCertEncodingType,
     X509_MULTI_BYTE_UINT, &blob, dwFlags, pEncodePara, pbEncoded, pcbEncoded);
    if (ret && pbEncoded)
    {
        if (dwFlags & CRYPT_ENCODE_ALLOC_FLAG)
            pbEncoded = *(BYTE **)pbEncoded;
        pbEncoded[0] = ASN_ENUMERATED;
    }
    return ret;
}

3515 3516 3517 3518
static BOOL WINAPI CRYPT_AsnEncodeUtcTime(DWORD dwCertEncodingType,
 LPCSTR lpszStructType, const void *pvStructInfo, DWORD dwFlags,
 PCRYPT_ENCODE_PARA pEncodePara, BYTE *pbEncoded, DWORD *pcbEncoded)
{
3519
    BOOL ret;
3520

3521
    __TRY
3522
    {
3523
        SYSTEMTIME sysTime;
3524
        /* sorry, magic number: enough for tag, len, YYMMDDHHMMSSZ.  I use a
3525 3526
         * temporary buffer because the output buffer is not NULL-terminated.
         */
3527 3528
        static const DWORD bytesNeeded = 15;
        char buf[40];
3529 3530 3531 3532 3533 3534 3535 3536 3537

        if (!pbEncoded)
        {
            *pcbEncoded = bytesNeeded;
            ret = TRUE;
        }
        else
        {
            /* Sanity check the year, this is a two-digit year format */
3538
            ret = FileTimeToSystemTime(pvStructInfo, &sysTime);
3539 3540 3541 3542 3543 3544 3545 3546 3547 3548 3549 3550 3551 3552 3553 3554 3555
            if (ret && (sysTime.wYear < 1950 || sysTime.wYear > 2050))
            {
                SetLastError(CRYPT_E_BAD_ENCODE);
                ret = FALSE;
            }
            if (ret)
            {
                if ((ret = CRYPT_EncodeEnsureSpace(dwFlags, pEncodePara,
                 pbEncoded, pcbEncoded, bytesNeeded)))
                {
                    if (dwFlags & CRYPT_ENCODE_ALLOC_FLAG)
                        pbEncoded = *(BYTE **)pbEncoded;
                    buf[0] = ASN_UTCTIME;
                    buf[1] = bytesNeeded - 2;
                    snprintf(buf + 2, sizeof(buf) - 2,
                     "%02d%02d%02d%02d%02d%02dZ", sysTime.wYear >= 2000 ?
                     sysTime.wYear - 2000 : sysTime.wYear - 1900,
3556
                     sysTime.wMonth, sysTime.wDay, sysTime.wHour,
3557 3558 3559 3560 3561
                     sysTime.wMinute, sysTime.wSecond);
                    memcpy(pbEncoded, buf, bytesNeeded);
                }
            }
        }
3562
    }
3563
    __EXCEPT_PAGE_FAULT
3564
    {
3565 3566
        SetLastError(STATUS_ACCESS_VIOLATION);
        ret = FALSE;
3567
    }
3568 3569
    __ENDTRY
    return ret;
3570 3571
}

3572
static BOOL CRYPT_AsnEncodeGeneralizedTime(DWORD dwCertEncodingType,
3573 3574 3575
 LPCSTR lpszStructType, const void *pvStructInfo, DWORD dwFlags,
 PCRYPT_ENCODE_PARA pEncodePara, BYTE *pbEncoded, DWORD *pcbEncoded)
{
3576
    BOOL ret;
3577

3578
    __TRY
3579
    {
3580
        SYSTEMTIME sysTime;
3581
        /* sorry, magic number: enough for tag, len, YYYYMMDDHHMMSSZ.  I use a
3582 3583
         * temporary buffer because the output buffer is not NULL-terminated.
         */
3584 3585
        static const DWORD bytesNeeded = 17;
        char buf[40];
3586 3587 3588 3589 3590 3591 3592 3593

        if (!pbEncoded)
        {
            *pcbEncoded = bytesNeeded;
            ret = TRUE;
        }
        else
        {
3594
            ret = FileTimeToSystemTime(pvStructInfo, &sysTime);
3595 3596 3597 3598 3599 3600 3601 3602 3603 3604
            if (ret)
                ret = CRYPT_EncodeEnsureSpace(dwFlags, pEncodePara, pbEncoded,
                 pcbEncoded, bytesNeeded);
            if (ret)
            {
                if (dwFlags & CRYPT_ENCODE_ALLOC_FLAG)
                    pbEncoded = *(BYTE **)pbEncoded;
                buf[0] = ASN_GENERALTIME;
                buf[1] = bytesNeeded - 2;
                snprintf(buf + 2, sizeof(buf) - 2, "%04d%02d%02d%02d%02d%02dZ",
3605
                 sysTime.wYear, sysTime.wMonth, sysTime.wDay, sysTime.wHour,
3606 3607 3608 3609
                 sysTime.wMinute, sysTime.wSecond);
                memcpy(pbEncoded, buf, bytesNeeded);
            }
        }
3610
    }
3611
    __EXCEPT_PAGE_FAULT
3612
    {
3613 3614
        SetLastError(STATUS_ACCESS_VIOLATION);
        ret = FALSE;
3615
    }
3616 3617
    __ENDTRY
    return ret;
3618 3619
}

3620 3621 3622 3623 3624 3625
static BOOL WINAPI CRYPT_AsnEncodeChoiceOfTime(DWORD dwCertEncodingType,
 LPCSTR lpszStructType, const void *pvStructInfo, DWORD dwFlags,
 PCRYPT_ENCODE_PARA pEncodePara, BYTE *pbEncoded, DWORD *pcbEncoded)
{
    BOOL ret;

3626 3627 3628 3629 3630
    __TRY
    {
        SYSTEMTIME sysTime;

        /* Check the year, if it's in the UTCTime range call that encode func */
3631
        if (!FileTimeToSystemTime(pvStructInfo, &sysTime))
3632 3633 3634 3635 3636 3637 3638 3639 3640
            return FALSE;
        if (sysTime.wYear >= 1950 && sysTime.wYear <= 2050)
            ret = CRYPT_AsnEncodeUtcTime(dwCertEncodingType, lpszStructType,
             pvStructInfo, dwFlags, pEncodePara, pbEncoded, pcbEncoded);
        else
            ret = CRYPT_AsnEncodeGeneralizedTime(dwCertEncodingType,
             lpszStructType, pvStructInfo, dwFlags, pEncodePara, pbEncoded,
             pcbEncoded);
    }
3641
    __EXCEPT_PAGE_FAULT
3642
    {
3643
        SetLastError(STATUS_ACCESS_VIOLATION);
3644
        ret = FALSE;
3645
    }
3646
    __ENDTRY
3647 3648 3649
    return ret;
}

3650 3651 3652 3653
static BOOL WINAPI CRYPT_AsnEncodeSequenceOfAny(DWORD dwCertEncodingType,
 LPCSTR lpszStructType, const void *pvStructInfo, DWORD dwFlags,
 PCRYPT_ENCODE_PARA pEncodePara, BYTE *pbEncoded, DWORD *pcbEncoded)
{
3654
    BOOL ret;
3655

3656
    __TRY
3657
    {
3658
        DWORD bytesNeeded, dataLen, lenBytes, i;
3659
        const CRYPT_SEQUENCE_OF_ANY *seq = pvStructInfo;
3660 3661 3662 3663 3664 3665 3666 3667 3668 3669 3670 3671 3672 3673 3674 3675 3676 3677 3678 3679 3680 3681 3682 3683 3684 3685 3686 3687

        for (i = 0, dataLen = 0; i < seq->cValue; i++)
            dataLen += seq->rgValue[i].cbData;
        CRYPT_EncodeLen(dataLen, NULL, &lenBytes);
        bytesNeeded = 1 + lenBytes + dataLen;
        if (!pbEncoded)
        {
            *pcbEncoded = bytesNeeded;
            ret = TRUE;
        }
        else
        {
            if ((ret = CRYPT_EncodeEnsureSpace(dwFlags, pEncodePara, pbEncoded,
             pcbEncoded, bytesNeeded)))
            {
                if (dwFlags & CRYPT_ENCODE_ALLOC_FLAG)
                    pbEncoded = *(BYTE **)pbEncoded;
                *pbEncoded++ = ASN_SEQUENCEOF;
                CRYPT_EncodeLen(dataLen, pbEncoded, &lenBytes);
                pbEncoded += lenBytes;
                for (i = 0; i < seq->cValue; i++)
                {
                    memcpy(pbEncoded, seq->rgValue[i].pbData,
                     seq->rgValue[i].cbData);
                    pbEncoded += seq->rgValue[i].cbData;
                }
            }
        }
3688
    }
3689
    __EXCEPT_PAGE_FAULT
3690
    {
3691 3692
        SetLastError(STATUS_ACCESS_VIOLATION);
        ret = FALSE;
3693
    }
3694 3695
    __ENDTRY
    return ret;
3696 3697
}

3698 3699 3700 3701 3702 3703 3704 3705 3706 3707 3708 3709 3710 3711 3712 3713 3714 3715 3716 3717 3718 3719 3720 3721 3722 3723 3724 3725 3726 3727 3728 3729 3730 3731 3732 3733 3734 3735 3736 3737 3738 3739 3740 3741 3742 3743 3744 3745 3746 3747 3748 3749 3750 3751 3752 3753 3754 3755 3756 3757 3758 3759 3760 3761 3762 3763 3764
static BOOL CRYPT_AsnEncodeDistPoint(const CRL_DIST_POINT *distPoint,
 BYTE *pbEncoded, DWORD *pcbEncoded)
{
    BOOL ret = TRUE;
    struct AsnEncodeSequenceItem items[3] = { { 0 } };
    struct AsnConstructedItem constructed = { 0 };
    struct AsnEncodeTagSwappedItem swapped[3] = { { 0 } };
    DWORD cItem = 0, cSwapped = 0;

    switch (distPoint->DistPointName.dwDistPointNameChoice)
    {
    case CRL_DIST_POINT_NO_NAME:
        /* do nothing */
        break;
    case CRL_DIST_POINT_FULL_NAME:
        swapped[cSwapped].tag = ASN_CONTEXT | ASN_CONSTRUCTOR | 0;
        swapped[cSwapped].pvStructInfo = &distPoint->DistPointName.u.FullName;
        swapped[cSwapped].encodeFunc = CRYPT_AsnEncodeAltName;
        constructed.tag = 0;
        constructed.pvStructInfo = &swapped[cSwapped];
        constructed.encodeFunc = CRYPT_AsnEncodeSwapTag;
        items[cItem].pvStructInfo = &constructed;
        items[cItem].encodeFunc = CRYPT_AsnEncodeConstructed;
        cSwapped++;
        cItem++;
        break;
    case CRL_DIST_POINT_ISSUER_RDN_NAME:
        FIXME("unimplemented for CRL_DIST_POINT_ISSUER_RDN_NAME\n");
        ret = FALSE;
        break;
    default:
        ret = FALSE;
    }
    if (ret && distPoint->ReasonFlags.cbData)
    {
        swapped[cSwapped].tag = ASN_CONTEXT | 1;
        swapped[cSwapped].pvStructInfo = &distPoint->ReasonFlags;
        swapped[cSwapped].encodeFunc = CRYPT_AsnEncodeBits;
        items[cItem].pvStructInfo = &swapped[cSwapped];
        items[cItem].encodeFunc = CRYPT_AsnEncodeSwapTag;
        cSwapped++;
        cItem++;
    }
    if (ret && distPoint->CRLIssuer.cAltEntry)
    {
        swapped[cSwapped].tag = ASN_CONTEXT | ASN_CONSTRUCTOR | 2;
        swapped[cSwapped].pvStructInfo = &distPoint->CRLIssuer;
        swapped[cSwapped].encodeFunc = CRYPT_AsnEncodeAltName;
        items[cItem].pvStructInfo = &swapped[cSwapped];
        items[cItem].encodeFunc = CRYPT_AsnEncodeSwapTag;
        cSwapped++;
        cItem++;
    }
    if (ret)
        ret = CRYPT_AsnEncodeSequence(X509_ASN_ENCODING, items, cItem, 0, NULL,
         pbEncoded, pcbEncoded);
    return ret;
}

static BOOL WINAPI CRYPT_AsnEncodeCRLDistPoints(DWORD dwCertEncodingType,
 LPCSTR lpszStructType, const void *pvStructInfo, DWORD dwFlags,
 PCRYPT_ENCODE_PARA pEncodePara, BYTE *pbEncoded, DWORD *pcbEncoded)
{
    BOOL ret;

    __TRY
    {
3765
        const CRL_DIST_POINTS_INFO *info = pvStructInfo;
3766 3767 3768

        if (!info->cDistPoint)
        {
3769
            SetLastError(E_INVALIDARG);
3770 3771 3772 3773 3774 3775 3776 3777 3778 3779 3780 3781 3782 3783 3784 3785 3786 3787 3788 3789 3790 3791 3792 3793 3794 3795 3796 3797 3798 3799 3800 3801 3802 3803 3804
            ret = FALSE;
        }
        else
        {
            DWORD bytesNeeded, dataLen, lenBytes, i;

            ret = TRUE;
            for (i = 0, dataLen = 0; ret && i < info->cDistPoint; i++)
            {
                DWORD len;

                ret = CRYPT_AsnEncodeDistPoint(&info->rgDistPoint[i], NULL,
                 &len);
                if (ret)
                    dataLen += len;
                else if (GetLastError() == CRYPT_E_INVALID_IA5_STRING)
                {
                    /* Have to propagate index of failing character */
                    *pcbEncoded = len;
                }
            }
            if (ret)
            {
                CRYPT_EncodeLen(dataLen, NULL, &lenBytes);
                bytesNeeded = 1 + lenBytes + dataLen;
                if (!pbEncoded)
                {
                    *pcbEncoded = bytesNeeded;
                    ret = TRUE;
                }
                else
                {
                    if ((ret = CRYPT_EncodeEnsureSpace(dwFlags, pEncodePara,
                     pbEncoded, pcbEncoded, bytesNeeded)))
                    {
3805 3806
                        BYTE *out;

3807 3808
                        if (dwFlags & CRYPT_ENCODE_ALLOC_FLAG)
                            pbEncoded = *(BYTE **)pbEncoded;
3809 3810 3811 3812
                        out = pbEncoded;
                        *out++ = ASN_SEQUENCEOF;
                        CRYPT_EncodeLen(dataLen, out, &lenBytes);
                        out += lenBytes;
3813 3814 3815 3816 3817
                        for (i = 0; ret && i < info->cDistPoint; i++)
                        {
                            DWORD len = dataLen;

                            ret = CRYPT_AsnEncodeDistPoint(
3818
                             &info->rgDistPoint[i], out, &len);
3819 3820
                            if (ret)
                            {
3821
                                out += len;
3822 3823 3824
                                dataLen -= len;
                            }
                        }
3825 3826
                        if (!ret && (dwFlags & CRYPT_ENCODE_ALLOC_FLAG))
                            CRYPT_FreeSpace(pEncodePara, pbEncoded);
3827 3828 3829 3830 3831
                    }
                }
            }
        }
    }
3832
    __EXCEPT_PAGE_FAULT
3833 3834 3835 3836 3837 3838 3839 3840
    {
        SetLastError(STATUS_ACCESS_VIOLATION);
        ret = FALSE;
    }
    __ENDTRY
    return ret;
}

3841 3842 3843 3844 3845 3846 3847 3848
static BOOL WINAPI CRYPT_AsnEncodeEnhancedKeyUsage(DWORD dwCertEncodingType,
 LPCSTR lpszStructType, const void *pvStructInfo, DWORD dwFlags,
 PCRYPT_ENCODE_PARA pEncodePara, BYTE *pbEncoded, DWORD *pcbEncoded)
{
    BOOL ret;

    __TRY
    {
3849
        const CERT_ENHKEY_USAGE *usage = pvStructInfo;
3850 3851 3852 3853 3854 3855 3856 3857 3858 3859 3860 3861 3862 3863 3864 3865 3866 3867 3868 3869 3870 3871
        DWORD bytesNeeded = 0, lenBytes, size, i;

        ret = TRUE;
        for (i = 0; ret && i < usage->cUsageIdentifier; i++)
        {
            ret = CRYPT_AsnEncodeOid(dwCertEncodingType, NULL,
             usage->rgpszUsageIdentifier[i],
             dwFlags & ~CRYPT_ENCODE_ALLOC_FLAG, NULL, NULL, &size);
            if (ret)
                bytesNeeded += size;
        }
        CRYPT_EncodeLen(bytesNeeded, NULL, &lenBytes);
        bytesNeeded += 1 + lenBytes;
        if (ret)
        {
            if (!pbEncoded)
                *pcbEncoded = bytesNeeded;
            else
            {
                if ((ret = CRYPT_EncodeEnsureSpace(dwFlags, pEncodePara,
                 pbEncoded, pcbEncoded, bytesNeeded)))
                {
3872 3873
                    BYTE *out;

3874 3875
                    if (dwFlags & CRYPT_ENCODE_ALLOC_FLAG)
                        pbEncoded = *(BYTE **)pbEncoded;
3876 3877 3878 3879
                    out = pbEncoded;
                    *out++ = ASN_SEQUENCEOF;
                    CRYPT_EncodeLen(bytesNeeded - lenBytes - 1, out, &lenBytes);
                    out += lenBytes;
3880 3881 3882 3883 3884
                    for (i = 0; ret && i < usage->cUsageIdentifier; i++)
                    {
                        size = bytesNeeded;
                        ret = CRYPT_AsnEncodeOid(dwCertEncodingType, NULL,
                         usage->rgpszUsageIdentifier[i],
3885
                         dwFlags & ~CRYPT_ENCODE_ALLOC_FLAG, NULL, out, &size);
3886 3887
                        if (ret)
                        {
3888
                            out += size;
3889 3890 3891
                            bytesNeeded -= size;
                        }
                    }
3892 3893
                    if (!ret && (dwFlags & CRYPT_ENCODE_ALLOC_FLAG))
                        CRYPT_FreeSpace(pEncodePara, pbEncoded);
3894 3895 3896 3897 3898 3899 3900 3901 3902 3903 3904 3905 3906
                }
            }
        }
    }
    __EXCEPT_PAGE_FAULT
    {
        SetLastError(STATUS_ACCESS_VIOLATION);
        ret = FALSE;
    }
    __ENDTRY
    return ret;
}

3907 3908 3909 3910 3911 3912 3913 3914
static BOOL WINAPI CRYPT_AsnEncodeIssuingDistPoint(DWORD dwCertEncodingType,
 LPCSTR lpszStructType, const void *pvStructInfo, DWORD dwFlags,
 PCRYPT_ENCODE_PARA pEncodePara, BYTE *pbEncoded, DWORD *pcbEncoded)
{
    BOOL ret;

    __TRY
    {
3915
        const CRL_ISSUING_DIST_POINT *point = pvStructInfo;
3916 3917 3918 3919 3920 3921 3922 3923 3924 3925 3926 3927 3928 3929 3930 3931 3932 3933 3934 3935 3936 3937 3938 3939 3940 3941 3942 3943 3944 3945 3946 3947 3948 3949 3950 3951 3952 3953 3954 3955 3956 3957 3958 3959 3960 3961 3962 3963 3964 3965 3966 3967 3968 3969 3970 3971 3972 3973 3974 3975 3976 3977 3978 3979 3980 3981 3982 3983 3984 3985 3986 3987 3988 3989 3990 3991 3992 3993 3994 3995
        struct AsnEncodeSequenceItem items[6] = { { 0 } };
        struct AsnConstructedItem constructed = { 0 };
        struct AsnEncodeTagSwappedItem swapped[5] = { { 0 } };
        DWORD cItem = 0, cSwapped = 0;

        ret = TRUE;
        switch (point->DistPointName.dwDistPointNameChoice)
        {
        case CRL_DIST_POINT_NO_NAME:
            /* do nothing */
            break;
        case CRL_DIST_POINT_FULL_NAME:
            swapped[cSwapped].tag = ASN_CONTEXT | ASN_CONSTRUCTOR | 0;
            swapped[cSwapped].pvStructInfo = &point->DistPointName.u.FullName;
            swapped[cSwapped].encodeFunc = CRYPT_AsnEncodeAltName;
            constructed.tag = 0;
            constructed.pvStructInfo = &swapped[cSwapped];
            constructed.encodeFunc = CRYPT_AsnEncodeSwapTag;
            items[cItem].pvStructInfo = &constructed;
            items[cItem].encodeFunc = CRYPT_AsnEncodeConstructed;
            cSwapped++;
            cItem++;
            break;
        default:
            SetLastError(E_INVALIDARG);
            ret = FALSE;
        }
        if (ret && point->fOnlyContainsUserCerts)
        {
            swapped[cSwapped].tag = ASN_CONTEXT | 1;
            swapped[cSwapped].pvStructInfo = &point->fOnlyContainsUserCerts;
            swapped[cSwapped].encodeFunc = CRYPT_AsnEncodeBool;
            items[cItem].pvStructInfo = &swapped[cSwapped];
            items[cItem].encodeFunc = CRYPT_AsnEncodeSwapTag;
            cSwapped++;
            cItem++;
        }
        if (ret && point->fOnlyContainsCACerts)
        {
            swapped[cSwapped].tag = ASN_CONTEXT | 2;
            swapped[cSwapped].pvStructInfo = &point->fOnlyContainsCACerts;
            swapped[cSwapped].encodeFunc = CRYPT_AsnEncodeBool;
            items[cItem].pvStructInfo = &swapped[cSwapped];
            items[cItem].encodeFunc = CRYPT_AsnEncodeSwapTag;
            cSwapped++;
            cItem++;
        }
        if (ret && point->OnlySomeReasonFlags.cbData)
        {
            swapped[cSwapped].tag = ASN_CONTEXT | 3;
            swapped[cSwapped].pvStructInfo = &point->OnlySomeReasonFlags;
            swapped[cSwapped].encodeFunc = CRYPT_AsnEncodeBits;
            items[cItem].pvStructInfo = &swapped[cSwapped];
            items[cItem].encodeFunc = CRYPT_AsnEncodeSwapTag;
            cSwapped++;
            cItem++;
        }
        if (ret && point->fIndirectCRL)
        {
            swapped[cSwapped].tag = ASN_CONTEXT | 4;
            swapped[cSwapped].pvStructInfo = &point->fIndirectCRL;
            swapped[cSwapped].encodeFunc = CRYPT_AsnEncodeBool;
            items[cItem].pvStructInfo = &swapped[cSwapped];
            items[cItem].encodeFunc = CRYPT_AsnEncodeSwapTag;
            cSwapped++;
            cItem++;
        }
        if (ret)
            ret = CRYPT_AsnEncodeSequence(dwCertEncodingType, items, cItem,
             dwFlags, pEncodePara, pbEncoded, pcbEncoded);
    }
    __EXCEPT_PAGE_FAULT
    {
        SetLastError(STATUS_ACCESS_VIOLATION);
        ret = FALSE;
    }
    __ENDTRY
    return ret;
}

3996
static BOOL CRYPT_AsnEncodeGeneralSubtree(DWORD dwCertEncodingType,
3997 3998 3999 4000
 LPCSTR lpszStructType, const void *pvStructInfo, DWORD dwFlags,
 PCRYPT_ENCODE_PARA pEncodePara, BYTE *pbEncoded, DWORD *pcbEncoded)
{
    BOOL ret;
4001
    const CERT_GENERAL_SUBTREE *subtree = pvStructInfo;
4002 4003 4004 4005 4006 4007 4008 4009 4010 4011 4012 4013 4014 4015 4016 4017 4018 4019 4020 4021 4022 4023 4024 4025 4026 4027 4028 4029 4030 4031 4032 4033 4034 4035 4036 4037 4038
    struct AsnEncodeSequenceItem items[3] = {
     { &subtree->Base, CRYPT_AsnEncodeAltNameEntry, 0 },
     { 0 }
    };
    struct AsnEncodeTagSwappedItem swapped[2] = { { 0 } };
    DWORD cItem = 1, cSwapped = 0;

    if (subtree->dwMinimum)
    {
        swapped[cSwapped].tag = ASN_CONTEXT | 0;
        swapped[cSwapped].pvStructInfo = &subtree->dwMinimum;
        swapped[cSwapped].encodeFunc = CRYPT_AsnEncodeInt;
        items[cItem].pvStructInfo = &swapped[cSwapped];
        items[cItem].encodeFunc = CRYPT_AsnEncodeSwapTag;
        cSwapped++;
        cItem++;
    }
    if (subtree->fMaximum)
    {
        swapped[cSwapped].tag = ASN_CONTEXT | 1;
        swapped[cSwapped].pvStructInfo = &subtree->dwMaximum;
        swapped[cSwapped].encodeFunc = CRYPT_AsnEncodeInt;
        items[cItem].pvStructInfo = &swapped[cSwapped];
        items[cItem].encodeFunc = CRYPT_AsnEncodeSwapTag;
        cSwapped++;
        cItem++;
    }
    ret = CRYPT_AsnEncodeSequence(dwCertEncodingType, items, cItem, dwFlags,
     pEncodePara, pbEncoded, pcbEncoded);
    return ret;
}

static BOOL WINAPI CRYPT_AsnEncodeNameConstraints(DWORD dwCertEncodingType,
 LPCSTR lpszStructType, const void *pvStructInfo, DWORD dwFlags,
 PCRYPT_ENCODE_PARA pEncodePara, BYTE *pbEncoded, DWORD *pcbEncoded)
{
    BOOL ret = FALSE;
4039
    CRYPT_BLOB_ARRAY permitted = { 0, NULL }, excluded = { 0, NULL };
4040 4041 4042 4043 4044

    TRACE("%p\n", pvStructInfo);

    __TRY
    {
4045
        const CERT_NAME_CONSTRAINTS_INFO *constraints = pvStructInfo;
4046 4047 4048 4049 4050 4051 4052
        struct AsnEncodeSequenceItem items[2] = { { 0 } };
        struct AsnEncodeTagSwappedItem swapped[2] = { { 0 } };
        DWORD i, cItem = 0, cSwapped = 0;

        ret = TRUE;
        if (constraints->cPermittedSubtree)
        {
4053
            permitted.rgBlob = CryptMemAlloc(
4054
             constraints->cPermittedSubtree * sizeof(CRYPT_DER_BLOB));
4055
            if (permitted.rgBlob)
4056
            {
4057 4058 4059 4060
                permitted.cBlob = constraints->cPermittedSubtree;
                memset(permitted.rgBlob, 0,
                 permitted.cBlob * sizeof(CRYPT_DER_BLOB));
                for (i = 0; ret && i < permitted.cBlob; i++)
4061 4062 4063
                    ret = CRYPT_AsnEncodeGeneralSubtree(dwCertEncodingType,
                     NULL, &constraints->rgPermittedSubtree[i],
                     CRYPT_ENCODE_ALLOC_FLAG, NULL,
4064 4065
                     (BYTE *)&permitted.rgBlob[i].pbData,
                     &permitted.rgBlob[i].cbData);
4066 4067 4068 4069 4070 4071 4072 4073 4074 4075 4076 4077 4078 4079 4080 4081
                if (ret)
                {
                    swapped[cSwapped].tag = ASN_CONTEXT | ASN_CONSTRUCTOR | 0;
                    swapped[cSwapped].pvStructInfo = &permitted;
                    swapped[cSwapped].encodeFunc = CRYPT_DEREncodeSet;
                    items[cItem].pvStructInfo = &swapped[cSwapped];
                    items[cItem].encodeFunc = CRYPT_AsnEncodeSwapTag;
                    cSwapped++;
                    cItem++;
                }
            }
            else
                ret = FALSE;
        }
        if (constraints->cExcludedSubtree)
        {
4082
            excluded.rgBlob = CryptMemAlloc(
4083
             constraints->cExcludedSubtree * sizeof(CRYPT_DER_BLOB));
4084
            if (excluded.rgBlob)
4085
            {
4086 4087 4088 4089
                excluded.cBlob = constraints->cExcludedSubtree;
                memset(excluded.rgBlob, 0,
                 excluded.cBlob * sizeof(CRYPT_DER_BLOB));
                for (i = 0; ret && i < excluded.cBlob; i++)
4090 4091 4092
                    ret = CRYPT_AsnEncodeGeneralSubtree(dwCertEncodingType,
                     NULL, &constraints->rgExcludedSubtree[i],
                     CRYPT_ENCODE_ALLOC_FLAG, NULL,
4093 4094
                     (BYTE *)&excluded.rgBlob[i].pbData,
                     &excluded.rgBlob[i].cbData);
4095 4096 4097 4098 4099 4100 4101 4102 4103 4104 4105 4106 4107 4108 4109 4110 4111
                if (ret)
                {
                    swapped[cSwapped].tag = ASN_CONTEXT | ASN_CONSTRUCTOR | 1;
                    swapped[cSwapped].pvStructInfo = &excluded;
                    swapped[cSwapped].encodeFunc = CRYPT_DEREncodeSet;
                    items[cItem].pvStructInfo = &swapped[cSwapped];
                    items[cItem].encodeFunc = CRYPT_AsnEncodeSwapTag;
                    cSwapped++;
                    cItem++;
                }
            }
            else
                ret = FALSE;
        }
        if (ret)
            ret = CRYPT_AsnEncodeSequence(dwCertEncodingType, items, cItem,
             dwFlags, pEncodePara, pbEncoded, pcbEncoded);
4112 4113 4114 4115
        for (i = 0; i < permitted.cBlob; i++)
            LocalFree(permitted.rgBlob[i].pbData);
        for (i = 0; i < excluded.cBlob; i++)
            LocalFree(excluded.rgBlob[i].pbData);
4116 4117 4118 4119 4120 4121
    }
    __EXCEPT_PAGE_FAULT
    {
        SetLastError(STATUS_ACCESS_VIOLATION);
    }
    __ENDTRY
4122 4123
    CryptMemFree(permitted.rgBlob);
    CryptMemFree(excluded.rgBlob);
4124 4125 4126 4127
    TRACE("returning %d\n", ret);
    return ret;
}

4128 4129 4130 4131 4132 4133
static BOOL WINAPI CRYPT_AsnEncodeIssuerSerialNumber(
 DWORD dwCertEncodingType, LPCSTR lpszStructType, const void *pvStructInfo,
 DWORD dwFlags, PCRYPT_ENCODE_PARA pEncodePara, BYTE *pbEncoded,
 DWORD *pcbEncoded)
{
    BOOL ret;
4134
    const CERT_ISSUER_SERIAL_NUMBER *issuerSerial = pvStructInfo;
4135 4136 4137 4138 4139 4140
    struct AsnEncodeSequenceItem items[] = {
     { &issuerSerial->Issuer,       CRYPT_CopyEncodedBlob, 0 },
     { &issuerSerial->SerialNumber, CRYPT_AsnEncodeInteger, 0 },
    };

    ret = CRYPT_AsnEncodeSequence(dwCertEncodingType, items,
4141
     ARRAY_SIZE(items), dwFlags, pEncodePara, pbEncoded, pcbEncoded);
4142 4143 4144 4145 4146 4147 4148 4149 4150 4151 4152 4153 4154 4155 4156 4157 4158
    return ret;
}

static BOOL WINAPI CRYPT_AsnEncodePKCSSignerInfo(DWORD dwCertEncodingType,
 LPCSTR lpszStructType, const void *pvStructInfo, DWORD dwFlags,
 PCRYPT_ENCODE_PARA pEncodePara, BYTE *pbEncoded, DWORD *pcbEncoded)
{
    BOOL ret = FALSE;

    if (!(dwCertEncodingType & PKCS_7_ASN_ENCODING))
    {
        SetLastError(E_INVALIDARG);
        return FALSE;
    }

    __TRY
    {
4159
        const CMSG_SIGNER_INFO *info = pvStructInfo;
4160 4161 4162 4163 4164 4165 4166 4167

        if (!info->Issuer.cbData)
            SetLastError(E_INVALIDARG);
        else
        {
            struct AsnEncodeSequenceItem items[7] = {
             { &info->dwVersion,     CRYPT_AsnEncodeInt, 0 },
             { &info->Issuer,        CRYPT_AsnEncodeIssuerSerialNumber, 0 },
4168 4169
             { &info->HashAlgorithm, CRYPT_AsnEncodeAlgorithmIdWithNullParams,
               0 },
4170
            };
4171 4172
            struct AsnEncodeTagSwappedItem swapped[2] = { { 0 } };
            DWORD cItem = 3, cSwapped = 0;
4173 4174 4175

            if (info->AuthAttrs.cAttr)
            {
4176 4177 4178 4179 4180 4181
                swapped[cSwapped].tag = ASN_CONTEXT | ASN_CONSTRUCTOR | 0;
                swapped[cSwapped].pvStructInfo = &info->AuthAttrs;
                swapped[cSwapped].encodeFunc = CRYPT_AsnEncodePKCSAttributes;
                items[cItem].pvStructInfo = &swapped[cSwapped];
                items[cItem].encodeFunc = CRYPT_AsnEncodeSwapTag;
                cSwapped++;
4182 4183
                cItem++;
            }
4184 4185 4186 4187 4188 4189
            items[cItem].pvStructInfo = &info->HashEncryptionAlgorithm;
            items[cItem].encodeFunc = CRYPT_AsnEncodeAlgorithmIdWithNullParams;
            cItem++;
            items[cItem].pvStructInfo = &info->EncryptedHash;
            items[cItem].encodeFunc = CRYPT_AsnEncodeOctets;
            cItem++;
4190 4191
            if (info->UnauthAttrs.cAttr)
            {
4192 4193 4194 4195 4196 4197
                swapped[cSwapped].tag = ASN_CONTEXT | ASN_CONSTRUCTOR | 1;
                swapped[cSwapped].pvStructInfo = &info->UnauthAttrs;
                swapped[cSwapped].encodeFunc = CRYPT_AsnEncodePKCSAttributes;
                items[cItem].pvStructInfo = &swapped[cSwapped];
                items[cItem].encodeFunc = CRYPT_AsnEncodeSwapTag;
                cSwapped++;
4198 4199 4200 4201 4202 4203 4204 4205 4206 4207 4208 4209 4210 4211
                cItem++;
            }
            ret = CRYPT_AsnEncodeSequence(dwCertEncodingType, items, cItem,
             dwFlags, pEncodePara, pbEncoded, pcbEncoded);
        }
    }
    __EXCEPT_PAGE_FAULT
    {
        SetLastError(STATUS_ACCESS_VIOLATION);
    }
    __ENDTRY
    return ret;
}

4212 4213 4214 4215 4216 4217 4218 4219 4220 4221 4222 4223 4224 4225
static BOOL WINAPI CRYPT_AsnEncodeCMSSignerInfo(DWORD dwCertEncodingType,
 LPCSTR lpszStructType, const void *pvStructInfo, DWORD dwFlags,
 PCRYPT_ENCODE_PARA pEncodePara, BYTE *pbEncoded, DWORD *pcbEncoded)
{
    BOOL ret = FALSE;

    if (!(dwCertEncodingType & PKCS_7_ASN_ENCODING))
    {
        SetLastError(E_INVALIDARG);
        return FALSE;
    }

    __TRY
    {
4226
        const CMSG_CMS_SIGNER_INFO *info = pvStructInfo;
4227 4228 4229 4230 4231 4232 4233 4234 4235 4236 4237 4238 4239 4240 4241 4242 4243 4244 4245 4246 4247 4248 4249 4250 4251 4252 4253 4254 4255 4256 4257 4258 4259 4260 4261 4262 4263 4264 4265 4266 4267 4268 4269 4270 4271 4272 4273 4274 4275 4276 4277 4278 4279 4280 4281 4282 4283 4284 4285 4286 4287 4288 4289 4290 4291 4292 4293 4294 4295 4296 4297 4298 4299 4300

        if (info->SignerId.dwIdChoice != CERT_ID_ISSUER_SERIAL_NUMBER &&
         info->SignerId.dwIdChoice != CERT_ID_KEY_IDENTIFIER)
            SetLastError(E_INVALIDARG);
        else if (info->SignerId.dwIdChoice == CERT_ID_ISSUER_SERIAL_NUMBER &&
         !info->SignerId.u.IssuerSerialNumber.Issuer.cbData)
            SetLastError(E_INVALIDARG);
        else
        {
            struct AsnEncodeSequenceItem items[7] = {
             { &info->dwVersion,     CRYPT_AsnEncodeInt, 0 },
            };
            struct AsnEncodeTagSwappedItem swapped[3] = { { 0 } };
            DWORD cItem = 1, cSwapped = 0;

            if (info->SignerId.dwIdChoice == CERT_ID_ISSUER_SERIAL_NUMBER)
            {
                items[cItem].pvStructInfo =
                 &info->SignerId.u.IssuerSerialNumber.Issuer;
                items[cItem].encodeFunc =
                 CRYPT_AsnEncodeIssuerSerialNumber;
                cItem++;
            }
            else
            {
                swapped[cSwapped].tag = ASN_CONTEXT | 0;
                swapped[cSwapped].pvStructInfo = &info->SignerId.u.KeyId;
                swapped[cSwapped].encodeFunc = CRYPT_AsnEncodeOctets;
                items[cItem].pvStructInfo = &swapped[cSwapped];
                items[cItem].encodeFunc = CRYPT_AsnEncodeSwapTag;
                cSwapped++;
                cItem++;
            }
            items[cItem].pvStructInfo = &info->HashAlgorithm;
            items[cItem].encodeFunc = CRYPT_AsnEncodeAlgorithmIdWithNullParams;
            cItem++;
            if (info->AuthAttrs.cAttr)
            {
                swapped[cSwapped].tag = ASN_CONTEXT | ASN_CONSTRUCTOR | 0;
                swapped[cSwapped].pvStructInfo = &info->AuthAttrs;
                swapped[cSwapped].encodeFunc = CRYPT_AsnEncodePKCSAttributes;
                items[cItem].pvStructInfo = &swapped[cSwapped];
                items[cItem].encodeFunc = CRYPT_AsnEncodeSwapTag;
                cSwapped++;
                cItem++;
            }
            items[cItem].pvStructInfo = &info->HashEncryptionAlgorithm;
            items[cItem].encodeFunc = CRYPT_AsnEncodeAlgorithmIdWithNullParams;
            cItem++;
            items[cItem].pvStructInfo = &info->EncryptedHash;
            items[cItem].encodeFunc = CRYPT_AsnEncodeOctets;
            cItem++;
            if (info->UnauthAttrs.cAttr)
            {
                swapped[cSwapped].tag = ASN_CONTEXT | ASN_CONSTRUCTOR | 1;
                swapped[cSwapped].pvStructInfo = &info->UnauthAttrs;
                swapped[cSwapped].encodeFunc = CRYPT_AsnEncodePKCSAttributes;
                items[cItem].pvStructInfo = &swapped[cSwapped];
                items[cItem].encodeFunc = CRYPT_AsnEncodeSwapTag;
                cSwapped++;
                cItem++;
            }
            ret = CRYPT_AsnEncodeSequence(dwCertEncodingType, items, cItem,
             dwFlags, pEncodePara, pbEncoded, pcbEncoded);
        }
    }
    __EXCEPT_PAGE_FAULT
    {
        SetLastError(STATUS_ACCESS_VIOLATION);
    }
    __ENDTRY
    return ret;
}

4301
BOOL CRYPT_AsnEncodeCMSSignedInfo(CRYPT_SIGNED_INFO *signedInfo, void *pvData,
4302 4303 4304 4305 4306
 DWORD *pcbData)
{
    struct AsnEncodeSequenceItem items[7] = {
     { &signedInfo->version, CRYPT_AsnEncodeInt, 0 },
    };
4307
    struct DERSetDescriptor digestAlgorithmsSet = { 0 }, certSet = { 0 };
4308
    struct DERSetDescriptor crlSet = { 0 }, signerSet = { 0 };
4309 4310
    struct AsnEncodeTagSwappedItem swapped[2] = { { 0 } };
    DWORD cItem = 1, cSwapped = 0;
4311 4312 4313 4314 4315 4316
    BOOL ret = TRUE;

    if (signedInfo->cSignerInfo)
    {
        digestAlgorithmsSet.cItems = signedInfo->cSignerInfo;
        digestAlgorithmsSet.items = signedInfo->rgSignerInfo;
4317
        digestAlgorithmsSet.itemSize = sizeof(CMSG_CMS_SIGNER_INFO);
4318
        digestAlgorithmsSet.itemOffset =
4319
         offsetof(CMSG_CMS_SIGNER_INFO, HashAlgorithm);
4320 4321 4322 4323 4324 4325 4326 4327
        digestAlgorithmsSet.encode = CRYPT_AsnEncodeAlgorithmIdWithNullParams;
        items[cItem].pvStructInfo = &digestAlgorithmsSet;
        items[cItem].encodeFunc = CRYPT_DEREncodeItemsAsSet;
        cItem++;
    }
    items[cItem].pvStructInfo = &signedInfo->content;
    items[cItem].encodeFunc = CRYPT_AsnEncodePKCSContentInfoInternal;
    cItem++;
4328 4329 4330 4331 4332 4333 4334 4335 4336 4337 4338 4339 4340 4341 4342
    if (signedInfo->cCertEncoded)
    {
        certSet.cItems = signedInfo->cCertEncoded;
        certSet.items = signedInfo->rgCertEncoded;
        certSet.itemSize = sizeof(CERT_BLOB);
        certSet.itemOffset = 0;
        certSet.encode = CRYPT_CopyEncodedBlob;
        swapped[cSwapped].tag = ASN_CONSTRUCTOR | ASN_CONTEXT | 0;
        swapped[cSwapped].pvStructInfo = &certSet;
        swapped[cSwapped].encodeFunc = CRYPT_DEREncodeItemsAsSet;
        items[cItem].pvStructInfo = &swapped[cSwapped];
        items[cItem].encodeFunc = CRYPT_AsnEncodeSwapTag;
        cSwapped++;
        cItem++;
    }
4343 4344 4345 4346 4347 4348 4349 4350 4351 4352 4353 4354 4355 4356 4357
    if (signedInfo->cCrlEncoded)
    {
        crlSet.cItems = signedInfo->cCrlEncoded;
        crlSet.items = signedInfo->rgCrlEncoded;
        crlSet.itemSize = sizeof(CRL_BLOB);
        crlSet.itemOffset = 0;
        crlSet.encode = CRYPT_CopyEncodedBlob;
        swapped[cSwapped].tag = ASN_CONSTRUCTOR | ASN_CONTEXT | 1;
        swapped[cSwapped].pvStructInfo = &crlSet;
        swapped[cSwapped].encodeFunc = CRYPT_DEREncodeItemsAsSet;
        items[cItem].pvStructInfo = &swapped[cSwapped];
        items[cItem].encodeFunc = CRYPT_AsnEncodeSwapTag;
        cSwapped++;
        cItem++;
    }
4358 4359 4360 4361
    if (ret && signedInfo->cSignerInfo)
    {
        signerSet.cItems = signedInfo->cSignerInfo;
        signerSet.items = signedInfo->rgSignerInfo;
4362
        signerSet.itemSize = sizeof(CMSG_CMS_SIGNER_INFO);
4363
        signerSet.itemOffset = 0;
4364
        signerSet.encode = CRYPT_AsnEncodeCMSSignerInfo;
4365 4366 4367 4368 4369 4370 4371 4372 4373 4374 4375
        items[cItem].pvStructInfo = &signerSet;
        items[cItem].encodeFunc = CRYPT_DEREncodeItemsAsSet;
        cItem++;
    }
    if (ret)
        ret = CRYPT_AsnEncodeSequence(X509_ASN_ENCODING | PKCS_7_ASN_ENCODING,
         items, cItem, 0, NULL, pvData, pcbData);

    return ret;
}

4376 4377 4378 4379 4380 4381 4382 4383 4384 4385 4386 4387 4388 4389 4390
static BOOL WINAPI CRYPT_AsnEncodeRecipientInfo(DWORD dwCertEncodingType,
 LPCSTR lpszStructType, const void *pvStructInfo, DWORD dwFlags,
 PCRYPT_ENCODE_PARA pEncodePara, BYTE *pbEncoded, DWORD *pcbEncoded)
{
    const CMSG_KEY_TRANS_RECIPIENT_INFO *info = pvStructInfo;
    struct AsnEncodeSequenceItem items[] = {
     { &info->dwVersion, CRYPT_AsnEncodeInt, 0 },
     { &info->RecipientId.u.IssuerSerialNumber,
       CRYPT_AsnEncodeIssuerSerialNumber, 0 },
     { &info->KeyEncryptionAlgorithm,
       CRYPT_AsnEncodeAlgorithmIdWithNullParams, 0 },
     { &info->EncryptedKey, CRYPT_AsnEncodeOctets, 0 },
    };

    return CRYPT_AsnEncodeSequence(dwCertEncodingType, items,
4391
     ARRAY_SIZE(items), dwFlags, pEncodePara, pbEncoded, pcbEncoded);
4392 4393 4394 4395 4396 4397 4398 4399 4400 4401 4402 4403 4404 4405 4406 4407 4408
}

static BOOL WINAPI CRYPT_AsnEncodeEncryptedContentInfo(DWORD dwCertEncodingType,
 LPCSTR lpszStructType, const void *pvStructInfo, DWORD dwFlags,
 PCRYPT_ENCODE_PARA pEncodePara, BYTE *pbEncoded, DWORD *pcbEncoded)
{
    const CRYPT_ENCRYPTED_CONTENT_INFO *info = pvStructInfo;
    struct AsnEncodeTagSwappedItem swapped = { ASN_CONTEXT | 0,
     &info->encryptedContent, CRYPT_AsnEncodeOctets };
    struct AsnEncodeSequenceItem items[] = {
     { info->contentType, CRYPT_AsnEncodeOid, 0 },
     { &info->contentEncryptionAlgorithm,
       CRYPT_AsnEncodeAlgorithmIdWithNullParams, 0 },
     { &swapped, CRYPT_AsnEncodeSwapTag, 0 },
    };

    return CRYPT_AsnEncodeSequence(dwCertEncodingType, items,
4409
     ARRAY_SIZE(items), dwFlags, pEncodePara, pbEncoded, pcbEncoded);
4410 4411 4412 4413 4414 4415 4416 4417 4418 4419 4420 4421 4422 4423 4424 4425
}

BOOL CRYPT_AsnEncodePKCSEnvelopedData(const CRYPT_ENVELOPED_DATA *envelopedData,
 void *pvData, DWORD *pcbData)
{
    struct DERSetDescriptor recipientInfosSet = { envelopedData->cRecipientInfo,
     envelopedData->rgRecipientInfo, sizeof(CMSG_KEY_TRANS_RECIPIENT_INFO), 0,
     CRYPT_AsnEncodeRecipientInfo };
    struct AsnEncodeSequenceItem items[] = {
     { &envelopedData->version, CRYPT_AsnEncodeInt, 0 },
     { &recipientInfosSet, CRYPT_DEREncodeItemsAsSet, 0 },
     { &envelopedData->encryptedContentInfo,
       CRYPT_AsnEncodeEncryptedContentInfo, 0 },
    };

    return CRYPT_AsnEncodeSequence(X509_ASN_ENCODING, items,
4426
     ARRAY_SIZE(items), 0, NULL, pvData, pcbData);
4427 4428
}

4429 4430
static CryptEncodeObjectExFunc CRYPT_GetBuiltinEncoder(DWORD dwCertEncodingType,
 LPCSTR lpszStructType)
4431
{
4432
    CryptEncodeObjectExFunc encodeFunc = NULL;
4433

4434 4435 4436 4437
    if ((dwCertEncodingType & CERT_ENCODING_TYPE_MASK) != X509_ASN_ENCODING
     && (dwCertEncodingType & CMSG_ENCODING_TYPE_MASK) != PKCS_7_ASN_ENCODING)
    {
        SetLastError(ERROR_FILE_NOT_FOUND);
4438
        return NULL;
4439
    }
4440

4441
    if (IS_INTOID(lpszStructType))
4442
    {
4443
        switch (LOWORD(lpszStructType))
4444
        {
4445
        case LOWORD(X509_CERT):
4446 4447
            encodeFunc = CRYPT_AsnEncodeCert;
            break;
4448
        case LOWORD(X509_CERT_TO_BE_SIGNED):
4449 4450
            encodeFunc = CRYPT_AsnEncodeCertInfo;
            break;
4451
        case LOWORD(X509_CERT_CRL_TO_BE_SIGNED):
4452 4453
            encodeFunc = CRYPT_AsnEncodeCRLInfo;
            break;
4454
        case LOWORD(X509_EXTENSIONS):
4455 4456
            encodeFunc = CRYPT_AsnEncodeExtensions;
            break;
4457
        case LOWORD(X509_NAME_VALUE):
4458 4459
            encodeFunc = CRYPT_AsnEncodeNameValue;
            break;
4460
        case LOWORD(X509_NAME):
4461 4462
            encodeFunc = CRYPT_AsnEncodeName;
            break;
4463
        case LOWORD(X509_PUBLIC_KEY_INFO):
4464 4465
            encodeFunc = CRYPT_AsnEncodePubKeyInfo;
            break;
4466
        case LOWORD(X509_AUTHORITY_KEY_ID):
4467 4468
            encodeFunc = CRYPT_AsnEncodeAuthorityKeyId;
            break;
4469
        case LOWORD(X509_ALTERNATE_NAME):
4470 4471
            encodeFunc = CRYPT_AsnEncodeAltName;
            break;
4472
        case LOWORD(X509_BASIC_CONSTRAINTS):
4473 4474
            encodeFunc = CRYPT_AsnEncodeBasicConstraints;
            break;
4475
        case LOWORD(X509_BASIC_CONSTRAINTS2):
4476 4477
            encodeFunc = CRYPT_AsnEncodeBasicConstraints2;
            break;
4478 4479 4480
        case LOWORD(X509_CERT_POLICIES):
            encodeFunc = CRYPT_AsnEncodeCertPolicies;
            break;
4481
        case LOWORD(RSA_CSP_PUBLICKEYBLOB):
4482 4483
            encodeFunc = CRYPT_AsnEncodeRsaPubKey;
            break;
4484
        case LOWORD(X509_UNICODE_NAME):
4485 4486
            encodeFunc = CRYPT_AsnEncodeUnicodeName;
            break;
4487
        case LOWORD(PKCS_CONTENT_INFO):
4488 4489
            encodeFunc = CRYPT_AsnEncodePKCSContentInfo;
            break;
4490
        case LOWORD(PKCS_ATTRIBUTE):
4491 4492
            encodeFunc = CRYPT_AsnEncodePKCSAttribute;
            break;
4493
        case LOWORD(X509_UNICODE_NAME_VALUE):
4494 4495
            encodeFunc = CRYPT_AsnEncodeUnicodeNameValue;
            break;
4496
        case LOWORD(X509_OCTET_STRING):
4497 4498
            encodeFunc = CRYPT_AsnEncodeOctets;
            break;
4499 4500
        case LOWORD(X509_BITS):
        case LOWORD(X509_KEY_USAGE):
4501 4502
            encodeFunc = CRYPT_AsnEncodeBits;
            break;
4503
        case LOWORD(X509_INTEGER):
4504 4505
            encodeFunc = CRYPT_AsnEncodeInt;
            break;
4506
        case LOWORD(X509_MULTI_BYTE_INTEGER):
4507 4508
            encodeFunc = CRYPT_AsnEncodeInteger;
            break;
4509
        case LOWORD(X509_MULTI_BYTE_UINT):
4510 4511
            encodeFunc = CRYPT_AsnEncodeUnsignedInteger;
            break;
4512
        case LOWORD(X509_ENUMERATED):
4513 4514
            encodeFunc = CRYPT_AsnEncodeEnumerated;
            break;
4515
        case LOWORD(X509_CHOICE_OF_TIME):
4516 4517
            encodeFunc = CRYPT_AsnEncodeChoiceOfTime;
            break;
4518
        case LOWORD(X509_AUTHORITY_KEY_ID2):
4519 4520
            encodeFunc = CRYPT_AsnEncodeAuthorityKeyId2;
            break;
4521 4522 4523
        case LOWORD(X509_AUTHORITY_INFO_ACCESS):
            encodeFunc = CRYPT_AsnEncodeAuthorityInfoAccess;
            break;
4524
        case LOWORD(X509_SEQUENCE_OF_ANY):
4525 4526
            encodeFunc = CRYPT_AsnEncodeSequenceOfAny;
            break;
4527
        case LOWORD(PKCS_UTC_TIME):
4528 4529
            encodeFunc = CRYPT_AsnEncodeUtcTime;
            break;
4530
        case LOWORD(X509_CRL_DIST_POINTS):
4531 4532
            encodeFunc = CRYPT_AsnEncodeCRLDistPoints;
            break;
4533
        case LOWORD(X509_ENHANCED_KEY_USAGE):
4534 4535
            encodeFunc = CRYPT_AsnEncodeEnhancedKeyUsage;
            break;
4536 4537 4538
        case LOWORD(PKCS_CTL):
            encodeFunc = CRYPT_AsnEncodeCTL;
            break;
4539 4540 4541
        case LOWORD(PKCS_SMIME_CAPABILITIES):
            encodeFunc = CRYPT_AsnEncodeSMIMECapabilities;
            break;
4542 4543 4544
        case LOWORD(X509_PKIX_POLICY_QUALIFIER_USERNOTICE):
            encodeFunc = CRYPT_AsnEncodePolicyQualifierUserNotice;
            break;
4545
        case LOWORD(PKCS_ATTRIBUTES):
4546 4547
            encodeFunc = CRYPT_AsnEncodePKCSAttributes;
            break;
4548
        case LOWORD(X509_ISSUING_DIST_POINT):
4549 4550
            encodeFunc = CRYPT_AsnEncodeIssuingDistPoint;
            break;
4551
        case LOWORD(X509_NAME_CONSTRAINTS):
4552 4553
            encodeFunc = CRYPT_AsnEncodeNameConstraints;
            break;
4554 4555 4556
        case LOWORD(X509_POLICY_MAPPINGS):
            encodeFunc = CRYPT_AsnEncodeCertPolicyMappings;
            break;
4557 4558 4559
        case LOWORD(X509_POLICY_CONSTRAINTS):
            encodeFunc = CRYPT_AsnEncodeCertPolicyConstraints;
            break;
4560
        case LOWORD(PKCS7_SIGNER_INFO):
4561 4562
            encodeFunc = CRYPT_AsnEncodePKCSSignerInfo;
            break;
4563 4564 4565
        case LOWORD(CMS_SIGNER_INFO):
            encodeFunc = CRYPT_AsnEncodeCMSSignerInfo;
            break;
4566 4567
        }
    }
4568 4569
    else if (!strcmp(lpszStructType, szOID_CERT_EXTENSIONS))
        encodeFunc = CRYPT_AsnEncodeExtensions;
4570 4571
    else if (!strcmp(lpszStructType, szOID_RSA_signingTime))
        encodeFunc = CRYPT_AsnEncodeUtcTime;
4572 4573
    else if (!strcmp(lpszStructType, szOID_RSA_SMIMECapabilities))
        encodeFunc = CRYPT_AsnEncodeUtcTime;
4574 4575
    else if (!strcmp(lpszStructType, szOID_AUTHORITY_KEY_IDENTIFIER))
        encodeFunc = CRYPT_AsnEncodeAuthorityKeyId;
4576 4577
    else if (!strcmp(lpszStructType, szOID_LEGACY_POLICY_MAPPINGS))
        encodeFunc = CRYPT_AsnEncodeCertPolicyMappings;
4578 4579
    else if (!strcmp(lpszStructType, szOID_AUTHORITY_KEY_IDENTIFIER2))
        encodeFunc = CRYPT_AsnEncodeAuthorityKeyId2;
4580 4581 4582 4583 4584 4585
    else if (!strcmp(lpszStructType, szOID_CRL_REASON_CODE))
        encodeFunc = CRYPT_AsnEncodeEnumerated;
    else if (!strcmp(lpszStructType, szOID_KEY_USAGE))
        encodeFunc = CRYPT_AsnEncodeBits;
    else if (!strcmp(lpszStructType, szOID_SUBJECT_KEY_IDENTIFIER))
        encodeFunc = CRYPT_AsnEncodeOctets;
4586 4587
    else if (!strcmp(lpszStructType, szOID_BASIC_CONSTRAINTS))
        encodeFunc = CRYPT_AsnEncodeBasicConstraints;
4588 4589
    else if (!strcmp(lpszStructType, szOID_BASIC_CONSTRAINTS2))
        encodeFunc = CRYPT_AsnEncodeBasicConstraints2;
4590 4591 4592 4593 4594 4595 4596 4597 4598 4599
    else if (!strcmp(lpszStructType, szOID_ISSUER_ALT_NAME))
        encodeFunc = CRYPT_AsnEncodeAltName;
    else if (!strcmp(lpszStructType, szOID_ISSUER_ALT_NAME2))
        encodeFunc = CRYPT_AsnEncodeAltName;
    else if (!strcmp(lpszStructType, szOID_NEXT_UPDATE_LOCATION))
        encodeFunc = CRYPT_AsnEncodeAltName;
    else if (!strcmp(lpszStructType, szOID_SUBJECT_ALT_NAME))
        encodeFunc = CRYPT_AsnEncodeAltName;
    else if (!strcmp(lpszStructType, szOID_SUBJECT_ALT_NAME2))
        encodeFunc = CRYPT_AsnEncodeAltName;
4600 4601
    else if (!strcmp(lpszStructType, szOID_CRL_DIST_POINTS))
        encodeFunc = CRYPT_AsnEncodeCRLDistPoints;
4602 4603
    else if (!strcmp(lpszStructType, szOID_CERT_POLICIES))
        encodeFunc = CRYPT_AsnEncodeCertPolicies;
4604 4605
    else if (!strcmp(lpszStructType, szOID_POLICY_MAPPINGS))
        encodeFunc = CRYPT_AsnEncodeCertPolicyMappings;
4606 4607
    else if (!strcmp(lpszStructType, szOID_POLICY_CONSTRAINTS))
        encodeFunc = CRYPT_AsnEncodeCertPolicyConstraints;
4608 4609
    else if (!strcmp(lpszStructType, szOID_ENHANCED_KEY_USAGE))
        encodeFunc = CRYPT_AsnEncodeEnhancedKeyUsage;
4610 4611
    else if (!strcmp(lpszStructType, szOID_ISSUING_DIST_POINT))
        encodeFunc = CRYPT_AsnEncodeIssuingDistPoint;
4612 4613
    else if (!strcmp(lpszStructType, szOID_NAME_CONSTRAINTS))
        encodeFunc = CRYPT_AsnEncodeNameConstraints;
4614 4615
    else if (!strcmp(lpszStructType, szOID_AUTHORITY_INFO_ACCESS))
        encodeFunc = CRYPT_AsnEncodeAuthorityInfoAccess;
4616 4617
    else if (!strcmp(lpszStructType, szOID_PKIX_POLICY_QUALIFIER_USERNOTICE))
        encodeFunc = CRYPT_AsnEncodePolicyQualifierUserNotice;
4618 4619
    else if (!strcmp(lpszStructType, szOID_CTL))
        encodeFunc = CRYPT_AsnEncodeCTL;
4620 4621 4622 4623 4624 4625 4626 4627 4628 4629 4630 4631 4632 4633 4634 4635 4636 4637 4638 4639 4640 4641 4642 4643 4644 4645 4646 4647 4648 4649 4650 4651 4652 4653 4654 4655 4656 4657 4658 4659 4660 4661 4662 4663 4664 4665 4666 4667 4668 4669
    return encodeFunc;
}

static CryptEncodeObjectFunc CRYPT_LoadEncoderFunc(DWORD dwCertEncodingType,
 LPCSTR lpszStructType, HCRYPTOIDFUNCADDR *hFunc)
{
    static HCRYPTOIDFUNCSET set = NULL;
    CryptEncodeObjectFunc encodeFunc = NULL;

    if (!set)
        set = CryptInitOIDFunctionSet(CRYPT_OID_ENCODE_OBJECT_FUNC, 0);
    CryptGetOIDFunctionAddress(set, dwCertEncodingType, lpszStructType, 0,
     (void **)&encodeFunc, hFunc);
    return encodeFunc;
}

static CryptEncodeObjectExFunc CRYPT_LoadEncoderExFunc(DWORD dwCertEncodingType,
 LPCSTR lpszStructType, HCRYPTOIDFUNCADDR *hFunc)
{
    static HCRYPTOIDFUNCSET set = NULL;
    CryptEncodeObjectExFunc encodeFunc = NULL;

    if (!set)
        set = CryptInitOIDFunctionSet(CRYPT_OID_ENCODE_OBJECT_EX_FUNC, 0);
    CryptGetOIDFunctionAddress(set, dwCertEncodingType, lpszStructType, 0,
     (void **)&encodeFunc, hFunc);
    return encodeFunc;
}

BOOL WINAPI CryptEncodeObject(DWORD dwCertEncodingType, LPCSTR lpszStructType,
 const void *pvStructInfo, BYTE *pbEncoded, DWORD *pcbEncoded)
{
    BOOL ret = FALSE;
    HCRYPTOIDFUNCADDR hFunc = NULL;
    CryptEncodeObjectFunc pCryptEncodeObject = NULL;
    CryptEncodeObjectExFunc pCryptEncodeObjectEx = NULL;

    TRACE_(crypt)("(0x%08x, %s, %p, %p, %p)\n", dwCertEncodingType,
     debugstr_a(lpszStructType), pvStructInfo, pbEncoded,
     pcbEncoded);

    if (!pbEncoded && !pcbEncoded)
    {
        SetLastError(ERROR_INVALID_PARAMETER);
        return FALSE;
    }

    if (!(pCryptEncodeObjectEx = CRYPT_GetBuiltinEncoder(dwCertEncodingType,
     lpszStructType)))
    {
4670 4671
        TRACE_(crypt)("OID %s not found or unimplemented, looking for DLL\n",
         debugstr_a(lpszStructType));
4672 4673 4674 4675 4676 4677 4678 4679 4680 4681 4682 4683 4684 4685 4686 4687 4688 4689 4690 4691 4692 4693 4694 4695 4696 4697 4698 4699 4700 4701 4702 4703 4704 4705 4706 4707 4708
        pCryptEncodeObject = CRYPT_LoadEncoderFunc(dwCertEncodingType,
         lpszStructType, &hFunc);
        if (!pCryptEncodeObject)
            pCryptEncodeObjectEx = CRYPT_LoadEncoderExFunc(dwCertEncodingType,
             lpszStructType, &hFunc);
    }
    if (pCryptEncodeObject)
        ret = pCryptEncodeObject(dwCertEncodingType, lpszStructType,
         pvStructInfo, pbEncoded, pcbEncoded);
    else if (pCryptEncodeObjectEx)
        ret = pCryptEncodeObjectEx(dwCertEncodingType, lpszStructType,
         pvStructInfo, 0, NULL, pbEncoded, pcbEncoded);
    if (hFunc)
        CryptFreeOIDFunctionAddress(hFunc, 0);
    TRACE_(crypt)("returning %d\n", ret);
    return ret;
}

BOOL WINAPI CryptEncodeObjectEx(DWORD dwCertEncodingType, LPCSTR lpszStructType,
 const void *pvStructInfo, DWORD dwFlags, PCRYPT_ENCODE_PARA pEncodePara,
 void *pvEncoded, DWORD *pcbEncoded)
{
    BOOL ret = FALSE;
    HCRYPTOIDFUNCADDR hFunc = NULL;
    CryptEncodeObjectExFunc encodeFunc = NULL;

    TRACE_(crypt)("(0x%08x, %s, %p, 0x%08x, %p, %p, %p)\n", dwCertEncodingType,
     debugstr_a(lpszStructType), pvStructInfo, dwFlags, pEncodePara,
     pvEncoded, pcbEncoded);

    if (!pvEncoded && !pcbEncoded)
    {
        SetLastError(ERROR_INVALID_PARAMETER);
        return FALSE;
    }

    SetLastError(NOERROR);
4709 4710 4711 4712 4713
    if (dwFlags & CRYPT_ENCODE_ALLOC_FLAG) {
        if (!pvEncoded) {
            SetLastError(ERROR_INVALID_PARAMETER);
            return FALSE;
        }
4714
        *(BYTE **)pvEncoded = NULL;
4715
    }
4716
    encodeFunc = CRYPT_GetBuiltinEncoder(dwCertEncodingType, lpszStructType);
4717
    if (!encodeFunc)
4718
    {
4719 4720 4721 4722
        TRACE_(crypt)("OID %s not found or unimplemented, looking for DLL\n",
         debugstr_a(lpszStructType));
        encodeFunc = CRYPT_LoadEncoderExFunc(dwCertEncodingType, lpszStructType,
         &hFunc);
4723
    }
4724 4725
    if (encodeFunc)
        ret = encodeFunc(dwCertEncodingType, lpszStructType, pvStructInfo,
4726
         dwFlags, pEncodePara, pvEncoded, pcbEncoded);
4727
    else
4728
    {
4729 4730
        CryptEncodeObjectFunc pCryptEncodeObject =
         CRYPT_LoadEncoderFunc(dwCertEncodingType, lpszStructType, &hFunc);
4731 4732 4733 4734 4735 4736 4737 4738 4739 4740 4741 4742 4743 4744 4745 4746 4747 4748

        if (pCryptEncodeObject)
        {
            if (dwFlags & CRYPT_ENCODE_ALLOC_FLAG)
            {
                ret = pCryptEncodeObject(dwCertEncodingType, lpszStructType,
                 pvStructInfo, NULL, pcbEncoded);
                if (ret && (ret = CRYPT_EncodeEnsureSpace(dwFlags, pEncodePara,
                 pvEncoded, pcbEncoded, *pcbEncoded)))
                    ret = pCryptEncodeObject(dwCertEncodingType,
                     lpszStructType, pvStructInfo, *(BYTE **)pvEncoded,
                     pcbEncoded);
            }
            else
                ret = pCryptEncodeObject(dwCertEncodingType, lpszStructType,
                 pvStructInfo, pvEncoded, pcbEncoded);
        }
    }
4749 4750
    if (hFunc)
        CryptFreeOIDFunctionAddress(hFunc, 0);
4751
    TRACE_(crypt)("returning %d\n", ret);
4752
    return ret;
4753 4754
}

4755
BOOL WINAPI CryptExportPublicKeyInfo(HCRYPTPROV_OR_NCRYPT_KEY_HANDLE hCryptProv, DWORD dwKeySpec,
4756 4757 4758 4759 4760 4761
 DWORD dwCertEncodingType, PCERT_PUBLIC_KEY_INFO pInfo, DWORD *pcbInfo)
{
    return CryptExportPublicKeyInfoEx(hCryptProv, dwKeySpec, dwCertEncodingType,
     NULL, 0, NULL, pInfo, pcbInfo);
}

4762 4763 4764 4765 4766
typedef BOOL (WINAPI *EncodePublicKeyAndParametersFunc)(DWORD dwCertEncodingType,
 LPSTR pszPublicKeyObjId, BYTE *pbPubKey, DWORD cbPubKey, DWORD dwFlags, void *pvAuxInfo,
 BYTE **ppPublicKey, DWORD *pcbPublicKey, BYTE **ppbParams, DWORD *pcbParams);

static BOOL WINAPI CRYPT_ExportPublicKeyInfoEx(HCRYPTPROV_OR_NCRYPT_KEY_HANDLE hCryptProv,
4767 4768
 DWORD dwKeySpec, DWORD dwCertEncodingType, LPSTR pszPublicKeyObjId,
 DWORD dwFlags, void *pvAuxInfo, PCERT_PUBLIC_KEY_INFO pInfo, DWORD *pcbInfo)
4769 4770 4771
{
    BOOL ret;
    HCRYPTKEY key;
4772
    static CHAR rsa_oid[] = szOID_RSA_RSA;
4773

4774
    TRACE_(crypt)("(%08lx, %d, %08x, %s, %08x, %p, %p, %d)\n", hCryptProv,
4775
     dwKeySpec, dwCertEncodingType, debugstr_a(pszPublicKeyObjId), dwFlags,
4776
     pvAuxInfo, pInfo, pInfo ? *pcbInfo : 0);
4777 4778 4779 4780 4781 4782 4783 4784

    if ((ret = CryptGetUserKey(hCryptProv, dwKeySpec, &key)))
    {
        DWORD keySize = 0;

        ret = CryptExportKey(key, 0, PUBLICKEYBLOB, 0, NULL, &keySize);
        if (ret)
        {
4785
            PUBLICKEYSTRUC *pubKey = CryptMemAlloc(keySize);
4786 4787 4788

            if (pubKey)
            {
4789
                ret = CryptExportKey(key, 0, PUBLICKEYBLOB, 0, (BYTE *)pubKey, &keySize);
4790 4791
                if (ret)
                {
4792 4793 4794 4795 4796 4797 4798 4799 4800 4801 4802 4803 4804 4805 4806 4807 4808 4809 4810 4811 4812 4813 4814 4815 4816 4817 4818 4819 4820 4821 4822 4823 4824 4825 4826 4827 4828 4829 4830 4831 4832 4833 4834 4835 4836 4837 4838 4839 4840 4841 4842 4843 4844 4845 4846 4847 4848 4849 4850 4851 4852 4853 4854 4855 4856 4857 4858 4859 4860 4861 4862
                    DWORD encodedLen;

                    if (!pszPublicKeyObjId)
                    {
                        static HCRYPTOIDFUNCSET set;
                        EncodePublicKeyAndParametersFunc encodeFunc = NULL;
                        HCRYPTOIDFUNCADDR hFunc = NULL;

                        pszPublicKeyObjId = (LPSTR)CertAlgIdToOID(pubKey->aiKeyAlg);
                        TRACE("public key algid %#x (%s)\n", pubKey->aiKeyAlg, debugstr_a(pszPublicKeyObjId));

                        if (!set) /* FIXME: there is no a public macro */
                            set = CryptInitOIDFunctionSet("CryptDllEncodePublicKeyAndParameters", 0);

                        CryptGetOIDFunctionAddress(set, dwCertEncodingType, pszPublicKeyObjId, 0, (void **)&encodeFunc, &hFunc);
                        if (encodeFunc)
                        {
                            BYTE *key_data = NULL;
                            DWORD key_size = 0;
                            BYTE *params = NULL;
                            DWORD params_size = 0;

                            ret = encodeFunc(dwCertEncodingType, pszPublicKeyObjId, (BYTE *)pubKey, keySize,
                                             dwFlags, pvAuxInfo, &key_data, &key_size, &params, &params_size);
                            if (ret)
                            {
                                DWORD oid_size = strlen(pszPublicKeyObjId) + 1;
                                DWORD size_needed = sizeof(*pInfo) + oid_size + key_size + params_size;

                                if (!pInfo)
                                    *pcbInfo = size_needed;
                                else if (*pcbInfo < size_needed)
                                {
                                    *pcbInfo = size_needed;
                                    SetLastError(ERROR_MORE_DATA);
                                    ret = FALSE;
                                }
                                else
                                {
                                    *pcbInfo = size_needed;
                                    pInfo->Algorithm.pszObjId = (char *)(pInfo + 1);
                                    lstrcpyA(pInfo->Algorithm.pszObjId, pszPublicKeyObjId);
                                    if (params)
                                    {
                                        pInfo->Algorithm.Parameters.cbData = params_size;
                                        pInfo->Algorithm.Parameters.pbData = (BYTE *)pInfo->Algorithm.pszObjId + oid_size;
                                        memcpy(pInfo->Algorithm.Parameters.pbData, params, params_size);
                                    }
                                    else
                                    {
                                        pInfo->Algorithm.Parameters.cbData = 0;
                                        pInfo->Algorithm.Parameters.pbData = NULL;
                                    }
                                    pInfo->PublicKey.pbData = (BYTE *)pInfo->Algorithm.pszObjId + oid_size + params_size;
                                    pInfo->PublicKey.cbData = key_size;
                                    memcpy(pInfo->PublicKey.pbData, key_data, key_size);
                                    pInfo->PublicKey.cUnusedBits = 0;
                                }

                                CryptMemFree(key_data);
                                CryptMemFree(params);
                            }

                            CryptMemFree(pubKey);
                            CryptFreeOIDFunctionAddress(hFunc, 0);
                            return ret;
                        }

                        /* fallback to RSA */
                        pszPublicKeyObjId = rsa_oid;
                    }
4863

4864
                    encodedLen = 0;
4865
                    ret = CryptEncodeObject(dwCertEncodingType,
4866
                     RSA_CSP_PUBLICKEYBLOB, pubKey, NULL, &encodedLen);
4867 4868 4869 4870 4871 4872 4873 4874 4875 4876 4877 4878 4879 4880 4881
                    if (ret)
                    {
                        DWORD sizeNeeded = sizeof(CERT_PUBLIC_KEY_INFO) +
                         strlen(pszPublicKeyObjId) + 1 + encodedLen;

                        if (!pInfo)
                            *pcbInfo = sizeNeeded;
                        else if (*pcbInfo < sizeNeeded)
                        {
                            SetLastError(ERROR_MORE_DATA);
                            *pcbInfo = sizeNeeded;
                            ret = FALSE;
                        }
                        else
                        {
4882
                            *pcbInfo = sizeNeeded;
4883 4884 4885 4886 4887 4888
                            pInfo->Algorithm.pszObjId = (char *)pInfo +
                             sizeof(CERT_PUBLIC_KEY_INFO);
                            lstrcpyA(pInfo->Algorithm.pszObjId,
                             pszPublicKeyObjId);
                            pInfo->Algorithm.Parameters.cbData = 0;
                            pInfo->Algorithm.Parameters.pbData = NULL;
4889 4890
                            pInfo->PublicKey.pbData =
                             (BYTE *)pInfo->Algorithm.pszObjId
4891 4892 4893 4894
                             + lstrlenA(pInfo->Algorithm.pszObjId) + 1;
                            pInfo->PublicKey.cbData = encodedLen;
                            pInfo->PublicKey.cUnusedBits = 0;
                            ret = CryptEncodeObject(dwCertEncodingType,
4895 4896
                             RSA_CSP_PUBLICKEYBLOB, pubKey,
                             pInfo->PublicKey.pbData, &pInfo->PublicKey.cbData);
4897 4898 4899
                        }
                    }
                }
4900
                CryptMemFree(pubKey);
4901 4902 4903 4904 4905 4906 4907 4908 4909
            }
            else
                ret = FALSE;
        }
        CryptDestroyKey(key);
    }
    return ret;
}

4910
typedef BOOL (WINAPI *ExportPublicKeyInfoExFunc)(HCRYPTPROV_OR_NCRYPT_KEY_HANDLE hCryptProv,
4911 4912 4913
 DWORD dwKeySpec, DWORD dwCertEncodingType, LPSTR pszPublicKeyObjId,
 DWORD dwFlags, void *pvAuxInfo, PCERT_PUBLIC_KEY_INFO pInfo, DWORD *pcbInfo);

4914
BOOL WINAPI CryptExportPublicKeyInfoEx(HCRYPTPROV_OR_NCRYPT_KEY_HANDLE hCryptProv, DWORD dwKeySpec,
4915 4916 4917
 DWORD dwCertEncodingType, LPSTR pszPublicKeyObjId, DWORD dwFlags,
 void *pvAuxInfo, PCERT_PUBLIC_KEY_INFO pInfo, DWORD *pcbInfo)
{
4918
    static HCRYPTOIDFUNCSET set = NULL;
4919 4920
    BOOL ret;
    ExportPublicKeyInfoExFunc exportFunc = NULL;
4921
    HCRYPTOIDFUNCADDR hFunc = NULL;
4922

4923
    TRACE_(crypt)("(%08lx, %d, %08x, %s, %08x, %p, %p, %d)\n", hCryptProv,
4924
     dwKeySpec, dwCertEncodingType, debugstr_a(pszPublicKeyObjId), dwFlags,
4925
     pvAuxInfo, pInfo, pInfo ? *pcbInfo : 0);
4926 4927 4928 4929 4930 4931 4932 4933

    if (!hCryptProv)
    {
        SetLastError(ERROR_INVALID_PARAMETER);
        return FALSE;
    }

    if (pszPublicKeyObjId)
4934 4935 4936 4937 4938 4939 4940
    {
        if (!set)
            set = CryptInitOIDFunctionSet(CRYPT_OID_EXPORT_PUBLIC_KEY_INFO_FUNC,
             0);
        CryptGetOIDFunctionAddress(set, dwCertEncodingType, pszPublicKeyObjId,
         0, (void **)&exportFunc, &hFunc);
    }
4941
    if (!exportFunc)
4942
        exportFunc = CRYPT_ExportPublicKeyInfoEx;
4943 4944
    ret = exportFunc(hCryptProv, dwKeySpec, dwCertEncodingType,
     pszPublicKeyObjId, dwFlags, pvAuxInfo, pInfo, pcbInfo);
4945 4946
    if (hFunc)
        CryptFreeOIDFunctionAddress(hFunc, 0);
4947 4948 4949
    return ret;
}

4950 4951 4952 4953 4954 4955 4956
BOOL WINAPI CryptImportPublicKeyInfo(HCRYPTPROV hCryptProv,
 DWORD dwCertEncodingType, PCERT_PUBLIC_KEY_INFO pInfo, HCRYPTKEY *phKey)
{
    return CryptImportPublicKeyInfoEx(hCryptProv, dwCertEncodingType, pInfo,
     0, 0, NULL, phKey);
}

4957 4958 4959 4960 4961
typedef BOOL (WINAPI *ConvertPublicKeyInfoFunc)(DWORD dwCertEncodingType,
 PCERT_PUBLIC_KEY_INFO pInfo, ALG_ID aiKeyAlg, DWORD dwFlags,
 BYTE **ppbData, DWORD *dwDataLen);

static BOOL WINAPI CRYPT_ImportPublicKeyInfoEx(HCRYPTPROV hCryptProv,
4962 4963 4964
 DWORD dwCertEncodingType, PCERT_PUBLIC_KEY_INFO pInfo, ALG_ID aiKeyAlg,
 DWORD dwFlags, void *pvAuxInfo, HCRYPTKEY *phKey)
{
4965 4966 4967
    static HCRYPTOIDFUNCSET set = NULL;
    ConvertPublicKeyInfoFunc convertFunc = NULL;
    HCRYPTOIDFUNCADDR hFunc = NULL;
4968
    BOOL ret;
4969 4970
    DWORD pubKeySize;
    LPBYTE pubKey;
4971

4972
    TRACE_(crypt)("(%08lx, %08x, %p, %08x, %08x, %p, %p)\n", hCryptProv,
4973 4974
     dwCertEncodingType, pInfo, aiKeyAlg, dwFlags, pvAuxInfo, phKey);

4975 4976 4977 4978 4979 4980 4981 4982 4983 4984 4985 4986 4987 4988 4989 4990 4991 4992 4993
    if (!set)
        set = CryptInitOIDFunctionSet(CRYPT_OID_CONVERT_PUBLIC_KEY_INFO_FUNC, 0);
    CryptGetOIDFunctionAddress(set, dwCertEncodingType, pInfo->Algorithm.pszObjId,
                               0, (void **)&convertFunc, &hFunc);
    if (convertFunc)
    {
        pubKey = NULL;
        pubKeySize = 0;
        ret = convertFunc(dwCertEncodingType, pInfo, aiKeyAlg, dwFlags, &pubKey, &pubKeySize);
        if (ret)
        {
            ret = CryptImportKey(hCryptProv, pubKey, pubKeySize, 0, 0, phKey);
            CryptMemFree(pubKey);
        }

        CryptFreeOIDFunctionAddress(hFunc, 0);
        return ret;
    }

4994
    ret = CryptDecodeObject(dwCertEncodingType, RSA_CSP_PUBLICKEYBLOB,
4995 4996 4997
     pInfo->PublicKey.pbData, pInfo->PublicKey.cbData, 0, NULL, &pubKeySize);
    if (ret)
    {
4998
        pubKey = CryptMemAlloc(pubKeySize);
4999 5000 5001

        if (pubKey)
        {
5002 5003 5004
            ret = CryptDecodeObject(dwCertEncodingType, RSA_CSP_PUBLICKEYBLOB,
             pInfo->PublicKey.pbData, pInfo->PublicKey.cbData, 0, pubKey,
             &pubKeySize);
5005
            if (ret)
5006 5007 5008
            {
                if(aiKeyAlg)
                  ((BLOBHEADER*)pubKey)->aiKeyAlg = aiKeyAlg;
5009 5010
                ret = CryptImportKey(hCryptProv, pubKey, pubKeySize, 0, 0,
                 phKey);
5011
            }
5012
            CryptMemFree(pubKey);
5013 5014 5015 5016 5017 5018
        }
        else
            ret = FALSE;
    }
    return ret;
}
5019 5020 5021 5022 5023 5024 5025 5026 5027

typedef BOOL (WINAPI *ImportPublicKeyInfoExFunc)(HCRYPTPROV hCryptProv,
 DWORD dwCertEncodingType, PCERT_PUBLIC_KEY_INFO pInfo, ALG_ID aiKeyAlg,
 DWORD dwFlags, void *pvAuxInfo, HCRYPTKEY *phKey);

BOOL WINAPI CryptImportPublicKeyInfoEx(HCRYPTPROV hCryptProv,
 DWORD dwCertEncodingType, PCERT_PUBLIC_KEY_INFO pInfo, ALG_ID aiKeyAlg,
 DWORD dwFlags, void *pvAuxInfo, HCRYPTKEY *phKey)
{
5028
    static HCRYPTOIDFUNCSET set = NULL;
5029 5030
    BOOL ret;
    ImportPublicKeyInfoExFunc importFunc = NULL;
5031
    HCRYPTOIDFUNCADDR hFunc = NULL;
5032

5033
    TRACE_(crypt)("(%08lx, %08x, %p, %08x, %08x, %p, %p)\n", hCryptProv,
5034 5035
     dwCertEncodingType, pInfo, aiKeyAlg, dwFlags, pvAuxInfo, phKey);

5036 5037 5038 5039
    if (!set)
        set = CryptInitOIDFunctionSet(CRYPT_OID_IMPORT_PUBLIC_KEY_INFO_FUNC, 0);
    CryptGetOIDFunctionAddress(set, dwCertEncodingType,
     pInfo->Algorithm.pszObjId, 0, (void **)&importFunc, &hFunc);
5040
    if (!importFunc)
5041
        importFunc = CRYPT_ImportPublicKeyInfoEx;
5042 5043
    ret = importFunc(hCryptProv, dwCertEncodingType, pInfo, aiKeyAlg, dwFlags,
     pvAuxInfo, phKey);
5044 5045
    if (hFunc)
        CryptFreeOIDFunctionAddress(hFunc, 0);
5046 5047
    return ret;
}
5048 5049 5050 5051 5052 5053 5054 5055 5056 5057

BOOL WINAPI CryptImportPublicKeyInfoEx2(DWORD dwCertEncodingType,
 PCERT_PUBLIC_KEY_INFO pInfo, DWORD dwFlags, void *pvAuxInfo,
 BCRYPT_KEY_HANDLE *phKey)
{
    FIXME_(crypt)("(%d, %p, %08x, %p, %p): stub\n", dwCertEncodingType, pInfo,
     dwFlags, pvAuxInfo, phKey);
    SetLastError(ERROR_FILE_NOT_FOUND);
    return FALSE;
}