- implement encoding and decoding of enumerated types, unsigned
[wine] / dlls / crypt32 / encode.c
1 /*
2  * Copyright 2002 Mike McCormack for CodeWeavers
3  * Copyright 2005 Juan Lang
4  *
5  * This library is free software; you can redistribute it and/or
6  * modify it under the terms of the GNU Lesser General Public
7  * License as published by the Free Software Foundation; either
8  * version 2.1 of the License, or (at your option) any later version.
9  *
10  * This library is distributed in the hope that it will be useful,
11  * but WITHOUT ANY WARRANTY; without even the implied warranty of
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
13  * Lesser General Public License for more details.
14  *
15  * You should have received a copy of the GNU Lesser General Public
16  * License along with this library; if not, write to the Free Software
17  * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
18  */
19 #include <stdarg.h>
20 #include <stdio.h>
21 #include <stdlib.h>
22 #include "windef.h"
23 #include "winbase.h"
24 #include "wincrypt.h"
25 #include "winreg.h"
26 #include "snmp.h"
27 #include "wine/debug.h"
28
29 /* a few asn.1 tags we need */
30 #define ASN_BITSTRING       (ASN_UNIVERSAL | ASN_PRIMITIVE | 0x03)
31 #define ASN_OCTETSTRING     (ASN_UNIVERSAL | ASN_PRIMITIVE | 0x04)
32 #define ASN_ENUMERATED      (ASN_UNIVERSAL | ASN_PRIMITIVE | 0x0a)
33 #define ASN_SETOF           (ASN_UNIVERSAL | ASN_PRIMITIVE | 0x11)
34 #define ASN_NUMERICSTRING   (ASN_UNIVERSAL | ASN_PRIMITIVE | 0x12)
35 #define ASN_PRINTABLESTRING (ASN_UNIVERSAL | ASN_PRIMITIVE | 0x13)
36 #define ASN_IA5STRING       (ASN_UNIVERSAL | ASN_PRIMITIVE | 0x16)
37 #define ASN_UTCTIME         (ASN_UNIVERSAL | ASN_PRIMITIVE | 0x17)
38 #define ASN_GENERALTIME     (ASN_UNIVERSAL | ASN_PRIMITIVE | 0x18)
39
40 WINE_DEFAULT_DEBUG_CHANNEL(crypt);
41
42 static const WCHAR szDllName[] = { 'D','l','l',0 };
43
44 static char *CRYPT_GetKeyName(DWORD dwEncodingType, LPCSTR pszFuncName,
45  LPCSTR pszOID)
46 {
47     static const char szEncodingTypeFmt[] =
48      "Software\\Microsoft\\Cryptography\\OID\\EncodingType %ld\\%s\\%s";
49     UINT len;
50     char numericOID[7]; /* enough for "#65535" */
51     const char *oid;
52     LPSTR szKey;
53
54     /* MSDN says the encoding type is a mask, but it isn't treated that way.
55      * (E.g., if dwEncodingType were 3, the key names "EncodingType 1" and
56      * "EncodingType 2" would be expected if it were a mask.  Instead native
57      * stores values in "EncodingType 3".
58      */
59     if (!HIWORD(pszOID))
60     {
61         snprintf(numericOID, sizeof(numericOID), "#%d", (int)pszOID);
62         oid = numericOID;
63     }
64     else
65         oid = pszOID;
66
67     /* This is enough: the lengths of the two string parameters are explicitly
68      * counted, and we need up to five additional characters for the encoding
69      * type.  These are covered by the "%d", "%s", and "%s" characters in the
70      * format specifier that are removed by sprintf.
71      */
72     len = sizeof(szEncodingTypeFmt) + lstrlenA(pszFuncName) + lstrlenA(oid);
73     szKey = HeapAlloc(GetProcessHeap(), 0, len);
74     if (szKey)
75         sprintf(szKey, szEncodingTypeFmt, dwEncodingType, pszFuncName, oid);
76     return szKey;
77 }
78
79 BOOL WINAPI CryptRegisterOIDFunction(DWORD dwEncodingType, LPCSTR pszFuncName,
80                   LPCSTR pszOID, LPCWSTR pwszDll, LPCSTR pszOverrideFuncName)
81 {
82     LONG r;
83     HKEY hKey;
84     LPSTR szKey;
85
86     TRACE("%lx %s %s %s %s\n", dwEncodingType, pszFuncName, pszOID,
87           debugstr_w(pwszDll), pszOverrideFuncName);
88
89     /* This only registers functions for encoding certs, not messages */
90     if (!GET_CERT_ENCODING_TYPE(dwEncodingType))
91         return TRUE;
92
93     /* Native does nothing pwszDll is NULL */
94     if (!pwszDll)
95         return TRUE;
96
97     /* I'm not matching MS bug for bug here, because I doubt any app depends on
98      * it:
99      * - native "succeeds" if pszFuncName is NULL, but the nonsensical entry
100      *   it creates would never be used
101      * - native returns an HRESULT rather than a Win32 error if pszOID is NULL.
102      * Instead I disallow both of these with ERROR_INVALID_PARAMETER.
103      */
104     if (!pszFuncName || !pszOID)
105     {
106         SetLastError(ERROR_INVALID_PARAMETER);
107         return FALSE;
108     }
109
110     szKey = CRYPT_GetKeyName(dwEncodingType, pszFuncName, pszOID);
111     TRACE("Key name is %s\n", debugstr_a(szKey));
112
113     if (!szKey)
114         return FALSE;
115
116     r = RegCreateKeyA(HKEY_LOCAL_MACHINE, szKey, &hKey);
117     HeapFree(GetProcessHeap(), 0, szKey);
118     if(r != ERROR_SUCCESS)
119         return FALSE;
120
121     /* write the values */
122     if (pszOverrideFuncName)
123         RegSetValueExA(hKey, "FuncName", 0, REG_SZ, pszOverrideFuncName,
124          lstrlenA(pszOverrideFuncName) + 1);
125     RegSetValueExW(hKey, szDllName, 0, REG_SZ, (const BYTE*) pwszDll,
126                     (lstrlenW(pwszDll) + 1) * sizeof (WCHAR));
127
128     RegCloseKey(hKey);
129     return TRUE;
130 }
131
132 BOOL WINAPI CryptUnregisterOIDFunction(DWORD dwEncodingType, LPCSTR pszFuncName,
133  LPCSTR pszOID)
134 {
135     LPSTR szKey;
136     LONG rc;
137
138     TRACE("%lx %s %s\n", dwEncodingType, pszFuncName, pszOID);
139
140     if (!GET_CERT_ENCODING_TYPE(dwEncodingType))
141         return TRUE;
142
143     if (!pszFuncName || !pszOID)
144     {
145         SetLastError(ERROR_INVALID_PARAMETER);
146         return FALSE;
147     }
148
149     szKey = CRYPT_GetKeyName(dwEncodingType, pszFuncName, pszOID);
150     rc = RegDeleteKeyA(HKEY_LOCAL_MACHINE, szKey);
151     HeapFree(GetProcessHeap(), 0, szKey);
152     if (rc)
153         SetLastError(rc);
154     return rc ? FALSE : TRUE;
155 }
156
157 BOOL WINAPI CryptGetOIDFunctionValue(DWORD dwEncodingType, LPCSTR pszFuncName,
158  LPCSTR pszOID, LPCWSTR pwszValueName, DWORD *pdwValueType, BYTE *pbValueData,
159  DWORD *pcbValueData)
160 {
161     LPSTR szKey;
162     LONG rc;
163     HKEY hKey;
164
165     TRACE("%lx %s %s %s %p %p %p\n", dwEncodingType, debugstr_a(pszFuncName),
166      debugstr_a(pszOID), debugstr_w(pwszValueName), pdwValueType, pbValueData,
167      pcbValueData);
168
169     if (!GET_CERT_ENCODING_TYPE(dwEncodingType))
170         return TRUE;
171
172     if (!pszFuncName || !pszOID || !pwszValueName)
173     {
174         SetLastError(ERROR_INVALID_PARAMETER);
175         return FALSE;
176     }
177
178     szKey = CRYPT_GetKeyName(dwEncodingType, pszFuncName, pszOID);
179     rc = RegOpenKeyA(HKEY_LOCAL_MACHINE, szKey, &hKey);
180     HeapFree(GetProcessHeap(), 0, szKey);
181     if (rc)
182         SetLastError(rc);
183     else
184     {
185         rc = RegQueryValueExW(hKey, pwszValueName, NULL, pdwValueType,
186          pbValueData, pcbValueData);
187         if (rc)
188             SetLastError(rc);
189         RegCloseKey(hKey);
190     }
191     return rc ? FALSE : TRUE;
192 }
193
194 BOOL WINAPI CryptSetOIDFunctionValue(DWORD dwEncodingType, LPCSTR pszFuncName,
195  LPCSTR pszOID, LPCWSTR pwszValueName, DWORD dwValueType,
196  const BYTE *pbValueData, DWORD cbValueData)
197 {
198     LPSTR szKey;
199     LONG rc;
200     HKEY hKey;
201
202     TRACE("%lx %s %s %s %ld %p %ld\n", dwEncodingType, debugstr_a(pszFuncName),
203      debugstr_a(pszOID), debugstr_w(pwszValueName), dwValueType, pbValueData,
204      cbValueData);
205
206     if (!GET_CERT_ENCODING_TYPE(dwEncodingType))
207         return TRUE;
208
209     if (!pszFuncName || !pszOID || !pwszValueName)
210     {
211         SetLastError(ERROR_INVALID_PARAMETER);
212         return FALSE;
213     }
214
215     szKey = CRYPT_GetKeyName(dwEncodingType, pszFuncName, pszOID);
216     rc = RegOpenKeyA(HKEY_LOCAL_MACHINE, szKey, &hKey);
217     HeapFree(GetProcessHeap(), 0, szKey);
218     if (rc)
219         SetLastError(rc);
220     else
221     {
222         rc = RegSetValueExW(hKey, pwszValueName, 0, dwValueType, pbValueData,
223          cbValueData);
224         if (rc)
225             SetLastError(rc);
226         RegCloseKey(hKey);
227     }
228     return rc ? FALSE : TRUE;
229 }
230
231 /* Gets the registered function named szFuncName for dwCertEncodingType and
232  * lpszStructType, or NULL if one could not be found.  *lib will be set to the
233  * handle of the module it's in, or NULL if no module was loaded.  If the
234  * return value is NULL, *lib will also be NULL, to simplify error handling.
235  */
236 static void *CRYPT_GetFunc(DWORD dwCertEncodingType, LPCSTR lpszStructType,
237  LPCSTR szFuncName, HMODULE *lib)
238 {
239     void *ret = NULL;
240     char *szKey = CRYPT_GetKeyName(dwCertEncodingType, szFuncName,
241      lpszStructType);
242     const char *funcName;
243     long r;
244     HKEY hKey;
245     DWORD type, size = 0;
246
247     *lib = NULL;
248     r = RegOpenKeyA(HKEY_LOCAL_MACHINE, szKey, &hKey);
249     HeapFree(GetProcessHeap(), 0, szKey);
250     if(r != ERROR_SUCCESS)
251         return NULL;
252
253     RegQueryValueExA(hKey, "FuncName", NULL, &type, NULL, &size);
254     if (GetLastError() == ERROR_MORE_DATA && type == REG_SZ)
255     {
256         funcName = HeapAlloc(GetProcessHeap(), 0, size);
257         RegQueryValueExA(hKey, "FuncName", NULL, &type, (LPBYTE)funcName,
258          &size);
259     }
260     else
261         funcName = szFuncName;
262     RegQueryValueExW(hKey, szDllName, NULL, &type, NULL, &size);
263     if (GetLastError() == ERROR_MORE_DATA && type == REG_SZ)
264     {
265         LPWSTR dllName = HeapAlloc(GetProcessHeap(), 0, size);
266
267         RegQueryValueExW(hKey, szDllName, NULL, &type, (LPBYTE)dllName,
268          &size);
269         *lib = LoadLibraryW(dllName);
270         if (*lib)
271         {
272              ret = GetProcAddress(*lib, funcName);
273              if (!ret)
274              {
275                  /* Unload the library, the caller doesn't want to unload it
276                   * when the return value is NULL.
277                   */
278                  FreeLibrary(*lib);
279                  *lib = NULL;
280              }
281         }
282         HeapFree(GetProcessHeap(), 0, dllName);
283     }
284     if (funcName != szFuncName)
285         HeapFree(GetProcessHeap(), 0, (char *)funcName);
286     return ret;
287 }
288
289 typedef BOOL (WINAPI *CryptEncodeObjectFunc)(DWORD, LPCSTR, const void *,
290  BYTE *, DWORD *);
291
292 BOOL WINAPI CryptEncodeObject(DWORD dwCertEncodingType, LPCSTR lpszStructType,
293  const void *pvStructInfo, BYTE *pbEncoded, DWORD *pcbEncoded)
294 {
295     BOOL ret = FALSE;
296     HMODULE lib;
297     CryptEncodeObjectFunc pCryptEncodeObject;
298
299     TRACE("(0x%08lx, %s, %p, %p, %p)\n",
300      dwCertEncodingType, HIWORD(lpszStructType) ? debugstr_a(lpszStructType) :
301      "(integer value)", pvStructInfo, pbEncoded, pcbEncoded);
302
303     if (!pbEncoded && !pcbEncoded)
304     {
305         SetLastError(ERROR_INVALID_PARAMETER);
306         return FALSE;
307     }
308
309     /* Try registered DLL first.. */
310     pCryptEncodeObject =
311      (CryptEncodeObjectFunc)CRYPT_GetFunc(dwCertEncodingType,
312      lpszStructType, "CryptEncodeObject", &lib);
313     if (pCryptEncodeObject)
314     {
315         ret = pCryptEncodeObject(dwCertEncodingType, lpszStructType,
316          pvStructInfo, pbEncoded, pcbEncoded);
317         FreeLibrary(lib);
318     }
319     else
320     {
321         /* If not, use CryptEncodeObjectEx */
322         ret = CryptEncodeObjectEx(dwCertEncodingType, lpszStructType,
323          pvStructInfo, 0, NULL, pbEncoded, pcbEncoded);
324     }
325     return ret;
326 }
327
328 /* Helper function to check *pcbEncoded, set it to the required size, and
329  * optionally to allocate memory.  Assumes pbEncoded is not NULL.
330  * If CRYPT_ENCODE_ALLOC_FLAG is set in dwFlags, *pbEncoded will be set to a
331  * pointer to the newly allocated memory.
332  */
333 static BOOL CRYPT_EncodeEnsureSpace(DWORD dwFlags,
334  PCRYPT_ENCODE_PARA pEncodePara, BYTE *pbEncoded, DWORD *pcbEncoded,
335  DWORD bytesNeeded)
336 {
337     BOOL ret = TRUE;
338
339     if (dwFlags & CRYPT_ENCODE_ALLOC_FLAG)
340     {
341         if (pEncodePara && pEncodePara->pfnAlloc)
342             *(BYTE **)pbEncoded = pEncodePara->pfnAlloc(bytesNeeded);
343         else
344             *(BYTE **)pbEncoded = LocalAlloc(0, bytesNeeded);
345         if (!*(BYTE **)pbEncoded)
346             ret = FALSE;
347         else
348             *pcbEncoded = bytesNeeded;
349     }
350     else if (bytesNeeded > *pcbEncoded)
351     {
352         *pcbEncoded = bytesNeeded;
353         SetLastError(ERROR_MORE_DATA);
354         ret = FALSE;
355     }
356     return ret;
357 }
358
359 static BOOL CRYPT_EncodeLen(DWORD len, BYTE *pbEncoded, DWORD *pcbEncoded)
360 {
361     DWORD bytesNeeded, significantBytes = 0;
362
363     if (len <= 0x7f)
364         bytesNeeded = 1;
365     else
366     {
367         DWORD temp;
368
369         for (temp = len, significantBytes = sizeof(temp); !(temp & 0xff000000);
370          temp <<= 8, significantBytes--)
371             ;
372         bytesNeeded = significantBytes + 1;
373     }
374     if (!pbEncoded)
375     {
376         *pcbEncoded = bytesNeeded;
377         return TRUE;
378     }
379     if (*pcbEncoded < bytesNeeded)
380     {
381         SetLastError(ERROR_MORE_DATA);
382         return FALSE;
383     }
384     if (len <= 0x7f)
385         *pbEncoded = (BYTE)len;
386     else
387     {
388         DWORD i;
389
390         *pbEncoded++ = significantBytes | 0x80;
391         for (i = 0; i < significantBytes; i++)
392         {
393             *(pbEncoded + significantBytes - i - 1) = (BYTE)(len & 0xff);
394             len >>= 8;
395         }
396     }
397     *pcbEncoded = bytesNeeded;
398     return TRUE;
399 }
400
401 static BOOL WINAPI CRYPT_AsnEncodeOid(DWORD dwCertEncodingType,
402  LPCSTR pszObjId, BYTE *pbEncoded, DWORD *pcbEncoded)
403 {
404     DWORD bytesNeeded = 0, lenBytes;
405     BOOL ret = TRUE;
406     int firstPos = 0;
407     BYTE firstByte = 0;
408
409     if (pszObjId)
410     {
411         const char *ptr;
412         int val1, val2;
413
414         if (sscanf(pszObjId, "%d.%d.%n", &val1, &val2, &firstPos) != 2)
415         {
416             SetLastError(CRYPT_E_ASN1_ERROR);
417             return FALSE;
418         }
419         bytesNeeded++;
420         firstByte = val1 * 40 + val2;
421         ptr = pszObjId + firstPos;
422         while (ret && *ptr)
423         {
424             int pos;
425
426             /* note I assume each component is at most 32-bits long in base 2 */
427             if (sscanf(ptr, "%d%n", &val1, &pos) == 1)
428             {
429                 if (val1 >= 0x10000000)
430                     bytesNeeded += 5;
431                 else if (val1 >= 0x200000)
432                     bytesNeeded += 4;
433                 else if (val1 >= 0x4000)
434                     bytesNeeded += 3;
435                 else if (val1 >= 0x80)
436                     bytesNeeded += 2;
437                 else
438                     bytesNeeded += 1;
439                 ptr += pos;
440                 if (*ptr == '.')
441                     ptr++;
442             }
443             else
444             {
445                 SetLastError(CRYPT_E_ASN1_ERROR);
446                 return FALSE;
447             }
448         }
449         CRYPT_EncodeLen(bytesNeeded, NULL, &lenBytes);
450     }
451     else
452         lenBytes = 1;
453     bytesNeeded += 1 + lenBytes;
454     if (pbEncoded)
455     {
456         if (*pbEncoded < bytesNeeded)
457         {
458             SetLastError(ERROR_MORE_DATA);
459             ret = FALSE;
460         }
461         else
462         {
463             *pbEncoded++ = ASN_OBJECTIDENTIFIER;
464             CRYPT_EncodeLen(bytesNeeded - 1 - lenBytes, pbEncoded, &lenBytes);
465             pbEncoded += lenBytes;
466             if (pszObjId)
467             {
468                 const char *ptr;
469                 int val, pos;
470
471                 *pbEncoded++ = firstByte;
472                 ptr = pszObjId + firstPos;
473                 while (ret && *ptr)
474                 {
475                     sscanf(ptr, "%d%n", &val, &pos);
476                     {
477                         unsigned char outBytes[5];
478                         int numBytes, i;
479
480                         if (val >= 0x10000000)
481                             numBytes = 5;
482                         else if (val >= 0x200000)
483                             numBytes = 4;
484                         else if (val >= 0x4000)
485                             numBytes = 3;
486                         else if (val >= 0x80)
487                             numBytes = 2;
488                         else
489                             numBytes = 1;
490                         for (i = numBytes; i > 0; i--)
491                         {
492                             outBytes[i - 1] = val & 0x7f;
493                             val >>= 7;
494                         }
495                         for (i = 0; i < numBytes - 1; i++)
496                             *pbEncoded++ = outBytes[i] | 0x80;
497                         *pbEncoded++ = outBytes[i];
498                         ptr += pos;
499                         if (*ptr == '.')
500                             ptr++;
501                     }
502                 }
503             }
504         }
505     }
506     *pcbEncoded = bytesNeeded;
507     return ret;
508 }
509
510 static BOOL WINAPI CRYPT_AsnEncodeNameValue(DWORD dwCertEncodingType,
511  CERT_NAME_VALUE *value, BYTE *pbEncoded, DWORD *pcbEncoded)
512 {
513     BYTE tag;
514     DWORD bytesNeeded, lenBytes, encodedLen;
515     BOOL ret = TRUE;
516
517     switch (value->dwValueType)
518     {
519     case CERT_RDN_NUMERIC_STRING:
520         tag = ASN_NUMERICSTRING;
521         encodedLen = value->Value.cbData;
522         break;
523     case CERT_RDN_PRINTABLE_STRING:
524         tag = ASN_PRINTABLESTRING;
525         encodedLen = value->Value.cbData;
526         break;
527     case CERT_RDN_IA5_STRING:
528         tag = ASN_IA5STRING;
529         encodedLen = value->Value.cbData;
530         break;
531     case CERT_RDN_ANY_TYPE:
532         /* explicitly disallowed */
533         SetLastError(HRESULT_FROM_WIN32(ERROR_INVALID_PARAMETER));
534         return FALSE;
535     default:
536         FIXME("String type %ld unimplemented\n", value->dwValueType);
537         return FALSE;
538     }
539     CRYPT_EncodeLen(encodedLen, NULL, &lenBytes);
540     bytesNeeded = 1 + lenBytes + encodedLen;
541     if (pbEncoded)
542     {
543         if (*pcbEncoded < bytesNeeded)
544         {
545             SetLastError(ERROR_MORE_DATA);
546             ret = FALSE;
547         }
548         else
549         {
550             *pbEncoded++ = tag;
551             CRYPT_EncodeLen(encodedLen, pbEncoded, &lenBytes);
552             pbEncoded += lenBytes;
553             switch (value->dwValueType)
554             {
555             case CERT_RDN_NUMERIC_STRING:
556             case CERT_RDN_PRINTABLE_STRING:
557             case CERT_RDN_IA5_STRING:
558                 memcpy(pbEncoded, value->Value.pbData, value->Value.cbData);
559             }
560         }
561     }
562     *pcbEncoded = bytesNeeded;
563     return ret;
564 }
565
566 static BOOL WINAPI CRYPT_AsnEncodeRdnAttr(DWORD dwCertEncodingType,
567  CERT_RDN_ATTR *attr, BYTE *pbEncoded, DWORD *pcbEncoded)
568 {
569     DWORD bytesNeeded = 0, lenBytes, size;
570     BOOL ret;
571
572     ret = CRYPT_AsnEncodeOid(dwCertEncodingType, attr->pszObjId, NULL, &size);
573     if (ret)
574     {
575         bytesNeeded += size;
576         /* hack: a CERT_RDN_ATTR is identical to a CERT_NAME_VALUE beginning
577          * with dwValueType, so "cast" it to get its encoded size
578          */
579         ret = CRYPT_AsnEncodeNameValue(dwCertEncodingType,
580          (CERT_NAME_VALUE *)&attr->dwValueType, NULL, &size);
581         if (ret)
582         {
583             bytesNeeded += size;
584             CRYPT_EncodeLen(bytesNeeded, NULL, &lenBytes);
585             bytesNeeded += 1 + lenBytes;
586             if (pbEncoded)
587             {
588                 if (*pcbEncoded < bytesNeeded)
589                 {
590                     SetLastError(ERROR_MORE_DATA);
591                     ret = FALSE;
592                 }
593                 else
594                 {
595                     *pbEncoded++ = ASN_CONSTRUCTOR | ASN_SEQUENCE;
596                     CRYPT_EncodeLen(bytesNeeded - lenBytes - 1, pbEncoded,
597                      &lenBytes);
598                     pbEncoded += lenBytes;
599                     size = bytesNeeded - 1 - lenBytes;
600                     ret = CRYPT_AsnEncodeOid(dwCertEncodingType, attr->pszObjId,
601                      pbEncoded, &size);
602                     if (ret)
603                     {
604                         pbEncoded += size;
605                         size = bytesNeeded - 1 - lenBytes - size;
606                         ret = CRYPT_AsnEncodeNameValue(dwCertEncodingType,
607                          (CERT_NAME_VALUE *)&attr->dwValueType, pbEncoded,
608                          &size);
609                     }
610                 }
611             }
612             *pcbEncoded = bytesNeeded;
613         }
614     }
615     return ret;
616 }
617
618 static int BLOBComp(const void *l, const void *r)
619 {
620     CRYPT_DER_BLOB *a = (CRYPT_DER_BLOB *)l, *b = (CRYPT_DER_BLOB *)r;
621     int ret;
622
623     if (!(ret = memcmp(a->pbData, b->pbData, min(a->cbData, b->cbData))))
624         ret = a->cbData - b->cbData;
625     return ret;
626 }
627
628 /* This encodes as a SET OF, which in DER must be lexicographically sorted.
629  */
630 static BOOL WINAPI CRYPT_AsnEncodeRdn(DWORD dwCertEncodingType, CERT_RDN *rdn,
631  BYTE *pbEncoded, DWORD *pcbEncoded)
632 {
633     DWORD bytesNeeded = 0, lenBytes, i;
634     BOOL ret;
635     CRYPT_DER_BLOB *blobs = NULL;
636    
637     ret = TRUE;
638     if (rdn->cRDNAttr)
639     {
640         if (!rdn->rgRDNAttr)
641         {
642             SetLastError(STATUS_ACCESS_VIOLATION);
643             ret = FALSE;
644         }
645         else
646         {
647             blobs = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY,
648              rdn->cRDNAttr * sizeof(CRYPT_DER_BLOB));
649             if (!blobs)
650                 ret = FALSE;
651         }
652     }
653     for (i = 0; ret && i < rdn->cRDNAttr; i++)
654     {
655         ret = CRYPT_AsnEncodeRdnAttr(dwCertEncodingType, &rdn->rgRDNAttr[i],
656          NULL, &blobs[i].cbData);
657         if (ret)
658             bytesNeeded += blobs[i].cbData;
659     }
660     CRYPT_EncodeLen(bytesNeeded, NULL, &lenBytes);
661     bytesNeeded += 1 + lenBytes;
662     if (ret)
663     {
664         if (pbEncoded)
665         {
666             if (*pcbEncoded < bytesNeeded)
667             {
668                 SetLastError(ERROR_MORE_DATA);
669                 ret = FALSE;
670             }
671             else
672             {
673                 for (i = 0; ret && i < rdn->cRDNAttr; i++)
674                 {
675                     blobs[i].pbData = HeapAlloc(GetProcessHeap(), 0,
676                      blobs[i].cbData);
677                     if (!blobs[i].pbData)
678                         ret = FALSE;
679                     else
680                         ret = CRYPT_AsnEncodeRdnAttr(dwCertEncodingType,
681                          &rdn->rgRDNAttr[i], blobs[i].pbData, &blobs[i].cbData);
682                 }
683                 if (ret)
684                 {
685                     qsort(blobs, rdn->cRDNAttr, sizeof(CRYPT_DER_BLOB),
686                      BLOBComp);
687                     *pbEncoded++ = ASN_CONSTRUCTOR | ASN_SETOF;
688                     CRYPT_EncodeLen(bytesNeeded - lenBytes - 1, pbEncoded,
689                      &lenBytes);
690                     pbEncoded += lenBytes;
691                     for (i = 0; ret && i < rdn->cRDNAttr; i++)
692                     {
693                         memcpy(pbEncoded, blobs[i].pbData, blobs[i].cbData);
694                         pbEncoded += blobs[i].cbData;
695                     }
696                 }
697             }
698         }
699         *pcbEncoded = bytesNeeded;
700     }
701     if (blobs)
702     {
703         for (i = 0; i < rdn->cRDNAttr; i++)
704             HeapFree(GetProcessHeap(), 0, blobs[i].pbData);
705         HeapFree(GetProcessHeap(), 0, blobs);
706     }
707     return ret;
708 }
709
710 static BOOL WINAPI CRYPT_AsnEncodeName(DWORD dwCertEncodingType,
711  LPCSTR lpszStructType, const void *pvStructInfo, DWORD dwFlags,
712  PCRYPT_ENCODE_PARA pEncodePara, BYTE *pbEncoded, DWORD *pcbEncoded)
713 {
714     CERT_NAME_INFO *info = (CERT_NAME_INFO *)pvStructInfo;
715     DWORD bytesNeeded = 0, lenBytes, size, i;
716     BOOL ret;
717
718     if (!pvStructInfo)
719     {
720         SetLastError(STATUS_ACCESS_VIOLATION);
721         return FALSE;
722     }
723     if (info->cRDN && !info->rgRDN)
724     {
725         SetLastError(STATUS_ACCESS_VIOLATION);
726         return FALSE;
727     }
728     TRACE("encoding name with %ld RDNs\n", info->cRDN);
729     ret = TRUE;
730     for (i = 0; ret && i < info->cRDN; i++)
731     {
732         ret = CRYPT_AsnEncodeRdn(dwCertEncodingType, &info->rgRDN[i], NULL,
733          &size);
734         if (ret)
735             bytesNeeded += size;
736     }
737     CRYPT_EncodeLen(bytesNeeded, NULL, &lenBytes);
738     bytesNeeded += 1 + lenBytes;
739     if (ret)
740     {
741         if (!pbEncoded)
742         {
743             *pcbEncoded = bytesNeeded;
744             return TRUE;
745         }
746         if (!CRYPT_EncodeEnsureSpace(dwFlags, pEncodePara, pbEncoded,
747          pcbEncoded, bytesNeeded))
748             return FALSE;
749         if (dwFlags & CRYPT_ENCODE_ALLOC_FLAG)
750             pbEncoded = *(BYTE **)pbEncoded;
751         *pbEncoded++ = ASN_CONSTRUCTOR | ASN_SEQUENCE;
752         CRYPT_EncodeLen(bytesNeeded - lenBytes - 1, pbEncoded, &size);
753         pbEncoded += size;
754         for (i = 0; ret && i < info->cRDN; i++)
755         {
756             size = bytesNeeded;
757             ret = CRYPT_AsnEncodeRdn(dwCertEncodingType, &info->rgRDN[i],
758              pbEncoded, &size);
759             if (ret)
760             {
761                 pbEncoded += size;
762                 bytesNeeded -= size;
763             }
764         }
765     }
766     return ret;
767 }
768
769 static BOOL WINAPI CRYPT_AsnEncodeOctets(DWORD dwCertEncodingType,
770  LPCSTR lpszStructType, const void *pvStructInfo, DWORD dwFlags,
771  PCRYPT_ENCODE_PARA pEncodePara, BYTE *pbEncoded, DWORD *pcbEncoded)
772 {
773     CRYPT_DATA_BLOB *blob = (CRYPT_DATA_BLOB *)pvStructInfo;
774     DWORD bytesNeeded, lenBytes;
775
776     if (!pvStructInfo)
777     {
778         SetLastError(STATUS_ACCESS_VIOLATION);
779         return FALSE;
780     }
781     /* FIXME: use exception handling to catch bogus pointers */
782     CRYPT_EncodeLen(blob->cbData, NULL, &lenBytes);
783     bytesNeeded = 1 + lenBytes + blob->cbData;
784     if (!pbEncoded)
785     {
786         *pcbEncoded = bytesNeeded;
787         return TRUE;
788     }
789     if (!CRYPT_EncodeEnsureSpace(dwFlags, pEncodePara, pbEncoded, pcbEncoded,
790      bytesNeeded))
791         return FALSE;
792     if (dwFlags & CRYPT_ENCODE_ALLOC_FLAG)
793         pbEncoded = *(BYTE **)pbEncoded;
794     *pbEncoded++ = ASN_OCTETSTRING;
795     CRYPT_EncodeLen(blob->cbData, pbEncoded, &lenBytes);
796     pbEncoded += lenBytes;
797     if (blob->cbData)
798         memcpy(pbEncoded, blob->pbData, blob->cbData);
799     return TRUE;
800 }
801
802 static BOOL WINAPI CRYPT_AsnEncodeBits(DWORD dwCertEncodingType,
803  LPCSTR lpszStructType, const void *pvStructInfo, DWORD dwFlags,
804  PCRYPT_ENCODE_PARA pEncodePara, BYTE *pbEncoded, DWORD *pcbEncoded)
805 {
806     CRYPT_BIT_BLOB *blob = (CRYPT_BIT_BLOB *)pvStructInfo;
807     DWORD bytesNeeded, lenBytes, dataBytes;
808     BYTE unusedBits;
809
810     if (!pvStructInfo)
811     {
812         SetLastError(STATUS_ACCESS_VIOLATION);
813         return FALSE;
814     }
815     /* FIXME: use exception handling to catch bogus pointers */
816     /* yep, MS allows cUnusedBits to be >= 8 */
817     if (blob->cbData * 8 > blob->cUnusedBits)
818     {
819         dataBytes = (blob->cbData * 8 - blob->cUnusedBits) / 8 + 1;
820         unusedBits = blob->cUnusedBits >= 8 ? blob->cUnusedBits / 8 :
821          blob->cUnusedBits;
822     }
823     else
824     {
825         dataBytes = 0;
826         unusedBits = 0;
827     }
828     CRYPT_EncodeLen(dataBytes + 1, NULL, &lenBytes);
829     bytesNeeded = 1 + lenBytes + dataBytes + 1;
830     if (!pbEncoded)
831     {
832         *pcbEncoded = bytesNeeded;
833         return TRUE;
834     }
835     if (!CRYPT_EncodeEnsureSpace(dwFlags, pEncodePara, pbEncoded, pcbEncoded,
836      bytesNeeded))
837         return FALSE;
838     if (dwFlags & CRYPT_ENCODE_ALLOC_FLAG)
839         pbEncoded = *(BYTE **)pbEncoded;
840     *pbEncoded++ = ASN_BITSTRING;
841     CRYPT_EncodeLen(dataBytes + 1, pbEncoded, &lenBytes);
842     pbEncoded += lenBytes;
843     *pbEncoded++ = unusedBits;
844     if (dataBytes)
845     {
846         BYTE mask = 0xff << unusedBits;
847
848         if (dataBytes > 1)
849         {
850             memcpy(pbEncoded, blob->pbData, dataBytes - 1);
851             pbEncoded += dataBytes - 1;
852         }
853         *pbEncoded = *(blob->pbData + dataBytes - 1) & mask;
854     }
855     return TRUE;
856 }
857
858 static BOOL WINAPI CRYPT_AsnEncodeInt(DWORD dwCertEncodingType,
859  LPCSTR lpszStructType, const void *pvStructInfo, DWORD dwFlags,
860  PCRYPT_ENCODE_PARA pEncodePara, BYTE *pbEncoded, DWORD *pcbEncoded)
861 {
862     INT val, i;
863     BYTE significantBytes, padByte = 0, bytesNeeded;
864     BOOL neg = FALSE, pad = FALSE;
865
866     if (!pvStructInfo)
867     {
868         SetLastError(STATUS_ACCESS_VIOLATION);
869         return FALSE;
870     }
871
872     memcpy(&val, pvStructInfo, sizeof(val));
873     /* Count the number of significant bytes.  Temporarily swap sign for
874      * negatives so I count the minimum number of bytes.
875      */
876     if (val < 0)
877     {
878         neg = TRUE;
879         val = -val;
880     }
881     for (significantBytes = sizeof(val); !(val & 0xff000000);
882      val <<= 8, significantBytes--)
883         ;
884     if (neg)
885     {
886         val = -val;
887         if ((val & 0xff000000) < 0x80000000)
888         {
889             padByte = 0xff;
890             pad = TRUE;
891         }
892     }
893     else if ((val & 0xff000000) > 0x7f000000)
894     {
895         padByte = 0;
896         pad = TRUE;
897     }
898     bytesNeeded = 2 + significantBytes;
899     if (pad)
900         bytesNeeded++;
901     if (!pbEncoded)
902     {
903         *pcbEncoded = bytesNeeded;
904         return TRUE;
905     }
906     if (!CRYPT_EncodeEnsureSpace(dwFlags, pEncodePara, pbEncoded, pcbEncoded,
907      bytesNeeded))
908         return FALSE;
909     if (dwFlags & CRYPT_ENCODE_ALLOC_FLAG)
910         pbEncoded = *(BYTE **)pbEncoded;
911     *pbEncoded++ = ASN_INTEGER;
912     if (pad)
913     {
914         *pbEncoded++ = significantBytes + 1;
915         *pbEncoded++ = padByte;
916     }
917     else
918         *pbEncoded++ = significantBytes;
919     for (i = 0; i < significantBytes; i++, val <<= 8)
920         *(pbEncoded + i) = (BYTE)((val & 0xff000000) >> 24);
921     return TRUE;
922 }
923
924 static BOOL WINAPI CRYPT_AsnEncodeInteger(DWORD dwCertEncodingType,
925  LPCSTR lpszStructType, const void *pvStructInfo, DWORD dwFlags,
926  PCRYPT_ENCODE_PARA pEncodePara, BYTE *pbEncoded, DWORD *pcbEncoded)
927 {
928     DWORD significantBytes, lenBytes;
929     BYTE padByte = 0, bytesNeeded;
930     BOOL pad = FALSE;
931     CRYPT_INTEGER_BLOB *blob = (CRYPT_INTEGER_BLOB *)pvStructInfo;
932
933     if (!pvStructInfo)
934     {
935         SetLastError(STATUS_ACCESS_VIOLATION);
936         return FALSE;
937     }
938
939     /* FIXME: use exception handling to protect against bogus pointers */
940     significantBytes = blob->cbData;
941     if (significantBytes)
942     {
943         if (blob->pbData[significantBytes - 1] & 0x80)
944         {
945             /* negative, lop off leading (little-endian) 0xffs */
946             for (; significantBytes > 0 &&
947              blob->pbData[significantBytes - 1] == 0xff; significantBytes--)
948                 ;
949             if (blob->pbData[significantBytes - 1] < 0x80)
950             {
951                 padByte = 0xff;
952                 pad = TRUE;
953             }
954         }
955         else
956         {
957             /* positive, lop off leading (little-endian) zeroes */
958             for (; significantBytes > 0 && !blob->pbData[significantBytes - 1];
959              significantBytes--)
960                 ;
961             if (blob->pbData[significantBytes - 1] > 0x7f)
962             {
963                 padByte = 0;
964                 pad = TRUE;
965             }
966         }
967     }
968     if (pad)
969         CRYPT_EncodeLen(significantBytes + 1, NULL, &lenBytes);
970     else
971         CRYPT_EncodeLen(significantBytes, NULL, &lenBytes);
972     bytesNeeded = 1 + lenBytes + significantBytes;
973     if (pad)
974         bytesNeeded++;
975     if (!pbEncoded)
976     {
977         *pcbEncoded = bytesNeeded;
978         return TRUE;
979     }
980     if (!CRYPT_EncodeEnsureSpace(dwFlags, pEncodePara, pbEncoded, pcbEncoded,
981      bytesNeeded))
982         return FALSE;
983     if (dwFlags & CRYPT_ENCODE_ALLOC_FLAG)
984         pbEncoded = *(BYTE **)pbEncoded;
985     *pbEncoded++ = ASN_INTEGER;
986     if (pad)
987     {
988         CRYPT_EncodeLen(significantBytes + 1, pbEncoded, &lenBytes);
989         pbEncoded += lenBytes;
990         *pbEncoded++ = padByte;
991     }
992     else
993     {
994         CRYPT_EncodeLen(significantBytes, pbEncoded, &lenBytes);
995         pbEncoded += lenBytes;
996     }
997     for (; significantBytes > 0; significantBytes--)
998         *(pbEncoded++) = blob->pbData[significantBytes - 1];
999     return TRUE;
1000 }
1001
1002 static BOOL WINAPI CRYPT_AsnEncodeUnsignedInteger(DWORD dwCertEncodingType,
1003  LPCSTR lpszStructType, const void *pvStructInfo, DWORD dwFlags,
1004  PCRYPT_ENCODE_PARA pEncodePara, BYTE *pbEncoded, DWORD *pcbEncoded)
1005 {
1006     DWORD significantBytes, lenBytes;
1007     BYTE bytesNeeded;
1008     BOOL pad = FALSE;
1009     CRYPT_INTEGER_BLOB *blob = (CRYPT_INTEGER_BLOB *)pvStructInfo;
1010
1011     if (!pvStructInfo)
1012     {
1013         SetLastError(STATUS_ACCESS_VIOLATION);
1014         return FALSE;
1015     }
1016
1017     /* FIXME: use exception handling to protect against bogus pointers */
1018     significantBytes = blob->cbData;
1019     if (significantBytes)
1020     {
1021         /* positive, lop off leading (little-endian) zeroes */
1022         for (; significantBytes > 0 && !blob->pbData[significantBytes - 1];
1023          significantBytes--)
1024             ;
1025         if (blob->pbData[significantBytes - 1] > 0x7f)
1026             pad = TRUE;
1027     }
1028     if (pad)
1029         CRYPT_EncodeLen(significantBytes + 1, NULL, &lenBytes);
1030     else
1031         CRYPT_EncodeLen(significantBytes, NULL, &lenBytes);
1032     bytesNeeded = 1 + lenBytes + significantBytes;
1033     if (pad)
1034         bytesNeeded++;
1035     if (!pbEncoded)
1036     {
1037         *pcbEncoded = bytesNeeded;
1038         return TRUE;
1039     }
1040     if (!CRYPT_EncodeEnsureSpace(dwFlags, pEncodePara, pbEncoded, pcbEncoded,
1041      bytesNeeded))
1042         return FALSE;
1043     if (dwFlags & CRYPT_ENCODE_ALLOC_FLAG)
1044         pbEncoded = *(BYTE **)pbEncoded;
1045     *pbEncoded++ = ASN_INTEGER;
1046     if (pad)
1047     {
1048         CRYPT_EncodeLen(significantBytes + 1, pbEncoded, &lenBytes);
1049         pbEncoded += lenBytes;
1050         *pbEncoded++ = 0;
1051     }
1052     else
1053     {
1054         CRYPT_EncodeLen(significantBytes, pbEncoded, &lenBytes);
1055         pbEncoded += lenBytes;
1056     }
1057     for (; significantBytes > 0; significantBytes--)
1058         *(pbEncoded++) = blob->pbData[significantBytes - 1];
1059     return TRUE;
1060 }
1061
1062 static BOOL WINAPI CRYPT_AsnEncodeEnumerated(DWORD dwCertEncodingType,
1063  LPCSTR lpszStructType, const void *pvStructInfo, DWORD dwFlags,
1064  PCRYPT_ENCODE_PARA pEncodePara, BYTE *pbEncoded, DWORD *pcbEncoded)
1065 {
1066     CRYPT_INTEGER_BLOB blob;
1067     BOOL ret;
1068
1069     /* Encode as an unsigned integer, then change the tag to enumerated */
1070     blob.cbData = sizeof(DWORD);
1071     blob.pbData = (BYTE *)pvStructInfo;
1072     ret = CRYPT_AsnEncodeUnsignedInteger(dwCertEncodingType,
1073      X509_MULTI_BYTE_UINT, &blob, dwFlags, pEncodePara, pbEncoded, pcbEncoded);
1074     if (ret && pbEncoded)
1075     {
1076         if (dwFlags & CRYPT_ENCODE_ALLOC_FLAG)
1077             pbEncoded = *(BYTE **)pbEncoded;
1078         pbEncoded[0] = ASN_ENUMERATED;
1079     }
1080     return ret;
1081 }
1082
1083 static BOOL WINAPI CRYPT_AsnEncodeUtcTime(DWORD dwCertEncodingType,
1084  LPCSTR lpszStructType, const void *pvStructInfo, DWORD dwFlags,
1085  PCRYPT_ENCODE_PARA pEncodePara, BYTE *pbEncoded, DWORD *pcbEncoded)
1086 {
1087     SYSTEMTIME sysTime;
1088     /* sorry, magic number: enough for tag, len, YYMMDDHHMMSSZ\0.  I use a
1089      * temporary buffer because the output buffer is not NULL-terminated.
1090      */
1091     char buf[16];
1092     static const DWORD bytesNeeded = sizeof(buf) - 1;
1093
1094     if (!pvStructInfo)
1095     {
1096         SetLastError(STATUS_ACCESS_VIOLATION);
1097         return FALSE;
1098     }
1099     /* Sanity check the year, this is a two-digit year format */
1100     if (!FileTimeToSystemTime((const FILETIME *)pvStructInfo, &sysTime))
1101         return FALSE;
1102     if (sysTime.wYear < 1950 || sysTime.wYear > 2050)
1103     {
1104         SetLastError(CRYPT_E_BAD_ENCODE);
1105         return FALSE;
1106     }
1107     if (!pbEncoded)
1108     {
1109         *pcbEncoded = bytesNeeded;
1110         return TRUE;
1111     }
1112     if (!CRYPT_EncodeEnsureSpace(dwFlags, pEncodePara, pbEncoded, pcbEncoded,
1113      bytesNeeded))
1114         return FALSE;
1115     if (dwFlags & CRYPT_ENCODE_ALLOC_FLAG)
1116         pbEncoded = *(BYTE **)pbEncoded;
1117     buf[0] = ASN_UTCTIME;
1118     buf[1] = bytesNeeded - 2;
1119     snprintf(buf + 2, sizeof(buf) - 2, "%02d%02d%02d%02d%02d%02dZ",
1120      sysTime.wYear >= 2000 ? sysTime.wYear - 2000 : sysTime.wYear - 1900,
1121      sysTime.wDay, sysTime.wMonth, sysTime.wHour, sysTime.wMinute,
1122      sysTime.wSecond);
1123     memcpy(pbEncoded, buf, bytesNeeded);
1124     return TRUE;
1125 }
1126
1127 static BOOL WINAPI CRYPT_AsnEncodeGeneralizedTime(DWORD dwCertEncodingType,
1128  LPCSTR lpszStructType, const void *pvStructInfo, DWORD dwFlags,
1129  PCRYPT_ENCODE_PARA pEncodePara, BYTE *pbEncoded, DWORD *pcbEncoded)
1130 {
1131     SYSTEMTIME sysTime;
1132     /* sorry, magic number: enough for tag, len, YYYYMMDDHHMMSSZ\0.  I use a
1133      * temporary buffer because the output buffer is not NULL-terminated.
1134      */
1135     char buf[18];
1136     static const DWORD bytesNeeded = sizeof(buf) - 1;
1137
1138     if (!pvStructInfo)
1139     {
1140         SetLastError(STATUS_ACCESS_VIOLATION);
1141         return FALSE;
1142     }
1143     if (!pbEncoded)
1144     {
1145         *pcbEncoded = bytesNeeded;
1146         return TRUE;
1147     }
1148     if (!FileTimeToSystemTime((const FILETIME *)pvStructInfo, &sysTime))
1149         return FALSE;
1150     if (!CRYPT_EncodeEnsureSpace(dwFlags, pEncodePara, pbEncoded, pcbEncoded,
1151      bytesNeeded))
1152         return FALSE;
1153     if (dwFlags & CRYPT_ENCODE_ALLOC_FLAG)
1154         pbEncoded = *(BYTE **)pbEncoded;
1155     buf[0] = ASN_GENERALTIME;
1156     buf[1] = bytesNeeded - 2;
1157     snprintf(buf + 2, sizeof(buf) - 2, "%04d%02d%02d%02d%02d%02dZ",
1158      sysTime.wYear, sysTime.wDay, sysTime.wMonth, sysTime.wHour,
1159      sysTime.wMinute, sysTime.wSecond);
1160     memcpy(pbEncoded, buf, bytesNeeded);
1161     return TRUE;
1162 }
1163
1164 static BOOL WINAPI CRYPT_AsnEncodeChoiceOfTime(DWORD dwCertEncodingType,
1165  LPCSTR lpszStructType, const void *pvStructInfo, DWORD dwFlags,
1166  PCRYPT_ENCODE_PARA pEncodePara, BYTE *pbEncoded, DWORD *pcbEncoded)
1167 {
1168     SYSTEMTIME sysTime;
1169     BOOL ret;
1170
1171     if (!pvStructInfo)
1172     {
1173         SetLastError(STATUS_ACCESS_VIOLATION);
1174         return FALSE;
1175     }
1176     /* Check the year, if it's in the UTCTime range call that encode func */
1177     if (!FileTimeToSystemTime((const FILETIME *)pvStructInfo, &sysTime))
1178         return FALSE;
1179     if (sysTime.wYear >= 1950 && sysTime.wYear <= 2050)
1180         ret = CRYPT_AsnEncodeUtcTime(dwCertEncodingType, lpszStructType,
1181          pvStructInfo, dwFlags, pEncodePara, pbEncoded, pcbEncoded);
1182     else
1183         ret = CRYPT_AsnEncodeGeneralizedTime(dwCertEncodingType,
1184          lpszStructType, pvStructInfo, dwFlags, pEncodePara, pbEncoded,
1185          pcbEncoded);
1186     return ret;
1187 }
1188
1189 typedef BOOL (WINAPI *CryptEncodeObjectExFunc)(DWORD, LPCSTR, const void *,
1190  DWORD, PCRYPT_ENCODE_PARA, BYTE *, DWORD *);
1191
1192 BOOL WINAPI CryptEncodeObjectEx(DWORD dwCertEncodingType, LPCSTR lpszStructType,
1193  const void *pvStructInfo, DWORD dwFlags, PCRYPT_ENCODE_PARA pEncodePara,
1194  BYTE *pbEncoded, DWORD *pcbEncoded)
1195 {
1196     BOOL ret = FALSE;
1197     HMODULE lib = NULL;
1198     CryptEncodeObjectExFunc encodeFunc = NULL;
1199
1200     TRACE("(0x%08lx, %s, %p, 0x%08lx, %p, %p, %p)\n",
1201      dwCertEncodingType, HIWORD(lpszStructType) ? debugstr_a(lpszStructType) :
1202      "(integer value)", pvStructInfo, dwFlags, pEncodePara, pbEncoded,
1203      pcbEncoded);
1204
1205     if (!pbEncoded && !pcbEncoded)
1206     {
1207         SetLastError(ERROR_INVALID_PARAMETER);
1208         return FALSE;
1209     }
1210     if ((dwCertEncodingType & CERT_ENCODING_TYPE_MASK) != X509_ASN_ENCODING
1211      && (dwCertEncodingType & CMSG_ENCODING_TYPE_MASK) != PKCS_7_ASN_ENCODING)
1212     {
1213         SetLastError(ERROR_FILE_NOT_FOUND);
1214         return FALSE;
1215     }
1216
1217     SetLastError(NOERROR);
1218     if (!HIWORD(lpszStructType))
1219     {
1220         switch (LOWORD(lpszStructType))
1221         {
1222         case (WORD)X509_NAME:
1223             encodeFunc = CRYPT_AsnEncodeName;
1224             break;
1225         case (WORD)X509_OCTET_STRING:
1226             encodeFunc = CRYPT_AsnEncodeOctets;
1227             break;
1228         case (WORD)X509_BITS:
1229         case (WORD)X509_KEY_USAGE:
1230             encodeFunc = CRYPT_AsnEncodeBits;
1231             break;
1232         case (WORD)X509_INTEGER:
1233             encodeFunc = CRYPT_AsnEncodeInt;
1234             break;
1235         case (WORD)X509_MULTI_BYTE_INTEGER:
1236             encodeFunc = CRYPT_AsnEncodeInteger;
1237             break;
1238         case (WORD)X509_MULTI_BYTE_UINT:
1239             encodeFunc = CRYPT_AsnEncodeUnsignedInteger;
1240             break;
1241         case (WORD)X509_ENUMERATED:
1242             encodeFunc = CRYPT_AsnEncodeEnumerated;
1243             break;
1244         case (WORD)X509_CHOICE_OF_TIME:
1245             encodeFunc = CRYPT_AsnEncodeChoiceOfTime;
1246             break;
1247         case (WORD)PKCS_UTC_TIME:
1248             encodeFunc = CRYPT_AsnEncodeUtcTime;
1249             break;
1250         default:
1251             FIXME("%d: unimplemented\n", LOWORD(lpszStructType));
1252         }
1253     }
1254     else if (!strcmp(lpszStructType, szOID_RSA_signingTime))
1255         encodeFunc = CRYPT_AsnEncodeUtcTime;
1256     else if (!strcmp(lpszStructType, szOID_CRL_REASON_CODE))
1257         encodeFunc = CRYPT_AsnEncodeEnumerated;
1258     else if (!strcmp(lpszStructType, szOID_KEY_USAGE))
1259         encodeFunc = CRYPT_AsnEncodeBits;
1260     else if (!strcmp(lpszStructType, szOID_SUBJECT_KEY_IDENTIFIER))
1261         encodeFunc = CRYPT_AsnEncodeOctets;
1262     if (!encodeFunc)
1263         encodeFunc = (CryptEncodeObjectExFunc)CRYPT_GetFunc(dwCertEncodingType,
1264          lpszStructType, "CryptEncodeObjectEx", &lib);
1265     if (encodeFunc)
1266         ret = encodeFunc(dwCertEncodingType, lpszStructType, pvStructInfo,
1267          dwFlags, pEncodePara, pbEncoded, pcbEncoded);
1268     else
1269         SetLastError(ERROR_FILE_NOT_FOUND);
1270     if (lib)
1271         FreeLibrary(lib);
1272     return ret;
1273 }
1274
1275 typedef BOOL (WINAPI *CryptDecodeObjectFunc)(DWORD, LPCSTR, const BYTE *,
1276  DWORD, DWORD, void *, DWORD *);
1277
1278 BOOL WINAPI CryptDecodeObject(DWORD dwCertEncodingType, LPCSTR lpszStructType,
1279  const BYTE *pbEncoded, DWORD cbEncoded, DWORD dwFlags, void *pvStructInfo,
1280  DWORD *pcbStructInfo)
1281 {
1282     BOOL ret = FALSE;
1283     HMODULE lib;
1284     CryptDecodeObjectFunc pCryptDecodeObject;
1285
1286     TRACE("(0x%08lx, %s, %p, %ld, 0x%08lx, %p, %p)\n",
1287      dwCertEncodingType, HIWORD(lpszStructType) ? debugstr_a(lpszStructType) :
1288      "(integer value)", pbEncoded, cbEncoded, dwFlags, pvStructInfo,
1289      pcbStructInfo);
1290
1291     if (!pvStructInfo && !pcbStructInfo)
1292     {
1293         SetLastError(ERROR_INVALID_PARAMETER);
1294         return FALSE;
1295     }
1296
1297     /* Try registered DLL first.. */
1298     pCryptDecodeObject =
1299      (CryptDecodeObjectFunc)CRYPT_GetFunc(dwCertEncodingType,
1300      lpszStructType, "CryptDecodeObject", &lib);
1301     if (pCryptDecodeObject)
1302     {
1303         ret = pCryptDecodeObject(dwCertEncodingType, lpszStructType,
1304          pbEncoded, cbEncoded, dwFlags, pvStructInfo, pcbStructInfo);
1305         FreeLibrary(lib);
1306     }
1307     else
1308     {
1309         /* If not, use CryptDecodeObjectEx */
1310         ret = CryptDecodeObjectEx(dwCertEncodingType, lpszStructType, pbEncoded,
1311          cbEncoded, dwFlags, NULL, pvStructInfo, pcbStructInfo);
1312     }
1313     return ret;
1314 }
1315
1316 /* Gets the number of length bytes from the given (leading) length byte */
1317 #define GET_LEN_BYTES(b) ((b) <= 0x7f ? 1 : 1 + ((b) & 0x7f))
1318
1319 /* Helper function to get the encoded length of the data starting at pbEncoded,
1320  * where pbEncoded[0] is the tag.  If the data are too short to contain a
1321  * length or if the length is too large for cbEncoded, sets an appropriate
1322  * error code and returns FALSE.
1323  */
1324 static BOOL WINAPI CRYPT_GetLen(const BYTE *pbEncoded, DWORD cbEncoded,
1325  DWORD *len)
1326 {
1327     BOOL ret;
1328
1329     if (cbEncoded <= 1)
1330     {
1331         SetLastError(CRYPT_E_ASN1_EOD);
1332         ret = FALSE;
1333     }
1334     else if (pbEncoded[1] <= 0x7f)
1335     {
1336         *len = pbEncoded[1];
1337         ret = TRUE;
1338     }
1339     else
1340     {
1341         BYTE lenLen = GET_LEN_BYTES(pbEncoded[1]);
1342
1343         if (lenLen > sizeof(DWORD))
1344         {
1345             SetLastError(CRYPT_E_ASN1_LARGE);
1346             ret = FALSE;
1347         }
1348         else if (lenLen + 2 > cbEncoded)
1349         {
1350             SetLastError(CRYPT_E_ASN1_CORRUPT);
1351             ret = FALSE;
1352         }
1353         else
1354         {
1355             DWORD out = 0;
1356
1357             pbEncoded += 2;
1358             while (lenLen--)
1359             {
1360                 out <<= 8;
1361                 out |= *pbEncoded++;
1362             }
1363             if (out + lenLen + 1 > cbEncoded)
1364             {
1365                 SetLastError(CRYPT_E_ASN1_EOD);
1366                 ret = FALSE;
1367             }
1368             else
1369             {
1370                 *len = out;
1371                 ret = TRUE;
1372             }
1373         }
1374     }
1375     return ret;
1376 }
1377
1378 /* Helper function to check *pcbStructInfo, set it to the required size, and
1379  * optionally to allocate memory.  Assumes pvStructInfo is not NULL.
1380  * If CRYPT_DECODE_ALLOC_FLAG is set in dwFlags, *pvStructInfo will be set to a
1381  * pointer to the newly allocated memory.
1382  */
1383 static BOOL CRYPT_DecodeEnsureSpace(DWORD dwFlags,
1384  PCRYPT_DECODE_PARA pDecodePara, void *pvStructInfo, DWORD *pcbStructInfo,
1385  DWORD bytesNeeded)
1386 {
1387     BOOL ret = TRUE;
1388
1389     if (dwFlags & CRYPT_DECODE_ALLOC_FLAG)
1390     {
1391         if (pDecodePara && pDecodePara->pfnAlloc)
1392             *(BYTE **)pvStructInfo = pDecodePara->pfnAlloc(bytesNeeded);
1393         else
1394             *(BYTE **)pvStructInfo = LocalAlloc(0, bytesNeeded);
1395         if (!*(BYTE **)pvStructInfo)
1396             ret = FALSE;
1397         else
1398             *pcbStructInfo = bytesNeeded;
1399     }
1400     else if (*pcbStructInfo < bytesNeeded)
1401     {
1402         *pcbStructInfo = bytesNeeded;
1403         SetLastError(ERROR_MORE_DATA);
1404         ret = FALSE;
1405     }
1406     return ret;
1407 }
1408
1409 /* FIXME: honor the CRYPT_DECODE_SHARE_OID_FLAG. */
1410 static BOOL WINAPI CRYPT_AsnDecodeOid(DWORD dwCertEncodingType,
1411  const BYTE *pbEncoded, DWORD cbEncoded, DWORD dwFlags, LPSTR pszObjId,
1412  DWORD *pcbObjId)
1413 {
1414     BOOL ret = TRUE;
1415     DWORD bytesNeeded, dataLen;
1416     BYTE lenBytes;
1417
1418     if (!CRYPT_GetLen(pbEncoded, cbEncoded, &dataLen))
1419         return FALSE;
1420     if (pbEncoded[0] != ASN_OBJECTIDENTIFIER)
1421     {
1422         SetLastError(CRYPT_E_ASN1_BADTAG);
1423         return FALSE;
1424     }
1425     lenBytes = GET_LEN_BYTES(pbEncoded[1]);
1426     if (dataLen)
1427     {
1428         /* The largest possible string for the first two components is 2.175
1429          * (= 2 * 40 + 175 = 255), so this is big enough.
1430          */
1431         char firstTwo[6];
1432         const BYTE *ptr;
1433
1434         snprintf(firstTwo, sizeof(firstTwo), "%d.%d",
1435          pbEncoded[1 + lenBytes] / 40,
1436          pbEncoded[1 + lenBytes] - (pbEncoded[1 + lenBytes] / 40) * 40);
1437         bytesNeeded = strlen(firstTwo) + 1;
1438         for (ptr = pbEncoded + 2 + lenBytes; ret &&
1439          ptr - pbEncoded - 1 - lenBytes < dataLen; )
1440         {
1441             /* large enough for ".4000000" */
1442             char str[9];
1443             int val = 0;
1444
1445             while (ptr - pbEncoded - 1 - lenBytes < dataLen && (*ptr & 0x80))
1446             {
1447                 val <<= 7;
1448                 val |= *ptr & 0x7f;
1449                 ptr++;
1450             }
1451             if (ptr - pbEncoded - 1 - lenBytes >= dataLen || (*ptr & 0x80))
1452             {
1453                 SetLastError(CRYPT_E_ASN1_CORRUPT);
1454                 ret = FALSE;
1455             }
1456             else
1457             {
1458                 val <<= 7;
1459                 val |= *ptr++;
1460                 snprintf(str, sizeof(str), ".%d", val);
1461                 bytesNeeded += strlen(str);
1462             }
1463         }
1464         if (!pszObjId)
1465             *pcbObjId = bytesNeeded;
1466         else if (*pcbObjId < bytesNeeded)
1467         {
1468             *pcbObjId = bytesNeeded;
1469             SetLastError(ERROR_MORE_DATA);
1470             ret = FALSE;
1471         }
1472         else
1473         {
1474             sprintf(pszObjId, "%d.%d", pbEncoded[1 + lenBytes] / 40,
1475              pbEncoded[1 + lenBytes] - (pbEncoded[1 + lenBytes] / 40) * 40);
1476             pszObjId += strlen(pszObjId);
1477             for (ptr = pbEncoded + 2 + lenBytes; ret &&
1478              ptr - pbEncoded - 1 - lenBytes < dataLen; )
1479             {
1480                 int val = 0;
1481
1482                 while (ptr - pbEncoded - 1 - lenBytes < dataLen &&
1483                  (*ptr & 0x80))
1484                 {
1485                     val <<= 7;
1486                     val |= *ptr & 0x7f;
1487                     ptr++;
1488                 }
1489                 val <<= 7;
1490                 val |= *ptr++;
1491                 sprintf(pszObjId, ".%d", val);
1492                 pszObjId += strlen(pszObjId);
1493             }
1494         }
1495     }
1496     else
1497         bytesNeeded = 0;
1498     *pcbObjId = bytesNeeded;
1499     return ret;
1500 }
1501
1502 /* Warning: this assumes the address of value->Value.pbData is already set, in
1503  * order to avoid overwriting memory.  (In some cases, it may change it, if it
1504  * doesn't copy anything to memory.)  Be sure to set it correctly!
1505  */
1506 static BOOL WINAPI CRYPT_AsnDecodeNameValue(DWORD dwCertEncodingType,
1507  const BYTE *pbEncoded, DWORD cbEncoded, DWORD dwFlags, CERT_NAME_VALUE *value,
1508  DWORD *pcbValue)
1509 {
1510     DWORD bytesNeeded, dataLen;
1511     BOOL ret = TRUE;
1512     BYTE lenBytes;
1513
1514     if (!CRYPT_GetLen(pbEncoded, cbEncoded, &dataLen))
1515         return FALSE;
1516     lenBytes = GET_LEN_BYTES(pbEncoded[1]);
1517     switch (pbEncoded[0])
1518     {
1519     case ASN_NUMERICSTRING:
1520     case ASN_PRINTABLESTRING:
1521     case ASN_IA5STRING:
1522         break;
1523     default:
1524         FIXME("Unimplemented string type %02x\n", pbEncoded[0]);
1525         SetLastError(OSS_UNIMPLEMENTED);
1526         return FALSE;
1527     }
1528     bytesNeeded = sizeof(CERT_NAME_VALUE);
1529     if (dataLen)
1530     {
1531         switch (pbEncoded[0])
1532         {
1533         case ASN_NUMERICSTRING:
1534         case ASN_PRINTABLESTRING:
1535         case ASN_IA5STRING:
1536             if (!(dwFlags & CRYPT_DECODE_NOCOPY_FLAG))
1537                 bytesNeeded += dataLen;
1538             break;
1539         }
1540     }
1541     if (!value)
1542     {
1543         *pcbValue = bytesNeeded;
1544         return TRUE;
1545     }
1546     if (*pcbValue < bytesNeeded)
1547     {
1548         *pcbValue = bytesNeeded;
1549         SetLastError(ERROR_MORE_DATA);
1550         return FALSE;
1551     }
1552     *pcbValue = bytesNeeded;
1553     switch (pbEncoded[0])
1554     {
1555     case ASN_NUMERICSTRING:
1556         value->dwValueType = CERT_RDN_NUMERIC_STRING;
1557         break;
1558     case ASN_PRINTABLESTRING:
1559         value->dwValueType = CERT_RDN_PRINTABLE_STRING;
1560         break;
1561     case ASN_IA5STRING:
1562         value->dwValueType = CERT_RDN_IA5_STRING;
1563         break;
1564     }
1565     if (dataLen)
1566     {
1567         switch (pbEncoded[0])
1568         {
1569         case ASN_NUMERICSTRING:
1570         case ASN_PRINTABLESTRING:
1571         case ASN_IA5STRING:
1572             value->Value.cbData = dataLen;
1573             if (dwFlags & CRYPT_DECODE_NOCOPY_FLAG)
1574                 value->Value.pbData = (BYTE *)pbEncoded + 1 + lenBytes;
1575             else
1576             {
1577                 if (!value->Value.pbData)
1578                 {
1579                     SetLastError(CRYPT_E_ASN1_INTERNAL);
1580                     ret = FALSE;
1581                 }
1582                 else
1583                     memcpy(value->Value.pbData, pbEncoded + 1 + lenBytes,
1584                      dataLen);
1585             }
1586             break;
1587         }
1588     }
1589     else
1590     {
1591         value->Value.cbData = 0;
1592         value->Value.pbData = NULL;
1593     }
1594     return ret;
1595 }
1596
1597 static BOOL WINAPI CRYPT_AsnDecodeRdnAttr(DWORD dwCertEncodingType,
1598  const BYTE *pbEncoded, DWORD cbEncoded, DWORD dwFlags, CERT_RDN_ATTR *attr,
1599  DWORD *pcbAttr)
1600 {
1601     BOOL ret = TRUE;
1602     DWORD bytesNeeded, dataLen, size;
1603     BYTE lenBytes;
1604
1605     if (!CRYPT_GetLen(pbEncoded, cbEncoded, &dataLen))
1606         return FALSE;
1607     /* The data length must be at least 4, two for the tag and length for the
1608      * OID, and two for the string (assuming both have short-form lengths.)
1609      */
1610     if (dataLen < 4)
1611     {
1612         SetLastError(CRYPT_E_ASN1_EOD);
1613         return FALSE;
1614     }
1615     if (pbEncoded[0] != (ASN_CONSTRUCTOR | ASN_SEQUENCE))
1616     {
1617         SetLastError(CRYPT_E_ASN1_BADTAG);
1618         return FALSE;
1619     }
1620     bytesNeeded = sizeof(CERT_RDN_ATTR);
1621     lenBytes = GET_LEN_BYTES(pbEncoded[1]);
1622     ret = CRYPT_AsnDecodeOid(dwCertEncodingType, pbEncoded + 1 + lenBytes,
1623      cbEncoded - 1 - lenBytes, dwFlags, NULL, &size);
1624     if (ret)
1625     {
1626         /* ugly: need to know the size of the next element of the sequence,
1627          * so get it directly
1628          */
1629         DWORD objIdOfset = 1 + lenBytes, objIdLen, nameValueOffset = 0;
1630
1631         ret = CRYPT_GetLen(pbEncoded + objIdOfset, cbEncoded - objIdOfset,
1632          &objIdLen);
1633         bytesNeeded += size;
1634         /* hack: like encoding, this takes advantage of the fact that the rest
1635          * of the structure is identical to a CERT_NAME_VALUE.
1636          */
1637         if (ret)
1638         {
1639             nameValueOffset = objIdOfset + objIdLen + 1 +
1640              GET_LEN_BYTES(pbEncoded[objIdOfset]);
1641             ret = CRYPT_AsnDecodeNameValue(dwCertEncodingType,
1642              pbEncoded + nameValueOffset, cbEncoded - nameValueOffset, dwFlags,
1643              NULL, &size);
1644         }
1645         if (ret)
1646         {
1647             bytesNeeded += size;
1648             if (!attr)
1649                 *pcbAttr = bytesNeeded;
1650             else if (*pcbAttr < bytesNeeded)
1651             {
1652                 *pcbAttr = bytesNeeded;
1653                 SetLastError(ERROR_MORE_DATA);
1654                 ret = FALSE;
1655             }
1656             else
1657             {
1658                 BYTE *originalData = attr->Value.pbData;
1659
1660                 *pcbAttr = bytesNeeded;
1661                 /* strange: decode the value first, because it has a counted
1662                  * size, and we can store the OID after it.  Keep track of the
1663                  * original data pointer, we'll need to know whether it was
1664                  * changed.
1665                  */
1666                 size = bytesNeeded;
1667                 ret = CRYPT_AsnDecodeNameValue(dwCertEncodingType,
1668                  pbEncoded + nameValueOffset, cbEncoded - nameValueOffset,
1669                  dwFlags, (CERT_NAME_VALUE *)&attr->dwValueType, &size);
1670                 if (ret)
1671                 {
1672                     if (objIdLen)
1673                     {
1674                         /* if the data were copied to the original location,
1675                          * the OID goes after.  Otherwise it goes in the
1676                          * spot originally reserved for the data.
1677                          */
1678                         if (attr->Value.pbData == originalData)
1679                             attr->pszObjId = (LPSTR)(attr->Value.pbData +
1680                              attr->Value.cbData);
1681                         else
1682                             attr->pszObjId = originalData;
1683                         size = bytesNeeded - size;
1684                         ret = CRYPT_AsnDecodeOid(dwCertEncodingType,
1685                          pbEncoded + objIdOfset, cbEncoded - objIdOfset,
1686                          dwFlags, attr->pszObjId, &size);
1687                     }
1688                     else
1689                         attr->pszObjId = NULL;
1690                 }
1691             }
1692         }
1693     }
1694     return ret;
1695 }
1696
1697 static BOOL WINAPI CRYPT_AsnDecodeRdn(DWORD dwCertEncodingType,
1698  const BYTE *pbEncoded, DWORD cbEncoded, DWORD dwFlags, CERT_RDN *rdn,
1699  DWORD *pcbRdn)
1700 {
1701     BOOL ret = TRUE;
1702     DWORD bytesNeeded, dataLen, cRDNAttr = 0;
1703     BYTE lenBytes;
1704
1705     if (!CRYPT_GetLen(pbEncoded, cbEncoded, &dataLen))
1706         return FALSE;
1707     if (pbEncoded[0] != (ASN_CONSTRUCTOR | ASN_SETOF))
1708     {
1709         SetLastError(CRYPT_E_ASN1_BADTAG);
1710         return FALSE;
1711     }
1712     lenBytes = GET_LEN_BYTES(pbEncoded[1]);
1713     bytesNeeded = sizeof(CERT_RDN);
1714     if (dataLen)
1715     {
1716         const BYTE *ptr;
1717         DWORD size;
1718
1719         for (ptr = pbEncoded + 1 + lenBytes; ret &&
1720          ptr - pbEncoded - 1 - lenBytes < dataLen; )
1721         {
1722             ret = CRYPT_AsnDecodeRdnAttr(dwCertEncodingType, ptr,
1723              cbEncoded - (ptr - pbEncoded), dwFlags, NULL, &size);
1724             if (ret)
1725             {
1726                 DWORD nextLen;
1727
1728                 cRDNAttr++;
1729                 bytesNeeded += size;
1730                 ret = CRYPT_GetLen(ptr, cbEncoded - (ptr - pbEncoded),
1731                  &nextLen);
1732                 if (ret)
1733                     ptr += nextLen + 1 + GET_LEN_BYTES(ptr[1]);
1734             }
1735         }
1736     }
1737     if (ret)
1738     {
1739         if (!rdn)
1740         {
1741             *pcbRdn = bytesNeeded;
1742             return TRUE;
1743         }
1744         if (*pcbRdn < bytesNeeded)
1745         {
1746             *pcbRdn = bytesNeeded;
1747             SetLastError(ERROR_MORE_DATA);
1748             return FALSE;
1749         }
1750         *pcbRdn = bytesNeeded;
1751         rdn->cRDNAttr = cRDNAttr;
1752         if (rdn->cRDNAttr == 0)
1753             rdn->rgRDNAttr = NULL;
1754         else
1755         {
1756             DWORD size, i;
1757             BYTE *nextData;
1758             const BYTE *ptr;
1759
1760             rdn->rgRDNAttr = (CERT_RDN_ATTR *)((BYTE *)rdn + sizeof(CERT_RDN));
1761             nextData = (BYTE *)rdn->rgRDNAttr +
1762              rdn->cRDNAttr * sizeof(CERT_RDN_ATTR);
1763             for (i = 0, ptr = pbEncoded + 1 + lenBytes; ret && i < cRDNAttr &&
1764              ptr - pbEncoded - 1 - lenBytes < dataLen; i++)
1765             {
1766                 rdn->rgRDNAttr[i].Value.pbData = nextData;
1767                 size = bytesNeeded;
1768                 ret = CRYPT_AsnDecodeRdnAttr(dwCertEncodingType, ptr,
1769                  cbEncoded - (ptr - pbEncoded), dwFlags, &rdn->rgRDNAttr[i],
1770                  &size);
1771                 if (ret)
1772                 {
1773                     DWORD nextLen;
1774
1775                     bytesNeeded -= size;
1776                     /* If dwFlags & CRYPT_DECODE_NOCOPY_FLAG, the data may not
1777                      * have been copied.
1778                      */
1779                     if (rdn->rgRDNAttr[i].Value.pbData == nextData)
1780                         nextData += rdn->rgRDNAttr[i].Value.cbData;
1781                     /* Ugly: the OID, if copied, is stored in memory after the
1782                      * value, so increment by its string length if it's set and
1783                      * points here.
1784                      */
1785                     if ((const BYTE *)rdn->rgRDNAttr[i].pszObjId == nextData)
1786                         nextData += strlen(rdn->rgRDNAttr[i].pszObjId) + 1;
1787                     ret = CRYPT_GetLen(ptr, cbEncoded - (ptr - pbEncoded),
1788                      &nextLen);
1789                     if (ret)
1790                         ptr += nextLen + 1 + GET_LEN_BYTES(ptr[1]);
1791                 }
1792             }
1793         }
1794     }
1795     return ret;
1796 }
1797
1798 static BOOL WINAPI CRYPT_AsnDecodeName(DWORD dwCertEncodingType,
1799  LPCSTR lpszStructType, const BYTE *pbEncoded, DWORD cbEncoded, DWORD dwFlags,
1800  PCRYPT_DECODE_PARA pDecodePara, void *pvStructInfo, DWORD *pcbStructInfo)
1801 {
1802     BOOL ret = TRUE;
1803     DWORD bytesNeeded, dataLen, cRDN = 0;
1804     BYTE lenBytes;
1805
1806     if (!pbEncoded)
1807     {
1808         SetLastError(CRYPT_E_ASN1_EOD);
1809         return FALSE;
1810     }
1811     if (!CRYPT_GetLen(pbEncoded, cbEncoded, &dataLen))
1812         return FALSE;
1813     if (pbEncoded[0] != (ASN_CONSTRUCTOR | ASN_SEQUENCEOF))
1814     {
1815         SetLastError(CRYPT_E_ASN1_BADTAG);
1816         return FALSE;
1817     }
1818     lenBytes = GET_LEN_BYTES(pbEncoded[1]);
1819     bytesNeeded = sizeof(CERT_NAME_INFO);
1820     if (dataLen)
1821     {
1822         const BYTE *ptr;
1823         DWORD size;
1824
1825         for (ptr = pbEncoded + 1 + lenBytes; ret && ptr - pbEncoded - 1 -
1826          lenBytes < dataLen; )
1827         {
1828             ret = CRYPT_AsnDecodeRdn(dwCertEncodingType, ptr,
1829              cbEncoded - (ptr - pbEncoded), dwFlags, NULL, &size);
1830             if (ret)
1831             {
1832                 DWORD nextLen;
1833
1834                 cRDN++;
1835                 bytesNeeded += size;
1836                 ret = CRYPT_GetLen(ptr, cbEncoded - (ptr - pbEncoded),
1837                  &nextLen);
1838                 if (ret)
1839                     ptr += nextLen + 1 + GET_LEN_BYTES(ptr[1]);
1840             }
1841         }
1842     }
1843     if (ret)
1844     {
1845         CERT_NAME_INFO *info;
1846
1847         if (!pvStructInfo)
1848         {
1849             *pcbStructInfo = bytesNeeded;
1850             return TRUE;
1851         }
1852         if (!CRYPT_DecodeEnsureSpace(dwFlags, pDecodePara, pvStructInfo,
1853          pcbStructInfo, bytesNeeded))
1854             return FALSE;
1855         if (dwFlags & CRYPT_DECODE_ALLOC_FLAG)
1856             pvStructInfo = *(BYTE **)pvStructInfo;
1857         info = (CERT_NAME_INFO *)pvStructInfo;
1858         info->cRDN = cRDN;
1859         if (info->cRDN == 0)
1860             info->rgRDN = NULL;
1861         else
1862         {
1863             DWORD size, i;
1864             BYTE *nextData;
1865             const BYTE *ptr;
1866
1867             info->rgRDN = (CERT_RDN *)((BYTE *)pvStructInfo +
1868              sizeof(CERT_NAME_INFO));
1869             nextData = (BYTE *)info->rgRDN + info->cRDN * sizeof(CERT_RDN);
1870             for (i = 0, ptr = pbEncoded + 1 + lenBytes; ret && i < cRDN &&
1871              ptr - pbEncoded - 1 - lenBytes < dataLen; i++)
1872             {
1873                 info->rgRDN[i].rgRDNAttr = (CERT_RDN_ATTR *)nextData;
1874                 size = bytesNeeded;
1875                 ret = CRYPT_AsnDecodeRdn(dwCertEncodingType, ptr,
1876                  cbEncoded - (ptr - pbEncoded), dwFlags, &info->rgRDN[i],
1877                  &size);
1878                 if (ret)
1879                 {
1880                     DWORD nextLen;
1881
1882                     nextData += size;
1883                     bytesNeeded -= size;
1884                     ret = CRYPT_GetLen(ptr, cbEncoded - (ptr - pbEncoded),
1885                      &nextLen);
1886                     if (ret)
1887                         ptr += nextLen + 1 + GET_LEN_BYTES(ptr[1]);
1888                 }
1889             }
1890         }
1891     }
1892     return ret;
1893 }
1894
1895 static BOOL WINAPI CRYPT_AsnDecodeOctets(DWORD dwCertEncodingType,
1896  LPCSTR lpszStructType, const BYTE *pbEncoded, DWORD cbEncoded, DWORD dwFlags,
1897  PCRYPT_DECODE_PARA pDecodePara, void *pvStructInfo, DWORD *pcbStructInfo)
1898 {
1899     CRYPT_DATA_BLOB *blob;
1900     DWORD bytesNeeded, dataLen;
1901
1902     if (!pbEncoded)
1903     {
1904         SetLastError(CRYPT_E_ASN1_EOD);
1905         return FALSE;
1906     }
1907     if (!CRYPT_GetLen(pbEncoded, cbEncoded, &dataLen))
1908         return FALSE;
1909     if (pbEncoded[0] != ASN_OCTETSTRING)
1910     {
1911         SetLastError(CRYPT_E_ASN1_BADTAG);
1912         return FALSE;
1913     }
1914     if (dwFlags & CRYPT_DECODE_NOCOPY_FLAG)
1915         bytesNeeded = sizeof(CRYPT_DATA_BLOB);
1916     else
1917         bytesNeeded = dataLen + sizeof(CRYPT_DATA_BLOB);
1918     if (!pvStructInfo)
1919     {
1920         *pcbStructInfo = bytesNeeded;
1921         return TRUE;
1922     }
1923     if (!CRYPT_DecodeEnsureSpace(dwFlags, pDecodePara, pvStructInfo,
1924      pcbStructInfo, bytesNeeded))
1925         return FALSE;
1926     if (dwFlags & CRYPT_DECODE_ALLOC_FLAG)
1927         pvStructInfo = *(BYTE **)pvStructInfo;
1928     blob = (CRYPT_DATA_BLOB *)pvStructInfo;
1929     blob->cbData = dataLen;
1930     if (dwFlags & CRYPT_DECODE_NOCOPY_FLAG)
1931         blob->pbData = (BYTE *)pbEncoded + 1 + GET_LEN_BYTES(pbEncoded[1]);
1932     else
1933     {
1934         blob->pbData = (BYTE *)pvStructInfo + sizeof(CRYPT_DATA_BLOB);
1935         if (blob->cbData)
1936             memcpy(blob->pbData, pbEncoded + 1 + GET_LEN_BYTES(pbEncoded[1]),
1937              blob->cbData);
1938     }
1939     return TRUE;
1940 }
1941
1942 static BOOL WINAPI CRYPT_AsnDecodeBits(DWORD dwCertEncodingType,
1943  LPCSTR lpszStructType, const BYTE *pbEncoded, DWORD cbEncoded, DWORD dwFlags,
1944  PCRYPT_DECODE_PARA pDecodePara, void *pvStructInfo, DWORD *pcbStructInfo)
1945 {
1946     CRYPT_BIT_BLOB *blob;
1947     DWORD bytesNeeded, dataLen;
1948
1949     if (!pbEncoded)
1950     {
1951         SetLastError(CRYPT_E_ASN1_EOD);
1952         return FALSE;
1953     }
1954     if (!CRYPT_GetLen(pbEncoded, cbEncoded, &dataLen))
1955         return FALSE;
1956     if (pbEncoded[0] != ASN_BITSTRING)
1957     {
1958         SetLastError(CRYPT_E_ASN1_BADTAG);
1959         return FALSE;
1960     }
1961     if (dwFlags & CRYPT_DECODE_NOCOPY_FLAG)
1962         bytesNeeded = sizeof(CRYPT_BIT_BLOB);
1963     else
1964         bytesNeeded = dataLen - 1 + sizeof(CRYPT_BIT_BLOB);
1965     if (!pvStructInfo)
1966     {
1967         *pcbStructInfo = bytesNeeded;
1968         return TRUE;
1969     }
1970     if (!CRYPT_DecodeEnsureSpace(dwFlags, pDecodePara, pvStructInfo,
1971      pcbStructInfo, bytesNeeded))
1972         return FALSE;
1973     if (dwFlags & CRYPT_DECODE_ALLOC_FLAG)
1974         pvStructInfo = *(BYTE **)pvStructInfo;
1975     blob = (CRYPT_BIT_BLOB *)pvStructInfo;
1976     blob->cbData = dataLen - 1;
1977     blob->cUnusedBits = *(pbEncoded + 1 + GET_LEN_BYTES(pbEncoded[1]));
1978     if (dwFlags & CRYPT_DECODE_NOCOPY_FLAG)
1979         blob->pbData = (BYTE *)pbEncoded + 2 + GET_LEN_BYTES(pbEncoded[1]);
1980     else
1981     {
1982         blob->pbData = (BYTE *)pvStructInfo + sizeof(CRYPT_BIT_BLOB);
1983         if (blob->cbData)
1984         {
1985             BYTE mask = 0xff << blob->cUnusedBits;
1986
1987             memcpy(blob->pbData, pbEncoded + 2 + GET_LEN_BYTES(pbEncoded[1]),
1988              blob->cbData);
1989             blob->pbData[blob->cbData - 1] &= mask;
1990         }
1991     }
1992     return TRUE;
1993 }
1994
1995 static BOOL WINAPI CRYPT_AsnDecodeInt(DWORD dwCertEncodingType,
1996  LPCSTR lpszStructType, const BYTE *pbEncoded, DWORD cbEncoded, DWORD dwFlags,
1997  PCRYPT_DECODE_PARA pDecodePara, void *pvStructInfo, DWORD *pcbStructInfo)
1998 {
1999     int val, i;
2000
2001     if (!pbEncoded || !cbEncoded)
2002     {
2003         SetLastError(CRYPT_E_ASN1_EOD);
2004         return FALSE;
2005     }
2006     if (!pvStructInfo)
2007     {
2008         *pcbStructInfo = sizeof(int);
2009         return TRUE;
2010     }
2011     if (pbEncoded[0] != ASN_INTEGER)
2012     {
2013         SetLastError(CRYPT_E_ASN1_BADTAG);
2014         return FALSE;
2015     }
2016     if (cbEncoded <= 1)
2017     {
2018         SetLastError(CRYPT_E_ASN1_EOD);
2019         return FALSE;
2020     }
2021     if (pbEncoded[1] == 0)
2022     {
2023         SetLastError(CRYPT_E_ASN1_CORRUPT);
2024         return FALSE;
2025     }
2026     if (pbEncoded[1] > sizeof(int))
2027     {
2028         SetLastError(CRYPT_E_ASN1_LARGE);
2029         return FALSE;
2030     }
2031     if (pbEncoded[2] & 0x80)
2032     {
2033         /* initialize to a negative value to sign-extend */
2034         val = -1;
2035     }
2036     else
2037         val = 0;
2038     for (i = 0; i < pbEncoded[1]; i++)
2039     {
2040         val <<= 8;
2041         val |= pbEncoded[2 + i];
2042     }
2043     if (!CRYPT_DecodeEnsureSpace(dwFlags, pDecodePara, pvStructInfo,
2044      pcbStructInfo, sizeof(int)))
2045         return FALSE;
2046     if (dwFlags & CRYPT_DECODE_ALLOC_FLAG)
2047         pvStructInfo = *(BYTE **)pvStructInfo;
2048     memcpy(pvStructInfo, &val, sizeof(int));
2049     return TRUE;
2050 }
2051
2052 static BOOL WINAPI CRYPT_AsnDecodeInteger(DWORD dwCertEncodingType,
2053  LPCSTR lpszStructType, const BYTE *pbEncoded, DWORD cbEncoded, DWORD dwFlags,
2054  PCRYPT_DECODE_PARA pDecodePara, void *pvStructInfo, DWORD *pcbStructInfo)
2055 {
2056     DWORD bytesNeeded, dataLen;
2057     BYTE lenBytes;
2058     CRYPT_INTEGER_BLOB *blob;
2059
2060     if (!pbEncoded)
2061     {
2062         SetLastError(CRYPT_E_ASN1_EOD);
2063         return FALSE;
2064     }
2065     if (!CRYPT_GetLen(pbEncoded, cbEncoded, &dataLen))
2066         return FALSE;
2067     if (pbEncoded[0] != ASN_INTEGER)
2068     {
2069         SetLastError(CRYPT_E_ASN1_BADTAG);
2070         return FALSE;
2071     }
2072     lenBytes = GET_LEN_BYTES(pbEncoded[1]);
2073     bytesNeeded = dataLen + sizeof(CRYPT_INTEGER_BLOB);
2074     if (!pvStructInfo)
2075     {
2076         *pcbStructInfo = bytesNeeded;
2077         return TRUE;
2078     }
2079     if (!CRYPT_DecodeEnsureSpace(dwFlags, pDecodePara, pvStructInfo,
2080      pcbStructInfo, bytesNeeded))
2081         return FALSE;
2082     if (dwFlags & CRYPT_DECODE_ALLOC_FLAG)
2083         pvStructInfo = *(BYTE **)pvStructInfo;
2084     blob = (CRYPT_INTEGER_BLOB *)pvStructInfo;
2085     blob->cbData = dataLen;
2086     blob->pbData = (BYTE *)pvStructInfo + sizeof(CRYPT_INTEGER_BLOB);
2087     if (blob->cbData)
2088     {
2089         DWORD i;
2090
2091         for (i = 0; i < blob->cbData; i++)
2092             blob->pbData[i] = *(pbEncoded + 1 + lenBytes + dataLen - i - 1);
2093     }
2094     return TRUE;
2095 }
2096
2097 static BOOL WINAPI CRYPT_AsnDecodeUnsignedInteger(DWORD dwCertEncodingType,
2098  LPCSTR lpszStructType, const BYTE *pbEncoded, DWORD cbEncoded, DWORD dwFlags,
2099  PCRYPT_DECODE_PARA pDecodePara, void *pvStructInfo, DWORD *pcbStructInfo)
2100 {
2101     DWORD bytesNeeded, dataLen;
2102     BYTE lenBytes;
2103     CRYPT_INTEGER_BLOB *blob;
2104
2105     if (!pbEncoded)
2106     {
2107         SetLastError(CRYPT_E_ASN1_EOD);
2108         return FALSE;
2109     }
2110     if (!CRYPT_GetLen(pbEncoded, cbEncoded, &dataLen))
2111         return FALSE;
2112     if (pbEncoded[0] != ASN_INTEGER)
2113     {
2114         SetLastError(CRYPT_E_ASN1_BADTAG);
2115         return FALSE;
2116     }
2117     lenBytes = GET_LEN_BYTES(pbEncoded[1]);
2118     bytesNeeded = dataLen + sizeof(CRYPT_INTEGER_BLOB);
2119     if (!pvStructInfo)
2120     {
2121         *pcbStructInfo = bytesNeeded;
2122         return TRUE;
2123     }
2124     if (!CRYPT_DecodeEnsureSpace(dwFlags, pDecodePara, pvStructInfo,
2125      pcbStructInfo, bytesNeeded))
2126         return FALSE;
2127     if (dwFlags & CRYPT_DECODE_ALLOC_FLAG)
2128         pvStructInfo = *(BYTE **)pvStructInfo;
2129     blob = (CRYPT_INTEGER_BLOB *)pvStructInfo;
2130     blob->cbData = dataLen;
2131     blob->pbData = (BYTE *)pvStructInfo + sizeof(CRYPT_INTEGER_BLOB);
2132     /* remove leading zero byte if it exists */
2133     if (blob->cbData && *(pbEncoded + 1 + lenBytes) == 0)
2134     {
2135         blob->cbData--;
2136         blob->pbData++;
2137     }
2138     if (blob->cbData)
2139     {
2140         DWORD i;
2141
2142         for (i = 0; i < blob->cbData; i++)
2143             blob->pbData[i] = *(pbEncoded + 1 + lenBytes + pbEncoded[1] - i -
2144              1);
2145     }
2146     return TRUE;
2147 }
2148
2149 static BOOL WINAPI CRYPT_AsnDecodeEnumerated(DWORD dwCertEncodingType,
2150  LPCSTR lpszStructType, const BYTE *pbEncoded, DWORD cbEncoded, DWORD dwFlags,
2151  PCRYPT_DECODE_PARA pDecodePara, void *pvStructInfo, DWORD *pcbStructInfo)
2152 {
2153     unsigned int val = 0, i;
2154
2155     /* Based on CRYPT_AsnDecodeInt, but interprets as unsigned */
2156     if (!pbEncoded || !cbEncoded)
2157     {
2158         SetLastError(CRYPT_E_ASN1_EOD);
2159         return FALSE;
2160     }
2161     if (!pvStructInfo)
2162     {
2163         *pcbStructInfo = sizeof(int);
2164         return TRUE;
2165     }
2166     if (pbEncoded[0] != ASN_ENUMERATED)
2167     {
2168         SetLastError(CRYPT_E_ASN1_BADTAG);
2169         return FALSE;
2170     }
2171     if (cbEncoded <= 1)
2172     {
2173         SetLastError(CRYPT_E_ASN1_EOD);
2174         return FALSE;
2175     }
2176     if (pbEncoded[1] == 0)
2177     {
2178         SetLastError(CRYPT_E_ASN1_CORRUPT);
2179         return FALSE;
2180     }
2181     /* A little strange looking, but we have to accept a sign byte: 0xffffffff
2182      * gets encoded as 0a 05 00 ff ff ff ff.  Also, assuming a small length is
2183      * okay here, it has to be in short form.
2184      */
2185     if (pbEncoded[1] > sizeof(unsigned int) + 1)
2186     {
2187         SetLastError(CRYPT_E_ASN1_LARGE);
2188         return FALSE;
2189     }
2190     for (i = 0; i < pbEncoded[1]; i++)
2191     {
2192         val <<= 8;
2193         val |= pbEncoded[2 + i];
2194     }
2195     if (!CRYPT_DecodeEnsureSpace(dwFlags, pDecodePara, pvStructInfo,
2196      pcbStructInfo, sizeof(unsigned int)))
2197         return FALSE;
2198     if (dwFlags & CRYPT_DECODE_ALLOC_FLAG)
2199         pvStructInfo = *(BYTE **)pvStructInfo;
2200     memcpy(pvStructInfo, &val, sizeof(unsigned int));
2201     return TRUE;
2202 }
2203
2204 #define CRYPT_TIME_GET_DIGITS(pbEncoded, len, numDigits, word) \
2205  do { \
2206     BYTE i; \
2207  \
2208     (word) = 0; \
2209     for (i = 0; (len) > 0 && i < (numDigits); i++, (len)--) \
2210     { \
2211         if (!isdigit(*(pbEncoded))) \
2212         { \
2213             SetLastError(CRYPT_E_ASN1_CORRUPT); \
2214             return FALSE; \
2215         } \
2216         (word) *= 10; \
2217         (word) += *(pbEncoded)++ - '0'; \
2218     } \
2219  } while (0)
2220
2221 static BOOL CRYPT_AsnDecodeTimeZone(const BYTE *pbEncoded, DWORD len,
2222  SYSTEMTIME *sysTime)
2223 {
2224     BOOL ret = TRUE;
2225
2226     if (len >= 3 && (*pbEncoded == '+' || *pbEncoded == '-'))
2227     {
2228         WORD hours, minutes = 0;
2229         BYTE sign = *pbEncoded++;
2230
2231         len--;
2232         CRYPT_TIME_GET_DIGITS(pbEncoded, len, 2, hours);
2233         if (hours >= 24)
2234         {
2235             SetLastError(CRYPT_E_ASN1_CORRUPT);
2236             ret = FALSE;
2237             goto end;
2238         }
2239         if (len >= 2)
2240         {
2241             CRYPT_TIME_GET_DIGITS(pbEncoded, len, 2, minutes);
2242             if (minutes >= 60)
2243             {
2244                 SetLastError(CRYPT_E_ASN1_CORRUPT);
2245                 ret = FALSE;
2246                 goto end;
2247             }
2248         }
2249         if (sign == '+')
2250         {
2251             sysTime->wHour += hours;
2252             sysTime->wMinute += minutes;
2253         }
2254         else
2255         {
2256             if (hours > sysTime->wHour)
2257             {
2258                 sysTime->wDay--;
2259                 sysTime->wHour = 24 - (hours - sysTime->wHour);
2260             }
2261             else
2262                 sysTime->wHour -= hours;
2263             if (minutes > sysTime->wMinute)
2264             {
2265                 sysTime->wHour--;
2266                 sysTime->wMinute = 60 - (minutes - sysTime->wMinute);
2267             }
2268             else
2269                 sysTime->wMinute -= minutes;
2270         }
2271     }
2272 end:
2273     return ret;
2274 }
2275
2276 static BOOL WINAPI CRYPT_AsnDecodeUtcTime(DWORD dwCertEncodingType,
2277  LPCSTR lpszStructType, const BYTE *pbEncoded, DWORD cbEncoded, DWORD dwFlags,
2278  PCRYPT_DECODE_PARA pDecodePara, void *pvStructInfo, DWORD *pcbStructInfo)
2279 {
2280     SYSTEMTIME sysTime = { 0 };
2281     BYTE len;
2282     BOOL ret = TRUE;
2283
2284     if (!pbEncoded || !cbEncoded)
2285     {
2286         SetLastError(CRYPT_E_ASN1_EOD);
2287         return FALSE;
2288     }
2289     if (!pvStructInfo)
2290     {
2291         *pcbStructInfo = sizeof(FILETIME);
2292         return TRUE;
2293     }
2294     if (pbEncoded[0] != ASN_UTCTIME)
2295     {
2296         SetLastError(CRYPT_E_ASN1_BADTAG);
2297         return FALSE;
2298     }
2299     if (cbEncoded <= 1)
2300     {
2301         SetLastError(CRYPT_E_ASN1_EOD);
2302         return FALSE;
2303     }
2304     if (pbEncoded[1] > 0x7f)
2305     {
2306         /* long-form date strings really can't be valid */
2307         SetLastError(CRYPT_E_ASN1_CORRUPT);
2308         return FALSE;
2309     }
2310     len = pbEncoded[1];
2311     /* FIXME: magic # */
2312     if (len < 10)
2313     {
2314         SetLastError(CRYPT_E_ASN1_CORRUPT);
2315         return FALSE;
2316     }
2317     pbEncoded += 2;
2318     CRYPT_TIME_GET_DIGITS(pbEncoded, len, 2, sysTime.wYear);
2319     if (sysTime.wYear >= 50)
2320         sysTime.wYear += 1900;
2321     else
2322         sysTime.wYear += 2000;
2323     CRYPT_TIME_GET_DIGITS(pbEncoded, len, 2, sysTime.wMonth);
2324     CRYPT_TIME_GET_DIGITS(pbEncoded, len, 2, sysTime.wDay);
2325     CRYPT_TIME_GET_DIGITS(pbEncoded, len, 2, sysTime.wHour);
2326     CRYPT_TIME_GET_DIGITS(pbEncoded, len, 2, sysTime.wMinute);
2327     if (len > 0)
2328     {
2329         if (len >= 2 && isdigit(*pbEncoded) && isdigit(*(pbEncoded + 1)))
2330             CRYPT_TIME_GET_DIGITS(pbEncoded, len, 2, sysTime.wSecond);
2331         else if (isdigit(*pbEncoded))
2332             CRYPT_TIME_GET_DIGITS(pbEncoded, len, 1, sysTime.wSecond);
2333         ret = CRYPT_AsnDecodeTimeZone(pbEncoded, len, &sysTime);
2334     }
2335     if (ret)
2336     {
2337         if (!CRYPT_DecodeEnsureSpace(dwFlags, pDecodePara, pvStructInfo,
2338          pcbStructInfo, sizeof(FILETIME)))
2339             ret = FALSE;
2340         else
2341         {
2342             if (dwFlags & CRYPT_DECODE_ALLOC_FLAG)
2343                 pvStructInfo = *(BYTE **)pvStructInfo;
2344             ret = SystemTimeToFileTime(&sysTime, (FILETIME *)pvStructInfo);
2345         }
2346     }
2347     return ret;
2348 }
2349
2350 static BOOL WINAPI CRYPT_AsnDecodeGeneralizedTime(DWORD dwCertEncodingType,
2351  LPCSTR lpszStructType, const BYTE *pbEncoded, DWORD cbEncoded, DWORD dwFlags,
2352  PCRYPT_DECODE_PARA pDecodePara, void *pvStructInfo, DWORD *pcbStructInfo)
2353 {
2354     SYSTEMTIME sysTime = { 0 };
2355     BYTE len;
2356     BOOL ret = TRUE;
2357
2358     if (!pbEncoded || !cbEncoded)
2359     {
2360         SetLastError(CRYPT_E_ASN1_EOD);
2361         return FALSE;
2362     }
2363     if (!pvStructInfo)
2364     {
2365         *pcbStructInfo = sizeof(FILETIME);
2366         return TRUE;
2367     }
2368     if (pbEncoded[0] != ASN_GENERALTIME)
2369     {
2370         SetLastError(CRYPT_E_ASN1_BADTAG);
2371         return FALSE;
2372     }
2373     if (cbEncoded <= 1)
2374     {
2375         SetLastError(CRYPT_E_ASN1_EOD);
2376         return FALSE;
2377     }
2378     if (pbEncoded[1] > 0x7f)
2379     {
2380         /* long-form date strings really can't be valid */
2381         SetLastError(CRYPT_E_ASN1_CORRUPT);
2382         return FALSE;
2383     }
2384     len = pbEncoded[1];
2385     /* FIXME: magic # */
2386     if (len < 10)
2387     {
2388         SetLastError(CRYPT_E_ASN1_CORRUPT);
2389         return FALSE;
2390     }
2391     pbEncoded += 2;
2392     CRYPT_TIME_GET_DIGITS(pbEncoded, len, 4, sysTime.wYear);
2393     CRYPT_TIME_GET_DIGITS(pbEncoded, len, 2, sysTime.wMonth);
2394     CRYPT_TIME_GET_DIGITS(pbEncoded, len, 2, sysTime.wDay);
2395     CRYPT_TIME_GET_DIGITS(pbEncoded, len, 2, sysTime.wHour);
2396     if (len > 0)
2397     {
2398         CRYPT_TIME_GET_DIGITS(pbEncoded, len, 2, sysTime.wMinute);
2399         if (len > 0)
2400             CRYPT_TIME_GET_DIGITS(pbEncoded, len, 2, sysTime.wSecond);
2401         if (len > 0 && (*pbEncoded == '.' || *pbEncoded == ','))
2402         {
2403             BYTE digits;
2404
2405             pbEncoded++;
2406             len--;
2407             digits = min(len, 3); /* workaround macro weirdness */
2408             CRYPT_TIME_GET_DIGITS(pbEncoded, len, digits,
2409              sysTime.wMilliseconds);
2410         }
2411         ret = CRYPT_AsnDecodeTimeZone(pbEncoded, len, &sysTime);
2412     }
2413     if (ret)
2414     {
2415         if (!CRYPT_DecodeEnsureSpace(dwFlags, pDecodePara, pvStructInfo,
2416          pcbStructInfo, sizeof(FILETIME)))
2417             ret = FALSE;
2418         else
2419         {
2420             if (dwFlags & CRYPT_DECODE_ALLOC_FLAG)
2421                 pvStructInfo = *(BYTE **)pvStructInfo;
2422             ret = SystemTimeToFileTime(&sysTime, (FILETIME *)pvStructInfo);
2423         }
2424     }
2425     return ret;
2426 }
2427
2428 static BOOL WINAPI CRYPT_AsnDecodeChoiceOfTime(DWORD dwCertEncodingType,
2429  LPCSTR lpszStructType, const BYTE *pbEncoded, DWORD cbEncoded, DWORD dwFlags,
2430  PCRYPT_DECODE_PARA pDecodePara, void *pvStructInfo, DWORD *pcbStructInfo)
2431 {
2432     BOOL ret;
2433
2434     if (!pbEncoded || !cbEncoded)
2435     {
2436         SetLastError(CRYPT_E_ASN1_EOD);
2437         return FALSE;
2438     }
2439     if (!pvStructInfo)
2440     {
2441         *pcbStructInfo = sizeof(FILETIME);
2442         return TRUE;
2443     }
2444
2445     if (pbEncoded[0] == ASN_UTCTIME)
2446         ret = CRYPT_AsnDecodeUtcTime(dwCertEncodingType, lpszStructType,
2447          pbEncoded, cbEncoded, dwFlags, pDecodePara, pvStructInfo,
2448          pcbStructInfo);
2449     else if (pbEncoded[0] == ASN_GENERALTIME)
2450         ret = CRYPT_AsnDecodeGeneralizedTime(dwCertEncodingType,
2451          lpszStructType, pbEncoded, cbEncoded, dwFlags, pDecodePara,
2452          pvStructInfo, pcbStructInfo);
2453     else
2454     {
2455         SetLastError(CRYPT_E_ASN1_BADTAG);
2456         ret = FALSE;
2457     }
2458     return ret;
2459 }
2460
2461 typedef BOOL (WINAPI *CryptDecodeObjectExFunc)(DWORD, LPCSTR, const BYTE *,
2462  DWORD, DWORD, PCRYPT_DECODE_PARA, void *, DWORD *);
2463
2464 BOOL WINAPI CryptDecodeObjectEx(DWORD dwCertEncodingType, LPCSTR lpszStructType,
2465  const BYTE *pbEncoded, DWORD cbEncoded, DWORD dwFlags,
2466  PCRYPT_DECODE_PARA pDecodePara, void *pvStructInfo, DWORD *pcbStructInfo)
2467 {
2468     BOOL ret = FALSE;
2469     HMODULE lib = NULL;
2470     CryptDecodeObjectExFunc decodeFunc = NULL;
2471
2472     TRACE("(0x%08lx, %s, %p, %ld, 0x%08lx, %p, %p, %p)\n",
2473      dwCertEncodingType, HIWORD(lpszStructType) ? debugstr_a(lpszStructType) :
2474      "(integer value)", pbEncoded, cbEncoded, dwFlags, pDecodePara,
2475      pvStructInfo, pcbStructInfo);
2476
2477     if (!pvStructInfo && !pcbStructInfo)
2478     {
2479         SetLastError(ERROR_INVALID_PARAMETER);
2480         return FALSE;
2481     }
2482     if ((dwCertEncodingType & CERT_ENCODING_TYPE_MASK) != X509_ASN_ENCODING
2483      && (dwCertEncodingType & CMSG_ENCODING_TYPE_MASK) != PKCS_7_ASN_ENCODING)
2484     {
2485         SetLastError(ERROR_FILE_NOT_FOUND);
2486         return FALSE;
2487     }
2488
2489     SetLastError(NOERROR);
2490     if (!HIWORD(lpszStructType))
2491     {
2492         switch (LOWORD(lpszStructType))
2493         {
2494         case (WORD)X509_NAME:
2495             decodeFunc = CRYPT_AsnDecodeName;
2496             break;
2497         case (WORD)X509_OCTET_STRING:
2498             decodeFunc = CRYPT_AsnDecodeOctets;
2499             break;
2500         case (WORD)X509_BITS:
2501         case (WORD)X509_KEY_USAGE:
2502             decodeFunc = CRYPT_AsnDecodeBits;
2503             break;
2504         case (WORD)X509_INTEGER:
2505             decodeFunc = CRYPT_AsnDecodeInt;
2506             break;
2507         case (WORD)X509_MULTI_BYTE_INTEGER:
2508             decodeFunc = CRYPT_AsnDecodeInteger;
2509             break;
2510         case (WORD)X509_MULTI_BYTE_UINT:
2511             decodeFunc = CRYPT_AsnDecodeUnsignedInteger;
2512             break;
2513         case (WORD)X509_ENUMERATED:
2514             decodeFunc = CRYPT_AsnDecodeEnumerated;
2515             break;
2516         case (WORD)X509_CHOICE_OF_TIME:
2517             decodeFunc = CRYPT_AsnDecodeChoiceOfTime;
2518             break;
2519         case (WORD)PKCS_UTC_TIME:
2520             decodeFunc = CRYPT_AsnDecodeUtcTime;
2521             break;
2522         default:
2523             FIXME("%d: unimplemented\n", LOWORD(lpszStructType));
2524         }
2525     }
2526     else if (!strcmp(lpszStructType, szOID_RSA_signingTime))
2527         decodeFunc = CRYPT_AsnDecodeUtcTime;
2528     else if (!strcmp(lpszStructType, szOID_CRL_REASON_CODE))
2529         decodeFunc = CRYPT_AsnDecodeEnumerated;
2530     else if (!strcmp(lpszStructType, szOID_KEY_USAGE))
2531         decodeFunc = CRYPT_AsnDecodeBits;
2532     else if (!strcmp(lpszStructType, szOID_SUBJECT_KEY_IDENTIFIER))
2533         decodeFunc = CRYPT_AsnDecodeOctets;
2534     if (!decodeFunc)
2535         decodeFunc = (CryptDecodeObjectExFunc)CRYPT_GetFunc(dwCertEncodingType,
2536          lpszStructType, "CryptDecodeObjectEx", &lib);
2537     if (decodeFunc)
2538         ret = decodeFunc(dwCertEncodingType, lpszStructType, pbEncoded,
2539          cbEncoded, dwFlags, pDecodePara, pvStructInfo, pcbStructInfo);
2540     else
2541         SetLastError(ERROR_FILE_NOT_FOUND);
2542     if (lib)
2543         FreeLibrary(lib);
2544     return ret;
2545 }