kernel32/tests: Add tests for the FALSE pathway of GetCurrentConsoleFont.
[wine/multimedia.git] / dlls / crypt32 / cert.c
bloba4b43ff1555037138d5b6dce89458e8f02464ffa
1 /*
2 * Copyright 2004-2006 Juan Lang
4 * This library is free software; you can redistribute it and/or
5 * modify it under the terms of the GNU Lesser General Public
6 * License as published by the Free Software Foundation; either
7 * version 2.1 of the License, or (at your option) any later version.
9 * This library is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
12 * Lesser General Public License for more details.
14 * You should have received a copy of the GNU Lesser General Public
15 * 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
20 #include <assert.h>
21 #include <stdarg.h>
23 #define NONAMELESSUNION
24 #include "windef.h"
25 #include "winbase.h"
26 #include "wincrypt.h"
27 #include "winnls.h"
28 #include "rpc.h"
29 #include "wine/debug.h"
30 #include "wine/unicode.h"
31 #include "crypt32_private.h"
33 WINE_DEFAULT_DEBUG_CHANNEL(crypt);
35 /* Internal version of CertGetCertificateContextProperty that gets properties
36 * directly from the context (or the context it's linked to, depending on its
37 * type.) Doesn't handle special-case properties, since they are handled by
38 * CertGetCertificateContextProperty, and are particular to the store in which
39 * the property exists (which is separate from the context.)
41 static BOOL CertContext_GetProperty(cert_t *cert, DWORD dwPropId,
42 void *pvData, DWORD *pcbData);
44 /* Internal version of CertSetCertificateContextProperty that sets properties
45 * directly on the context (or the context it's linked to, depending on its
46 * type.) Doesn't handle special cases, since they're handled by
47 * CertSetCertificateContextProperty anyway.
49 static BOOL CertContext_SetProperty(cert_t *cert, DWORD dwPropId,
50 DWORD dwFlags, const void *pvData);
52 BOOL WINAPI CertAddEncodedCertificateToStore(HCERTSTORE hCertStore,
53 DWORD dwCertEncodingType, const BYTE *pbCertEncoded, DWORD cbCertEncoded,
54 DWORD dwAddDisposition, PCCERT_CONTEXT *ppCertContext)
56 PCCERT_CONTEXT cert = CertCreateCertificateContext(dwCertEncodingType,
57 pbCertEncoded, cbCertEncoded);
58 BOOL ret;
60 TRACE("(%p, %08x, %p, %d, %08x, %p)\n", hCertStore, dwCertEncodingType,
61 pbCertEncoded, cbCertEncoded, dwAddDisposition, ppCertContext);
63 if (cert)
65 ret = CertAddCertificateContextToStore(hCertStore, cert,
66 dwAddDisposition, ppCertContext);
67 CertFreeCertificateContext(cert);
69 else
70 ret = FALSE;
71 return ret;
74 BOOL WINAPI CertAddEncodedCertificateToSystemStoreA(LPCSTR pszCertStoreName,
75 const BYTE *pbCertEncoded, DWORD cbCertEncoded)
77 HCERTSTORE store;
78 BOOL ret = FALSE;
80 TRACE("(%s, %p, %d)\n", debugstr_a(pszCertStoreName), pbCertEncoded,
81 cbCertEncoded);
83 store = CertOpenSystemStoreA(0, pszCertStoreName);
84 if (store)
86 ret = CertAddEncodedCertificateToStore(store, X509_ASN_ENCODING,
87 pbCertEncoded, cbCertEncoded, CERT_STORE_ADD_USE_EXISTING, NULL);
88 CertCloseStore(store, 0);
90 return ret;
93 BOOL WINAPI CertAddEncodedCertificateToSystemStoreW(LPCWSTR pszCertStoreName,
94 const BYTE *pbCertEncoded, DWORD cbCertEncoded)
96 HCERTSTORE store;
97 BOOL ret = FALSE;
99 TRACE("(%s, %p, %d)\n", debugstr_w(pszCertStoreName), pbCertEncoded,
100 cbCertEncoded);
102 store = CertOpenSystemStoreW(0, pszCertStoreName);
103 if (store)
105 ret = CertAddEncodedCertificateToStore(store, X509_ASN_ENCODING,
106 pbCertEncoded, cbCertEncoded, CERT_STORE_ADD_USE_EXISTING, NULL);
107 CertCloseStore(store, 0);
109 return ret;
112 static const context_vtbl_t cert_vtbl;
114 static void Cert_free(context_t *context)
116 cert_t *cert = (cert_t*)context;
118 CryptMemFree(cert->ctx.pbCertEncoded);
119 LocalFree(cert->ctx.pCertInfo);
122 static context_t *Cert_clone(context_t *context, WINECRYPT_CERTSTORE *store, BOOL use_link)
124 cert_t *cert;
126 if(use_link) {
127 cert = (cert_t*)Context_CreateLinkContext(sizeof(CERT_CONTEXT), context, store);
128 if(!cert)
129 return NULL;
130 }else {
131 const cert_t *cloned = (const cert_t*)context;
132 DWORD size = 0;
133 BOOL res;
135 cert = (cert_t*)Context_CreateDataContext(sizeof(CERT_CONTEXT), &cert_vtbl, store);
136 if(!cert)
137 return NULL;
139 Context_CopyProperties(&cert->ctx, &cloned->ctx);
141 cert->ctx.dwCertEncodingType = cloned->ctx.dwCertEncodingType;
142 cert->ctx.pbCertEncoded = CryptMemAlloc(cloned->ctx.cbCertEncoded);
143 memcpy(cert->ctx.pbCertEncoded, cloned->ctx.pbCertEncoded, cloned->ctx.cbCertEncoded);
144 cert->ctx.cbCertEncoded = cloned->ctx.cbCertEncoded;
146 /* FIXME: We don't need to decode the object here, we could just clone cert info. */
147 res = CryptDecodeObjectEx(cert->ctx.dwCertEncodingType, X509_CERT_TO_BE_SIGNED,
148 cert->ctx.pbCertEncoded, cert->ctx.cbCertEncoded, CRYPT_DECODE_ALLOC_FLAG, NULL,
149 &cert->ctx.pCertInfo, &size);
150 if(!res) {
151 CertFreeCertificateContext(&cert->ctx);
152 return NULL;
156 cert->ctx.hCertStore = store;
157 return &cert->base;
160 static const context_vtbl_t cert_vtbl = {
161 Cert_free,
162 Cert_clone
165 static BOOL add_cert_to_store(WINECRYPT_CERTSTORE *store, const CERT_CONTEXT *cert,
166 DWORD add_disposition, BOOL use_link, PCCERT_CONTEXT *ret_context)
168 const CERT_CONTEXT *existing = NULL;
169 BOOL ret = TRUE, inherit_props = FALSE;
170 context_t *new_context = NULL;
172 switch (add_disposition)
174 case CERT_STORE_ADD_ALWAYS:
175 break;
176 case CERT_STORE_ADD_NEW:
177 case CERT_STORE_ADD_REPLACE_EXISTING:
178 case CERT_STORE_ADD_REPLACE_EXISTING_INHERIT_PROPERTIES:
179 case CERT_STORE_ADD_USE_EXISTING:
180 case CERT_STORE_ADD_NEWER:
181 case CERT_STORE_ADD_NEWER_INHERIT_PROPERTIES:
183 BYTE hashToAdd[20];
184 DWORD size = sizeof(hashToAdd);
186 ret = CertGetCertificateContextProperty(cert, CERT_HASH_PROP_ID,
187 hashToAdd, &size);
188 if (ret)
190 CRYPT_HASH_BLOB blob = { sizeof(hashToAdd), hashToAdd };
192 existing = CertFindCertificateInStore(store, cert->dwCertEncodingType, 0,
193 CERT_FIND_SHA1_HASH, &blob, NULL);
195 break;
197 default:
198 FIXME("Unimplemented add disposition %d\n", add_disposition);
199 SetLastError(E_INVALIDARG);
200 return FALSE;
203 switch (add_disposition)
205 case CERT_STORE_ADD_ALWAYS:
206 break;
207 case CERT_STORE_ADD_NEW:
208 if (existing)
210 TRACE("found matching certificate, not adding\n");
211 SetLastError(CRYPT_E_EXISTS);
212 return FALSE;
214 break;
215 case CERT_STORE_ADD_REPLACE_EXISTING:
216 break;
217 case CERT_STORE_ADD_REPLACE_EXISTING_INHERIT_PROPERTIES:
218 if (use_link)
219 FIXME("CERT_STORE_ADD_REPLACE_EXISTING_INHERIT_PROPERTIES: semi-stub for links\n");
220 if (existing)
221 inherit_props = TRUE;
222 break;
223 case CERT_STORE_ADD_USE_EXISTING:
224 if(use_link)
225 FIXME("CERT_STORE_ADD_USE_EXISTING: semi-stub for links\n");
226 if (existing)
228 Context_CopyProperties(existing, cert);
229 if (ret_context)
230 *ret_context = CertDuplicateCertificateContext(existing);
231 return TRUE;
233 break;
234 case CERT_STORE_ADD_NEWER:
235 if (existing && CompareFileTime(&existing->pCertInfo->NotBefore, &cert->pCertInfo->NotBefore) >= 0)
237 TRACE("existing certificate is newer, not adding\n");
238 SetLastError(CRYPT_E_EXISTS);
239 return FALSE;
241 break;
242 case CERT_STORE_ADD_NEWER_INHERIT_PROPERTIES:
243 if (existing)
245 if (CompareFileTime(&existing->pCertInfo->NotBefore, &cert->pCertInfo->NotBefore) >= 0)
247 TRACE("existing certificate is newer, not adding\n");
248 SetLastError(CRYPT_E_EXISTS);
249 return FALSE;
251 inherit_props = TRUE;
253 break;
256 /* FIXME: We have tests that this works, but what should we really do in this case? */
257 if(!store) {
258 if(ret_context)
259 *ret_context = CertDuplicateCertificateContext(cert);
260 return TRUE;
263 ret = store->vtbl->certs.addContext(store, context_from_ptr(cert), existing ? context_from_ptr(existing) : NULL,
264 (ret_context || inherit_props) ? &new_context : NULL, use_link);
265 if(!ret)
266 return FALSE;
268 if(inherit_props)
269 Context_CopyProperties(context_ptr(new_context), existing);
271 if(ret_context)
272 *ret_context = context_ptr(new_context);
273 else if(new_context)
274 Context_Release(new_context);
276 TRACE("returning %d\n", ret);
277 return ret;
280 BOOL WINAPI CertAddCertificateContextToStore(HCERTSTORE hCertStore, PCCERT_CONTEXT pCertContext,
281 DWORD dwAddDisposition, PCCERT_CONTEXT *ppStoreContext)
283 WINECRYPT_CERTSTORE *store = hCertStore;
285 TRACE("(%p, %p, %08x, %p)\n", hCertStore, pCertContext, dwAddDisposition, ppStoreContext);
287 return add_cert_to_store(store, pCertContext, dwAddDisposition, FALSE, ppStoreContext);
290 BOOL WINAPI CertAddCertificateLinkToStore(HCERTSTORE hCertStore,
291 PCCERT_CONTEXT pCertContext, DWORD dwAddDisposition,
292 PCCERT_CONTEXT *ppCertContext)
294 static int calls;
295 WINECRYPT_CERTSTORE *store = (WINECRYPT_CERTSTORE*)hCertStore;
297 if (!(calls++))
298 FIXME("(%p, %p, %08x, %p): semi-stub\n", hCertStore, pCertContext,
299 dwAddDisposition, ppCertContext);
300 if (store->dwMagic != WINE_CRYPTCERTSTORE_MAGIC)
301 return FALSE;
302 if (store->type == StoreTypeCollection)
304 SetLastError(E_INVALIDARG);
305 return FALSE;
307 return add_cert_to_store(hCertStore, pCertContext, dwAddDisposition, TRUE, ppCertContext);
310 PCCERT_CONTEXT WINAPI CertCreateCertificateContext(DWORD dwCertEncodingType,
311 const BYTE *pbCertEncoded, DWORD cbCertEncoded)
313 cert_t *cert = NULL;
314 BYTE *data = NULL;
315 BOOL ret;
316 PCERT_INFO certInfo = NULL;
317 DWORD size = 0;
319 TRACE("(%08x, %p, %d)\n", dwCertEncodingType, pbCertEncoded,
320 cbCertEncoded);
322 if ((dwCertEncodingType & CERT_ENCODING_TYPE_MASK) != X509_ASN_ENCODING)
324 SetLastError(E_INVALIDARG);
325 return NULL;
328 ret = CryptDecodeObjectEx(dwCertEncodingType, X509_CERT_TO_BE_SIGNED,
329 pbCertEncoded, cbCertEncoded, CRYPT_DECODE_ALLOC_FLAG, NULL,
330 &certInfo, &size);
331 if (!ret)
332 return NULL;
334 cert = (cert_t*)Context_CreateDataContext(sizeof(CERT_CONTEXT), &cert_vtbl, &empty_store);
335 if (!cert)
336 return NULL;
337 data = CryptMemAlloc(cbCertEncoded);
338 if (!data)
340 Context_Release(&cert->base);
341 return NULL;
344 memcpy(data, pbCertEncoded, cbCertEncoded);
345 cert->ctx.dwCertEncodingType = dwCertEncodingType;
346 cert->ctx.pbCertEncoded = data;
347 cert->ctx.cbCertEncoded = cbCertEncoded;
348 cert->ctx.pCertInfo = certInfo;
349 cert->ctx.hCertStore = &empty_store;
351 return &cert->ctx;
354 PCCERT_CONTEXT WINAPI CertDuplicateCertificateContext(PCCERT_CONTEXT pCertContext)
356 TRACE("(%p)\n", pCertContext);
358 if (!pCertContext)
359 return NULL;
361 Context_AddRef(&cert_from_ptr(pCertContext)->base);
362 return pCertContext;
365 BOOL WINAPI CertFreeCertificateContext(PCCERT_CONTEXT pCertContext)
367 TRACE("(%p)\n", pCertContext);
369 if (pCertContext)
370 Context_Release(&cert_from_ptr(pCertContext)->base);
371 return TRUE;
374 DWORD WINAPI CertEnumCertificateContextProperties(PCCERT_CONTEXT pCertContext,
375 DWORD dwPropId)
377 cert_t *cert = cert_from_ptr(pCertContext);
378 DWORD ret;
380 TRACE("(%p, %d)\n", pCertContext, dwPropId);
382 if (cert->base.properties)
383 ret = ContextPropertyList_EnumPropIDs(cert->base.properties, dwPropId);
384 else
385 ret = 0;
386 return ret;
389 static BOOL CertContext_GetHashProp(cert_t *cert, DWORD dwPropId,
390 ALG_ID algID, const BYTE *toHash, DWORD toHashLen, void *pvData,
391 DWORD *pcbData)
393 BOOL ret = CryptHashCertificate(0, algID, 0, toHash, toHashLen, pvData,
394 pcbData);
395 if (ret && pvData)
397 CRYPT_DATA_BLOB blob = { *pcbData, pvData };
399 ret = CertContext_SetProperty(cert, dwPropId, 0, &blob);
401 return ret;
404 static BOOL CertContext_CopyParam(void *pvData, DWORD *pcbData, const void *pb,
405 DWORD cb)
407 BOOL ret = TRUE;
409 if (!pvData)
410 *pcbData = cb;
411 else if (*pcbData < cb)
413 SetLastError(ERROR_MORE_DATA);
414 *pcbData = cb;
415 ret = FALSE;
417 else
419 memcpy(pvData, pb, cb);
420 *pcbData = cb;
422 return ret;
425 static BOOL CertContext_GetProperty(cert_t *cert, DWORD dwPropId,
426 void *pvData, DWORD *pcbData)
428 BOOL ret;
429 CRYPT_DATA_BLOB blob;
431 TRACE("(%p, %d, %p, %p)\n", cert, dwPropId, pvData, pcbData);
433 if (cert->base.properties)
434 ret = ContextPropertyList_FindProperty(cert->base.properties, dwPropId, &blob);
435 else
436 ret = FALSE;
437 if (ret)
438 ret = CertContext_CopyParam(pvData, pcbData, blob.pbData, blob.cbData);
439 else
441 /* Implicit properties */
442 switch (dwPropId)
444 case CERT_SHA1_HASH_PROP_ID:
445 ret = CertContext_GetHashProp(cert, dwPropId, CALG_SHA1,
446 cert->ctx.pbCertEncoded, cert->ctx.cbCertEncoded, pvData,
447 pcbData);
448 break;
449 case CERT_MD5_HASH_PROP_ID:
450 ret = CertContext_GetHashProp(cert, dwPropId, CALG_MD5,
451 cert->ctx.pbCertEncoded, cert->ctx.cbCertEncoded, pvData,
452 pcbData);
453 break;
454 case CERT_SUBJECT_NAME_MD5_HASH_PROP_ID:
455 ret = CertContext_GetHashProp(cert, dwPropId, CALG_MD5,
456 cert->ctx.pCertInfo->Subject.pbData,
457 cert->ctx.pCertInfo->Subject.cbData,
458 pvData, pcbData);
459 break;
460 case CERT_SUBJECT_PUBLIC_KEY_MD5_HASH_PROP_ID:
461 ret = CertContext_GetHashProp(cert, dwPropId, CALG_MD5,
462 cert->ctx.pCertInfo->SubjectPublicKeyInfo.PublicKey.pbData,
463 cert->ctx.pCertInfo->SubjectPublicKeyInfo.PublicKey.cbData,
464 pvData, pcbData);
465 break;
466 case CERT_ISSUER_SERIAL_NUMBER_MD5_HASH_PROP_ID:
467 ret = CertContext_GetHashProp(cert, dwPropId, CALG_MD5,
468 cert->ctx.pCertInfo->SerialNumber.pbData,
469 cert->ctx.pCertInfo->SerialNumber.cbData,
470 pvData, pcbData);
471 break;
472 case CERT_SIGNATURE_HASH_PROP_ID:
473 ret = CryptHashToBeSigned(0, cert->ctx.dwCertEncodingType,
474 cert->ctx.pbCertEncoded, cert->ctx.cbCertEncoded, pvData,
475 pcbData);
476 if (ret && pvData)
478 CRYPT_DATA_BLOB blob = { *pcbData, pvData };
480 ret = CertContext_SetProperty(cert, dwPropId, 0, &blob);
482 break;
483 case CERT_KEY_IDENTIFIER_PROP_ID:
485 PCERT_EXTENSION ext = CertFindExtension(
486 szOID_SUBJECT_KEY_IDENTIFIER, cert->ctx.pCertInfo->cExtension,
487 cert->ctx.pCertInfo->rgExtension);
489 if (ext)
491 CRYPT_DATA_BLOB value;
492 DWORD size = sizeof(value);
494 ret = CryptDecodeObjectEx(X509_ASN_ENCODING,
495 szOID_SUBJECT_KEY_IDENTIFIER, ext->Value.pbData,
496 ext->Value.cbData, CRYPT_DECODE_NOCOPY_FLAG, NULL, &value,
497 &size);
498 if (ret)
500 ret = CertContext_CopyParam(pvData, pcbData, value.pbData,
501 value.cbData);
502 CertContext_SetProperty(cert, dwPropId, 0, &value);
505 else
506 SetLastError(ERROR_INVALID_DATA);
507 break;
509 default:
510 SetLastError(CRYPT_E_NOT_FOUND);
513 TRACE("returning %d\n", ret);
514 return ret;
517 void CRYPT_FixKeyProvInfoPointers(PCRYPT_KEY_PROV_INFO info)
519 DWORD i, containerLen, provNameLen;
520 LPBYTE data = (LPBYTE)info + sizeof(CRYPT_KEY_PROV_INFO);
522 info->pwszContainerName = (LPWSTR)data;
523 containerLen = (lstrlenW(info->pwszContainerName) + 1) * sizeof(WCHAR);
524 data += containerLen;
526 info->pwszProvName = (LPWSTR)data;
527 provNameLen = (lstrlenW(info->pwszProvName) + 1) * sizeof(WCHAR);
528 data += provNameLen;
530 info->rgProvParam = (PCRYPT_KEY_PROV_PARAM)data;
531 data += info->cProvParam * sizeof(CRYPT_KEY_PROV_PARAM);
533 for (i = 0; i < info->cProvParam; i++)
535 info->rgProvParam[i].pbData = data;
536 data += info->rgProvParam[i].cbData;
540 BOOL WINAPI CertGetCertificateContextProperty(PCCERT_CONTEXT pCertContext,
541 DWORD dwPropId, void *pvData, DWORD *pcbData)
543 cert_t *cert = cert_from_ptr(pCertContext);
544 BOOL ret;
546 TRACE("(%p, %d, %p, %p)\n", pCertContext, dwPropId, pvData, pcbData);
548 switch (dwPropId)
550 case 0:
551 case CERT_CERT_PROP_ID:
552 case CERT_CRL_PROP_ID:
553 case CERT_CTL_PROP_ID:
554 SetLastError(E_INVALIDARG);
555 ret = FALSE;
556 break;
557 case CERT_ACCESS_STATE_PROP_ID:
558 ret = CertGetStoreProperty(cert->ctx.hCertStore, dwPropId, pvData, pcbData);
559 break;
560 case CERT_KEY_PROV_HANDLE_PROP_ID:
562 CERT_KEY_CONTEXT keyContext;
563 DWORD size = sizeof(keyContext);
565 ret = CertContext_GetProperty(cert,
566 CERT_KEY_CONTEXT_PROP_ID, &keyContext, &size);
567 if (ret)
568 ret = CertContext_CopyParam(pvData, pcbData, &keyContext.hCryptProv,
569 sizeof(keyContext.hCryptProv));
570 break;
572 case CERT_KEY_PROV_INFO_PROP_ID:
573 ret = CertContext_GetProperty(cert, dwPropId, pvData,
574 pcbData);
575 if (ret && pvData)
576 CRYPT_FixKeyProvInfoPointers(pvData);
577 break;
578 default:
579 ret = CertContext_GetProperty(cert, dwPropId, pvData,
580 pcbData);
583 TRACE("returning %d\n", ret);
584 return ret;
587 /* Copies key provider info from from into to, where to is assumed to be a
588 * contiguous buffer of memory large enough for from and all its associated
589 * data, but whose pointers are uninitialized.
590 * Upon return, to contains a contiguous copy of from, packed in the following
591 * order:
592 * - CRYPT_KEY_PROV_INFO
593 * - pwszContainerName
594 * - pwszProvName
595 * - rgProvParam[0]...
597 static void CRYPT_CopyKeyProvInfo(PCRYPT_KEY_PROV_INFO to,
598 const CRYPT_KEY_PROV_INFO *from)
600 DWORD i;
601 LPBYTE nextData = (LPBYTE)to + sizeof(CRYPT_KEY_PROV_INFO);
603 if (from->pwszContainerName)
605 to->pwszContainerName = (LPWSTR)nextData;
606 lstrcpyW(to->pwszContainerName, from->pwszContainerName);
607 nextData += (lstrlenW(from->pwszContainerName) + 1) * sizeof(WCHAR);
609 else
610 to->pwszContainerName = NULL;
611 if (from->pwszProvName)
613 to->pwszProvName = (LPWSTR)nextData;
614 lstrcpyW(to->pwszProvName, from->pwszProvName);
615 nextData += (lstrlenW(from->pwszProvName) + 1) * sizeof(WCHAR);
617 else
618 to->pwszProvName = NULL;
619 to->dwProvType = from->dwProvType;
620 to->dwFlags = from->dwFlags;
621 to->cProvParam = from->cProvParam;
622 to->rgProvParam = (PCRYPT_KEY_PROV_PARAM)nextData;
623 nextData += to->cProvParam * sizeof(CRYPT_KEY_PROV_PARAM);
624 to->dwKeySpec = from->dwKeySpec;
625 for (i = 0; i < to->cProvParam; i++)
627 memcpy(&to->rgProvParam[i], &from->rgProvParam[i],
628 sizeof(CRYPT_KEY_PROV_PARAM));
629 to->rgProvParam[i].pbData = nextData;
630 memcpy(to->rgProvParam[i].pbData, from->rgProvParam[i].pbData,
631 from->rgProvParam[i].cbData);
632 nextData += from->rgProvParam[i].cbData;
636 static BOOL CertContext_SetKeyProvInfoProperty(CONTEXT_PROPERTY_LIST *properties,
637 const CRYPT_KEY_PROV_INFO *info)
639 BOOL ret;
640 LPBYTE buf = NULL;
641 DWORD size = sizeof(CRYPT_KEY_PROV_INFO), i, containerSize, provNameSize;
643 if (info->pwszContainerName)
644 containerSize = (lstrlenW(info->pwszContainerName) + 1) * sizeof(WCHAR);
645 else
646 containerSize = 0;
647 if (info->pwszProvName)
648 provNameSize = (lstrlenW(info->pwszProvName) + 1) * sizeof(WCHAR);
649 else
650 provNameSize = 0;
651 size += containerSize + provNameSize;
652 for (i = 0; i < info->cProvParam; i++)
653 size += sizeof(CRYPT_KEY_PROV_PARAM) + info->rgProvParam[i].cbData;
654 buf = CryptMemAlloc(size);
655 if (buf)
657 CRYPT_CopyKeyProvInfo((PCRYPT_KEY_PROV_INFO)buf, info);
658 ret = ContextPropertyList_SetProperty(properties,
659 CERT_KEY_PROV_INFO_PROP_ID, buf, size);
660 CryptMemFree(buf);
662 else
663 ret = FALSE;
664 return ret;
667 static BOOL CertContext_SetProperty(cert_t *cert, DWORD dwPropId,
668 DWORD dwFlags, const void *pvData)
670 BOOL ret;
672 TRACE("(%p, %d, %08x, %p)\n", cert, dwPropId, dwFlags, pvData);
674 if (!cert->base.properties)
675 ret = FALSE;
676 else
678 switch (dwPropId)
680 case CERT_AUTO_ENROLL_PROP_ID:
681 case CERT_CTL_USAGE_PROP_ID: /* same as CERT_ENHKEY_USAGE_PROP_ID */
682 case CERT_DESCRIPTION_PROP_ID:
683 case CERT_FRIENDLY_NAME_PROP_ID:
684 case CERT_HASH_PROP_ID:
685 case CERT_KEY_IDENTIFIER_PROP_ID:
686 case CERT_MD5_HASH_PROP_ID:
687 case CERT_NEXT_UPDATE_LOCATION_PROP_ID:
688 case CERT_PUBKEY_ALG_PARA_PROP_ID:
689 case CERT_PVK_FILE_PROP_ID:
690 case CERT_SIGNATURE_HASH_PROP_ID:
691 case CERT_ISSUER_PUBLIC_KEY_MD5_HASH_PROP_ID:
692 case CERT_SUBJECT_NAME_MD5_HASH_PROP_ID:
693 case CERT_EXTENDED_ERROR_INFO_PROP_ID:
694 case CERT_SUBJECT_PUBLIC_KEY_MD5_HASH_PROP_ID:
695 case CERT_ENROLLMENT_PROP_ID:
696 case CERT_CROSS_CERT_DIST_POINTS_PROP_ID:
697 case CERT_OCSP_RESPONSE_PROP_ID:
698 case CERT_RENEWAL_PROP_ID:
700 if (pvData)
702 const CRYPT_DATA_BLOB *blob = pvData;
704 ret = ContextPropertyList_SetProperty(cert->base.properties, dwPropId,
705 blob->pbData, blob->cbData);
707 else
709 ContextPropertyList_RemoveProperty(cert->base.properties, dwPropId);
710 ret = TRUE;
712 break;
714 case CERT_DATE_STAMP_PROP_ID:
715 if (pvData)
716 ret = ContextPropertyList_SetProperty(cert->base.properties, dwPropId,
717 pvData, sizeof(FILETIME));
718 else
720 ContextPropertyList_RemoveProperty(cert->base.properties, dwPropId);
721 ret = TRUE;
723 break;
724 case CERT_KEY_CONTEXT_PROP_ID:
726 if (pvData)
728 const CERT_KEY_CONTEXT *keyContext = pvData;
730 if (keyContext->cbSize != sizeof(CERT_KEY_CONTEXT))
732 SetLastError(E_INVALIDARG);
733 ret = FALSE;
735 else
736 ret = ContextPropertyList_SetProperty(cert->base.properties, dwPropId,
737 (const BYTE *)keyContext, keyContext->cbSize);
739 else
741 ContextPropertyList_RemoveProperty(cert->base.properties, dwPropId);
742 ret = TRUE;
744 break;
746 case CERT_KEY_PROV_INFO_PROP_ID:
747 if (pvData)
748 ret = CertContext_SetKeyProvInfoProperty(cert->base.properties, pvData);
749 else
751 ContextPropertyList_RemoveProperty(cert->base.properties, dwPropId);
752 ret = TRUE;
754 break;
755 case CERT_KEY_PROV_HANDLE_PROP_ID:
757 CERT_KEY_CONTEXT keyContext;
758 DWORD size = sizeof(keyContext);
760 ret = CertContext_GetProperty(cert, CERT_KEY_CONTEXT_PROP_ID,
761 &keyContext, &size);
762 if (ret)
764 if (!(dwFlags & CERT_STORE_NO_CRYPT_RELEASE_FLAG))
765 CryptReleaseContext(keyContext.hCryptProv, 0);
767 keyContext.cbSize = sizeof(keyContext);
768 if (pvData)
769 keyContext.hCryptProv = *(const HCRYPTPROV *)pvData;
770 else
772 keyContext.hCryptProv = 0;
773 keyContext.dwKeySpec = AT_SIGNATURE;
775 ret = CertContext_SetProperty(cert, CERT_KEY_CONTEXT_PROP_ID,
776 0, &keyContext);
777 break;
779 default:
780 FIXME("%d: stub\n", dwPropId);
781 ret = FALSE;
784 TRACE("returning %d\n", ret);
785 return ret;
788 BOOL WINAPI CertSetCertificateContextProperty(PCCERT_CONTEXT pCertContext,
789 DWORD dwPropId, DWORD dwFlags, const void *pvData)
791 BOOL ret;
793 TRACE("(%p, %d, %08x, %p)\n", pCertContext, dwPropId, dwFlags, pvData);
795 /* Handle special cases for "read-only"/invalid prop IDs. Windows just
796 * crashes on most of these, I'll be safer.
798 switch (dwPropId)
800 case 0:
801 case CERT_ACCESS_STATE_PROP_ID:
802 case CERT_CERT_PROP_ID:
803 case CERT_CRL_PROP_ID:
804 case CERT_CTL_PROP_ID:
805 SetLastError(E_INVALIDARG);
806 return FALSE;
808 ret = CertContext_SetProperty(cert_from_ptr(pCertContext), dwPropId, dwFlags,
809 pvData);
810 TRACE("returning %d\n", ret);
811 return ret;
814 /* Acquires the private key using the key provider info, retrieving info from
815 * the certificate if info is NULL. The acquired provider is returned in
816 * *phCryptProv, and the key spec for the provider is returned in *pdwKeySpec.
818 static BOOL CRYPT_AcquirePrivateKeyFromProvInfo(PCCERT_CONTEXT pCert,
819 PCRYPT_KEY_PROV_INFO info, HCRYPTPROV *phCryptProv, DWORD *pdwKeySpec)
821 DWORD size = 0;
822 BOOL allocated = FALSE, ret = TRUE;
824 if (!info)
826 ret = CertGetCertificateContextProperty(pCert,
827 CERT_KEY_PROV_INFO_PROP_ID, 0, &size);
828 if (ret)
830 info = HeapAlloc(GetProcessHeap(), 0, size);
831 if (info)
833 ret = CertGetCertificateContextProperty(pCert,
834 CERT_KEY_PROV_INFO_PROP_ID, info, &size);
835 allocated = TRUE;
837 else
839 SetLastError(ERROR_OUTOFMEMORY);
840 ret = FALSE;
843 else
844 SetLastError(CRYPT_E_NO_KEY_PROPERTY);
846 if (ret)
848 ret = CryptAcquireContextW(phCryptProv, info->pwszContainerName,
849 info->pwszProvName, info->dwProvType, 0);
850 if (ret)
852 DWORD i;
854 for (i = 0; i < info->cProvParam; i++)
856 CryptSetProvParam(*phCryptProv,
857 info->rgProvParam[i].dwParam, info->rgProvParam[i].pbData,
858 info->rgProvParam[i].dwFlags);
860 *pdwKeySpec = info->dwKeySpec;
862 else
863 SetLastError(CRYPT_E_NO_KEY_PROPERTY);
865 if (allocated)
866 HeapFree(GetProcessHeap(), 0, info);
867 return ret;
870 BOOL WINAPI CryptAcquireCertificatePrivateKey(PCCERT_CONTEXT pCert,
871 DWORD dwFlags, void *pvReserved, HCRYPTPROV_OR_NCRYPT_KEY_HANDLE *phCryptProv,
872 DWORD *pdwKeySpec, BOOL *pfCallerFreeProv)
874 BOOL ret = FALSE, cache = FALSE;
875 PCRYPT_KEY_PROV_INFO info = NULL;
876 CERT_KEY_CONTEXT keyContext;
877 DWORD size;
879 TRACE("(%p, %08x, %p, %p, %p, %p)\n", pCert, dwFlags, pvReserved,
880 phCryptProv, pdwKeySpec, pfCallerFreeProv);
882 if (dwFlags & CRYPT_ACQUIRE_USE_PROV_INFO_FLAG)
884 DWORD size = 0;
886 ret = CertGetCertificateContextProperty(pCert,
887 CERT_KEY_PROV_INFO_PROP_ID, 0, &size);
888 if (ret)
890 info = HeapAlloc(GetProcessHeap(), 0, size);
891 ret = CertGetCertificateContextProperty(pCert,
892 CERT_KEY_PROV_INFO_PROP_ID, info, &size);
893 if (ret)
894 cache = info->dwFlags & CERT_SET_KEY_CONTEXT_PROP_ID;
897 else if (dwFlags & CRYPT_ACQUIRE_CACHE_FLAG)
898 cache = TRUE;
899 *phCryptProv = 0;
900 if (cache)
902 size = sizeof(keyContext);
903 ret = CertGetCertificateContextProperty(pCert, CERT_KEY_CONTEXT_PROP_ID,
904 &keyContext, &size);
905 if (ret)
907 *phCryptProv = keyContext.hCryptProv;
908 if (pdwKeySpec)
909 *pdwKeySpec = keyContext.dwKeySpec;
910 if (pfCallerFreeProv)
911 *pfCallerFreeProv = !cache;
914 if (!*phCryptProv)
916 ret = CRYPT_AcquirePrivateKeyFromProvInfo(pCert, info,
917 &keyContext.hCryptProv, &keyContext.dwKeySpec);
918 if (ret)
920 *phCryptProv = keyContext.hCryptProv;
921 if (pdwKeySpec)
922 *pdwKeySpec = keyContext.dwKeySpec;
923 if (cache)
925 keyContext.cbSize = sizeof(keyContext);
926 if (CertSetCertificateContextProperty(pCert,
927 CERT_KEY_CONTEXT_PROP_ID, 0, &keyContext))
929 if (pfCallerFreeProv)
930 *pfCallerFreeProv = FALSE;
933 else
935 if (pfCallerFreeProv)
936 *pfCallerFreeProv = TRUE;
940 HeapFree(GetProcessHeap(), 0, info);
941 return ret;
944 static BOOL key_prov_info_matches_cert(PCCERT_CONTEXT pCert,
945 const CRYPT_KEY_PROV_INFO *keyProvInfo)
947 HCRYPTPROV csp;
948 BOOL matches = FALSE;
950 if (CryptAcquireContextW(&csp, keyProvInfo->pwszContainerName,
951 keyProvInfo->pwszProvName, keyProvInfo->dwProvType, keyProvInfo->dwFlags))
953 DWORD size;
955 /* Need to sign something to verify the sig. What to sign? Why not
956 * the certificate itself?
958 if (CryptSignAndEncodeCertificate(csp, AT_SIGNATURE,
959 pCert->dwCertEncodingType, X509_CERT_TO_BE_SIGNED, pCert->pCertInfo,
960 &pCert->pCertInfo->SignatureAlgorithm, NULL, NULL, &size))
962 BYTE *certEncoded = CryptMemAlloc(size);
964 if (certEncoded)
966 if (CryptSignAndEncodeCertificate(csp, AT_SIGNATURE,
967 pCert->dwCertEncodingType, X509_CERT_TO_BE_SIGNED,
968 pCert->pCertInfo, &pCert->pCertInfo->SignatureAlgorithm,
969 NULL, certEncoded, &size))
971 if (size == pCert->cbCertEncoded &&
972 !memcmp(certEncoded, pCert->pbCertEncoded, size))
973 matches = TRUE;
975 CryptMemFree(certEncoded);
978 CryptReleaseContext(csp, 0);
980 return matches;
983 static BOOL container_matches_cert(PCCERT_CONTEXT pCert, LPCSTR container,
984 CRYPT_KEY_PROV_INFO *keyProvInfo)
986 CRYPT_KEY_PROV_INFO copy;
987 WCHAR containerW[MAX_PATH];
988 BOOL matches;
990 MultiByteToWideChar(CP_ACP, 0, container, -1,
991 containerW, sizeof(containerW) / sizeof(containerW[0]));
992 /* We make a copy of the CRYPT_KEY_PROV_INFO because the caller expects
993 * keyProvInfo->pwszContainerName to be NULL or a heap-allocated container
994 * name.
996 copy = *keyProvInfo;
997 copy.pwszContainerName = containerW;
998 matches = key_prov_info_matches_cert(pCert, &copy);
999 if (matches)
1001 keyProvInfo->pwszContainerName =
1002 CryptMemAlloc((strlenW(containerW) + 1) * sizeof(WCHAR));
1003 if (keyProvInfo->pwszContainerName)
1005 strcpyW(keyProvInfo->pwszContainerName, containerW);
1006 keyProvInfo->dwKeySpec = AT_SIGNATURE;
1008 else
1009 matches = FALSE;
1011 return matches;
1014 /* Searches the provider named keyProvInfo.pwszProvName for a container whose
1015 * private key matches pCert's public key. Upon success, updates keyProvInfo
1016 * with the matching container's info (free keyProvInfo.pwszContainerName upon
1017 * success.)
1018 * Returns TRUE if found, FALSE if not.
1020 static BOOL find_key_prov_info_in_provider(PCCERT_CONTEXT pCert,
1021 CRYPT_KEY_PROV_INFO *keyProvInfo)
1023 HCRYPTPROV defProvider;
1024 BOOL ret, found = FALSE;
1025 char containerA[MAX_PATH];
1027 assert(keyProvInfo->pwszContainerName == NULL);
1028 if ((ret = CryptAcquireContextW(&defProvider, NULL,
1029 keyProvInfo->pwszProvName, keyProvInfo->dwProvType,
1030 keyProvInfo->dwFlags | CRYPT_VERIFYCONTEXT)))
1032 DWORD enumFlags = keyProvInfo->dwFlags | CRYPT_FIRST;
1034 while (ret && !found)
1036 DWORD size = sizeof(containerA);
1038 ret = CryptGetProvParam(defProvider, PP_ENUMCONTAINERS,
1039 (BYTE *)containerA, &size, enumFlags);
1040 if (ret)
1041 found = container_matches_cert(pCert, containerA, keyProvInfo);
1042 if (enumFlags & CRYPT_FIRST)
1044 enumFlags &= ~CRYPT_FIRST;
1045 enumFlags |= CRYPT_NEXT;
1048 CryptReleaseContext(defProvider, 0);
1050 return found;
1053 static BOOL find_matching_provider(PCCERT_CONTEXT pCert, DWORD dwFlags)
1055 BOOL found = FALSE, ret = TRUE;
1056 DWORD index = 0, cbProvName = 0;
1057 CRYPT_KEY_PROV_INFO keyProvInfo;
1059 TRACE("(%p, %08x)\n", pCert, dwFlags);
1061 memset(&keyProvInfo, 0, sizeof(keyProvInfo));
1062 while (ret && !found)
1064 DWORD size = 0;
1066 ret = CryptEnumProvidersW(index, NULL, 0, &keyProvInfo.dwProvType,
1067 NULL, &size);
1068 if (ret)
1070 if (size <= cbProvName)
1071 ret = CryptEnumProvidersW(index, NULL, 0,
1072 &keyProvInfo.dwProvType, keyProvInfo.pwszProvName, &size);
1073 else
1075 CryptMemFree(keyProvInfo.pwszProvName);
1076 keyProvInfo.pwszProvName = CryptMemAlloc(size);
1077 if (keyProvInfo.pwszProvName)
1079 cbProvName = size;
1080 ret = CryptEnumProvidersW(index, NULL, 0,
1081 &keyProvInfo.dwProvType, keyProvInfo.pwszProvName, &size);
1082 if (ret)
1084 if (dwFlags & CRYPT_FIND_SILENT_KEYSET_FLAG)
1085 keyProvInfo.dwFlags |= CRYPT_SILENT;
1086 if (dwFlags & CRYPT_FIND_USER_KEYSET_FLAG ||
1087 !(dwFlags & (CRYPT_FIND_USER_KEYSET_FLAG |
1088 CRYPT_FIND_MACHINE_KEYSET_FLAG)))
1090 keyProvInfo.dwFlags |= CRYPT_USER_KEYSET;
1091 found = find_key_prov_info_in_provider(pCert,
1092 &keyProvInfo);
1094 if (!found)
1096 if (dwFlags & CRYPT_FIND_MACHINE_KEYSET_FLAG ||
1097 !(dwFlags & (CRYPT_FIND_USER_KEYSET_FLAG |
1098 CRYPT_FIND_MACHINE_KEYSET_FLAG)))
1100 keyProvInfo.dwFlags &= ~CRYPT_USER_KEYSET;
1101 keyProvInfo.dwFlags |= CRYPT_MACHINE_KEYSET;
1102 found = find_key_prov_info_in_provider(pCert,
1103 &keyProvInfo);
1108 else
1109 ret = FALSE;
1111 index++;
1114 if (found)
1115 CertSetCertificateContextProperty(pCert, CERT_KEY_PROV_INFO_PROP_ID,
1116 0, &keyProvInfo);
1117 CryptMemFree(keyProvInfo.pwszProvName);
1118 CryptMemFree(keyProvInfo.pwszContainerName);
1119 return found;
1122 static BOOL cert_prov_info_matches_cert(PCCERT_CONTEXT pCert)
1124 BOOL matches = FALSE;
1125 DWORD size;
1127 if (CertGetCertificateContextProperty(pCert, CERT_KEY_PROV_INFO_PROP_ID,
1128 NULL, &size))
1130 CRYPT_KEY_PROV_INFO *keyProvInfo = CryptMemAlloc(size);
1132 if (keyProvInfo)
1134 if (CertGetCertificateContextProperty(pCert,
1135 CERT_KEY_PROV_INFO_PROP_ID, keyProvInfo, &size))
1136 matches = key_prov_info_matches_cert(pCert, keyProvInfo);
1137 CryptMemFree(keyProvInfo);
1140 return matches;
1143 BOOL WINAPI CryptFindCertificateKeyProvInfo(PCCERT_CONTEXT pCert,
1144 DWORD dwFlags, void *pvReserved)
1146 BOOL matches;
1148 TRACE("(%p, %08x, %p)\n", pCert, dwFlags, pvReserved);
1150 matches = cert_prov_info_matches_cert(pCert);
1151 if (!matches)
1152 matches = find_matching_provider(pCert, dwFlags);
1153 return matches;
1156 BOOL WINAPI CertCompareCertificate(DWORD dwCertEncodingType,
1157 PCERT_INFO pCertId1, PCERT_INFO pCertId2)
1159 BOOL ret;
1161 TRACE("(%08x, %p, %p)\n", dwCertEncodingType, pCertId1, pCertId2);
1163 ret = CertCompareCertificateName(dwCertEncodingType, &pCertId1->Issuer,
1164 &pCertId2->Issuer) && CertCompareIntegerBlob(&pCertId1->SerialNumber,
1165 &pCertId2->SerialNumber);
1166 TRACE("returning %d\n", ret);
1167 return ret;
1170 BOOL WINAPI CertCompareCertificateName(DWORD dwCertEncodingType,
1171 PCERT_NAME_BLOB pCertName1, PCERT_NAME_BLOB pCertName2)
1173 BOOL ret;
1175 TRACE("(%08x, %p, %p)\n", dwCertEncodingType, pCertName1, pCertName2);
1177 if (pCertName1->cbData == pCertName2->cbData)
1179 if (pCertName1->cbData)
1180 ret = !memcmp(pCertName1->pbData, pCertName2->pbData,
1181 pCertName1->cbData);
1182 else
1183 ret = TRUE;
1185 else
1186 ret = FALSE;
1187 TRACE("returning %d\n", ret);
1188 return ret;
1191 /* Returns the number of significant bytes in pInt, where a byte is
1192 * insignificant if it's a leading 0 for positive numbers or a leading 0xff
1193 * for negative numbers. pInt is assumed to be little-endian.
1195 static DWORD CRYPT_significantBytes(const CRYPT_INTEGER_BLOB *pInt)
1197 DWORD ret = pInt->cbData;
1199 while (ret > 1)
1201 if (pInt->pbData[ret - 2] <= 0x7f && pInt->pbData[ret - 1] == 0)
1202 ret--;
1203 else if (pInt->pbData[ret - 2] >= 0x80 && pInt->pbData[ret - 1] == 0xff)
1204 ret--;
1205 else
1206 break;
1208 return ret;
1211 BOOL WINAPI CertCompareIntegerBlob(PCRYPT_INTEGER_BLOB pInt1,
1212 PCRYPT_INTEGER_BLOB pInt2)
1214 BOOL ret;
1215 DWORD cb1, cb2;
1217 TRACE("(%p, %p)\n", pInt1, pInt2);
1219 cb1 = CRYPT_significantBytes(pInt1);
1220 cb2 = CRYPT_significantBytes(pInt2);
1221 if (cb1 == cb2)
1223 if (cb1)
1224 ret = !memcmp(pInt1->pbData, pInt2->pbData, cb1);
1225 else
1226 ret = TRUE;
1228 else
1229 ret = FALSE;
1230 TRACE("returning %d\n", ret);
1231 return ret;
1234 BOOL WINAPI CertComparePublicKeyInfo(DWORD dwCertEncodingType,
1235 PCERT_PUBLIC_KEY_INFO pPublicKey1, PCERT_PUBLIC_KEY_INFO pPublicKey2)
1237 BOOL ret;
1239 TRACE("(%08x, %p, %p)\n", dwCertEncodingType, pPublicKey1, pPublicKey2);
1241 switch (GET_CERT_ENCODING_TYPE(dwCertEncodingType))
1243 case 0: /* Seems to mean "raw binary bits" */
1244 if (pPublicKey1->PublicKey.cbData == pPublicKey2->PublicKey.cbData &&
1245 pPublicKey1->PublicKey.cUnusedBits == pPublicKey2->PublicKey.cUnusedBits)
1247 if (pPublicKey2->PublicKey.cbData)
1248 ret = !memcmp(pPublicKey1->PublicKey.pbData,
1249 pPublicKey2->PublicKey.pbData, pPublicKey1->PublicKey.cbData);
1250 else
1251 ret = TRUE;
1253 else
1254 ret = FALSE;
1255 break;
1256 default:
1257 WARN("Unknown encoding type %08x\n", dwCertEncodingType);
1258 /* FALLTHROUGH */
1259 case X509_ASN_ENCODING:
1261 BLOBHEADER *pblob1, *pblob2;
1262 DWORD length;
1263 ret = FALSE;
1264 if (CryptDecodeObject(dwCertEncodingType, RSA_CSP_PUBLICKEYBLOB,
1265 pPublicKey1->PublicKey.pbData, pPublicKey1->PublicKey.cbData,
1266 0, NULL, &length))
1268 pblob1 = CryptMemAlloc(length);
1269 if (CryptDecodeObject(dwCertEncodingType, RSA_CSP_PUBLICKEYBLOB,
1270 pPublicKey1->PublicKey.pbData, pPublicKey1->PublicKey.cbData,
1271 0, pblob1, &length))
1273 if (CryptDecodeObject(dwCertEncodingType, RSA_CSP_PUBLICKEYBLOB,
1274 pPublicKey2->PublicKey.pbData, pPublicKey2->PublicKey.cbData,
1275 0, NULL, &length))
1277 pblob2 = CryptMemAlloc(length);
1278 if (CryptDecodeObject(dwCertEncodingType, RSA_CSP_PUBLICKEYBLOB,
1279 pPublicKey2->PublicKey.pbData, pPublicKey2->PublicKey.cbData,
1280 0, pblob2, &length))
1282 /* The RSAPUBKEY structure directly follows the BLOBHEADER */
1283 RSAPUBKEY *pk1 = (LPVOID)(pblob1 + 1),
1284 *pk2 = (LPVOID)(pblob2 + 1);
1285 ret = (pk1->bitlen == pk2->bitlen) && (pk1->pubexp == pk2->pubexp)
1286 && !memcmp(pk1 + 1, pk2 + 1, pk1->bitlen/8);
1288 CryptMemFree(pblob2);
1291 CryptMemFree(pblob1);
1294 break;
1297 return ret;
1300 DWORD WINAPI CertGetPublicKeyLength(DWORD dwCertEncodingType,
1301 PCERT_PUBLIC_KEY_INFO pPublicKey)
1303 DWORD len = 0;
1305 TRACE("(%08x, %p)\n", dwCertEncodingType, pPublicKey);
1307 if (GET_CERT_ENCODING_TYPE(dwCertEncodingType) != X509_ASN_ENCODING)
1309 SetLastError(ERROR_FILE_NOT_FOUND);
1310 return 0;
1312 if (pPublicKey->Algorithm.pszObjId &&
1313 !strcmp(pPublicKey->Algorithm.pszObjId, szOID_RSA_DH))
1315 FIXME("unimplemented for DH public keys\n");
1316 SetLastError(CRYPT_E_ASN1_BADTAG);
1318 else
1320 DWORD size;
1321 PBYTE buf;
1322 BOOL ret = CryptDecodeObjectEx(dwCertEncodingType,
1323 RSA_CSP_PUBLICKEYBLOB, pPublicKey->PublicKey.pbData,
1324 pPublicKey->PublicKey.cbData, CRYPT_DECODE_ALLOC_FLAG, NULL, &buf,
1325 &size);
1327 if (ret)
1329 RSAPUBKEY *rsaPubKey = (RSAPUBKEY *)(buf + sizeof(BLOBHEADER));
1331 len = rsaPubKey->bitlen;
1332 LocalFree(buf);
1335 return len;
1338 typedef BOOL (*CertCompareFunc)(PCCERT_CONTEXT pCertContext, DWORD dwType,
1339 DWORD dwFlags, const void *pvPara);
1341 static BOOL compare_cert_by_md5_hash(PCCERT_CONTEXT pCertContext, DWORD dwType,
1342 DWORD dwFlags, const void *pvPara)
1344 BOOL ret;
1345 BYTE hash[16];
1346 DWORD size = sizeof(hash);
1348 ret = CertGetCertificateContextProperty(pCertContext,
1349 CERT_MD5_HASH_PROP_ID, hash, &size);
1350 if (ret)
1352 const CRYPT_HASH_BLOB *pHash = pvPara;
1354 if (size == pHash->cbData)
1355 ret = !memcmp(pHash->pbData, hash, size);
1356 else
1357 ret = FALSE;
1359 return ret;
1362 static BOOL compare_cert_by_sha1_hash(PCCERT_CONTEXT pCertContext, DWORD dwType,
1363 DWORD dwFlags, const void *pvPara)
1365 BOOL ret;
1366 BYTE hash[20];
1367 DWORD size = sizeof(hash);
1369 ret = CertGetCertificateContextProperty(pCertContext,
1370 CERT_SHA1_HASH_PROP_ID, hash, &size);
1371 if (ret)
1373 const CRYPT_HASH_BLOB *pHash = pvPara;
1375 if (size == pHash->cbData)
1376 ret = !memcmp(pHash->pbData, hash, size);
1377 else
1378 ret = FALSE;
1380 return ret;
1383 static BOOL compare_cert_by_name(PCCERT_CONTEXT pCertContext, DWORD dwType,
1384 DWORD dwFlags, const void *pvPara)
1386 CERT_NAME_BLOB *blob = (CERT_NAME_BLOB *)pvPara, *toCompare;
1387 BOOL ret;
1389 if (dwType & CERT_INFO_SUBJECT_FLAG)
1390 toCompare = &pCertContext->pCertInfo->Subject;
1391 else
1392 toCompare = &pCertContext->pCertInfo->Issuer;
1393 ret = CertCompareCertificateName(pCertContext->dwCertEncodingType,
1394 toCompare, blob);
1395 return ret;
1398 static BOOL compare_cert_by_public_key(PCCERT_CONTEXT pCertContext,
1399 DWORD dwType, DWORD dwFlags, const void *pvPara)
1401 CERT_PUBLIC_KEY_INFO *publicKey = (CERT_PUBLIC_KEY_INFO *)pvPara;
1402 BOOL ret;
1404 ret = CertComparePublicKeyInfo(pCertContext->dwCertEncodingType,
1405 &pCertContext->pCertInfo->SubjectPublicKeyInfo, publicKey);
1406 return ret;
1409 static BOOL compare_cert_by_subject_cert(PCCERT_CONTEXT pCertContext,
1410 DWORD dwType, DWORD dwFlags, const void *pvPara)
1412 CERT_INFO *pCertInfo = (CERT_INFO *)pvPara;
1413 BOOL ret;
1415 /* Matching serial number and subject match.. */
1416 ret = CertCompareCertificateName(pCertContext->dwCertEncodingType,
1417 &pCertContext->pCertInfo->Subject, &pCertInfo->Issuer);
1418 if (ret)
1419 ret = CertCompareIntegerBlob(&pCertContext->pCertInfo->SerialNumber,
1420 &pCertInfo->SerialNumber);
1421 else
1423 /* failing that, if the serial number and issuer match, we match */
1424 ret = CertCompareIntegerBlob(&pCertContext->pCertInfo->SerialNumber,
1425 &pCertInfo->SerialNumber);
1426 if (ret)
1427 ret = CertCompareCertificateName(pCertContext->dwCertEncodingType,
1428 &pCertContext->pCertInfo->Issuer, &pCertInfo->Issuer);
1430 TRACE("returning %d\n", ret);
1431 return ret;
1434 static BOOL compare_cert_by_cert_id(PCCERT_CONTEXT pCertContext, DWORD dwType,
1435 DWORD dwFlags, const void *pvPara)
1437 CERT_ID *id = (CERT_ID *)pvPara;
1438 BOOL ret;
1440 switch (id->dwIdChoice)
1442 case CERT_ID_ISSUER_SERIAL_NUMBER:
1443 ret = CertCompareCertificateName(pCertContext->dwCertEncodingType,
1444 &pCertContext->pCertInfo->Issuer, &id->u.IssuerSerialNumber.Issuer);
1445 if (ret)
1446 ret = CertCompareIntegerBlob(&pCertContext->pCertInfo->SerialNumber,
1447 &id->u.IssuerSerialNumber.SerialNumber);
1448 break;
1449 case CERT_ID_SHA1_HASH:
1450 ret = compare_cert_by_sha1_hash(pCertContext, dwType, dwFlags,
1451 &id->u.HashId);
1452 break;
1453 case CERT_ID_KEY_IDENTIFIER:
1455 DWORD size = 0;
1457 ret = CertGetCertificateContextProperty(pCertContext,
1458 CERT_KEY_IDENTIFIER_PROP_ID, NULL, &size);
1459 if (ret && size == id->u.KeyId.cbData)
1461 LPBYTE buf = CryptMemAlloc(size);
1463 if (buf)
1465 CertGetCertificateContextProperty(pCertContext,
1466 CERT_KEY_IDENTIFIER_PROP_ID, buf, &size);
1467 ret = !memcmp(buf, id->u.KeyId.pbData, size);
1468 CryptMemFree(buf);
1470 else
1471 ret = FALSE;
1473 else
1474 ret = FALSE;
1475 break;
1477 default:
1478 ret = FALSE;
1479 break;
1481 return ret;
1484 static BOOL compare_existing_cert(PCCERT_CONTEXT pCertContext, DWORD dwType,
1485 DWORD dwFlags, const void *pvPara)
1487 PCCERT_CONTEXT toCompare = pvPara;
1488 return CertCompareCertificate(pCertContext->dwCertEncodingType,
1489 pCertContext->pCertInfo, toCompare->pCertInfo);
1492 static BOOL compare_cert_by_signature_hash(PCCERT_CONTEXT pCertContext, DWORD dwType,
1493 DWORD dwFlags, const void *pvPara)
1495 const CRYPT_HASH_BLOB *hash = pvPara;
1496 DWORD size = 0;
1497 BOOL ret;
1499 ret = CertGetCertificateContextProperty(pCertContext,
1500 CERT_SIGNATURE_HASH_PROP_ID, NULL, &size);
1501 if (ret && size == hash->cbData)
1503 LPBYTE buf = CryptMemAlloc(size);
1505 if (buf)
1507 CertGetCertificateContextProperty(pCertContext,
1508 CERT_SIGNATURE_HASH_PROP_ID, buf, &size);
1509 ret = !memcmp(buf, hash->pbData, size);
1510 CryptMemFree(buf);
1512 else
1513 ret = FALSE;
1515 else
1516 ret = FALSE;
1517 return ret;
1520 static inline PCCERT_CONTEXT cert_compare_certs_in_store(HCERTSTORE store,
1521 PCCERT_CONTEXT prev, CertCompareFunc compare, DWORD dwType, DWORD dwFlags,
1522 const void *pvPara)
1524 BOOL matches = FALSE;
1525 PCCERT_CONTEXT ret;
1527 ret = prev;
1528 do {
1529 ret = CertEnumCertificatesInStore(store, ret);
1530 if (ret)
1531 matches = compare(ret, dwType, dwFlags, pvPara);
1532 } while (ret != NULL && !matches);
1533 return ret;
1536 typedef PCCERT_CONTEXT (*CertFindFunc)(HCERTSTORE store, DWORD dwType,
1537 DWORD dwFlags, const void *pvPara, PCCERT_CONTEXT prev);
1539 static PCCERT_CONTEXT find_cert_any(HCERTSTORE store, DWORD dwType,
1540 DWORD dwFlags, const void *pvPara, PCCERT_CONTEXT prev)
1542 return CertEnumCertificatesInStore(store, prev);
1545 static PCCERT_CONTEXT find_cert_by_issuer(HCERTSTORE store, DWORD dwType,
1546 DWORD dwFlags, const void *pvPara, PCCERT_CONTEXT prev)
1548 BOOL ret;
1549 PCCERT_CONTEXT found = NULL, subject = pvPara;
1550 PCERT_EXTENSION ext;
1551 DWORD size;
1553 if ((ext = CertFindExtension(szOID_AUTHORITY_KEY_IDENTIFIER,
1554 subject->pCertInfo->cExtension, subject->pCertInfo->rgExtension)))
1556 CERT_AUTHORITY_KEY_ID_INFO *info;
1558 ret = CryptDecodeObjectEx(subject->dwCertEncodingType,
1559 X509_AUTHORITY_KEY_ID, ext->Value.pbData, ext->Value.cbData,
1560 CRYPT_DECODE_ALLOC_FLAG | CRYPT_DECODE_NOCOPY_FLAG, NULL,
1561 &info, &size);
1562 if (ret)
1564 CERT_ID id;
1566 if (info->CertIssuer.cbData && info->CertSerialNumber.cbData)
1568 id.dwIdChoice = CERT_ID_ISSUER_SERIAL_NUMBER;
1569 memcpy(&id.u.IssuerSerialNumber.Issuer, &info->CertIssuer,
1570 sizeof(CERT_NAME_BLOB));
1571 memcpy(&id.u.IssuerSerialNumber.SerialNumber,
1572 &info->CertSerialNumber, sizeof(CRYPT_INTEGER_BLOB));
1574 else if (info->KeyId.cbData)
1576 id.dwIdChoice = CERT_ID_KEY_IDENTIFIER;
1577 memcpy(&id.u.KeyId, &info->KeyId, sizeof(CRYPT_HASH_BLOB));
1579 else
1580 ret = FALSE;
1581 if (ret)
1582 found = cert_compare_certs_in_store(store, prev,
1583 compare_cert_by_cert_id, dwType, dwFlags, &id);
1584 LocalFree(info);
1587 else if ((ext = CertFindExtension(szOID_AUTHORITY_KEY_IDENTIFIER2,
1588 subject->pCertInfo->cExtension, subject->pCertInfo->rgExtension)))
1590 CERT_AUTHORITY_KEY_ID2_INFO *info;
1592 ret = CryptDecodeObjectEx(subject->dwCertEncodingType,
1593 X509_AUTHORITY_KEY_ID2, ext->Value.pbData, ext->Value.cbData,
1594 CRYPT_DECODE_ALLOC_FLAG | CRYPT_DECODE_NOCOPY_FLAG, NULL,
1595 &info, &size);
1596 if (ret)
1598 CERT_ID id;
1600 if (info->AuthorityCertIssuer.cAltEntry &&
1601 info->AuthorityCertSerialNumber.cbData)
1603 PCERT_ALT_NAME_ENTRY directoryName = NULL;
1604 DWORD i;
1606 for (i = 0; !directoryName &&
1607 i < info->AuthorityCertIssuer.cAltEntry; i++)
1608 if (info->AuthorityCertIssuer.rgAltEntry[i].dwAltNameChoice
1609 == CERT_ALT_NAME_DIRECTORY_NAME)
1610 directoryName =
1611 &info->AuthorityCertIssuer.rgAltEntry[i];
1612 if (directoryName)
1614 id.dwIdChoice = CERT_ID_ISSUER_SERIAL_NUMBER;
1615 memcpy(&id.u.IssuerSerialNumber.Issuer,
1616 &directoryName->u.DirectoryName, sizeof(CERT_NAME_BLOB));
1617 memcpy(&id.u.IssuerSerialNumber.SerialNumber,
1618 &info->AuthorityCertSerialNumber,
1619 sizeof(CRYPT_INTEGER_BLOB));
1621 else
1623 FIXME("no supported name type in authority key id2\n");
1624 ret = FALSE;
1627 else if (info->KeyId.cbData)
1629 id.dwIdChoice = CERT_ID_KEY_IDENTIFIER;
1630 memcpy(&id.u.KeyId, &info->KeyId, sizeof(CRYPT_HASH_BLOB));
1632 else
1633 ret = FALSE;
1634 if (ret)
1635 found = cert_compare_certs_in_store(store, prev,
1636 compare_cert_by_cert_id, dwType, dwFlags, &id);
1637 LocalFree(info);
1640 else
1641 found = cert_compare_certs_in_store(store, prev,
1642 compare_cert_by_name, CERT_COMPARE_NAME | CERT_COMPARE_SUBJECT_CERT,
1643 dwFlags, &subject->pCertInfo->Issuer);
1644 return found;
1647 static BOOL compare_cert_by_name_str(PCCERT_CONTEXT pCertContext,
1648 DWORD dwType, DWORD dwFlags, const void *pvPara)
1650 PCERT_NAME_BLOB name;
1651 DWORD len;
1652 BOOL ret = FALSE;
1654 if (dwType & CERT_INFO_SUBJECT_FLAG)
1655 name = &pCertContext->pCertInfo->Subject;
1656 else
1657 name = &pCertContext->pCertInfo->Issuer;
1658 len = CertNameToStrW(pCertContext->dwCertEncodingType, name,
1659 CERT_SIMPLE_NAME_STR, NULL, 0);
1660 if (len)
1662 LPWSTR str = CryptMemAlloc(len * sizeof(WCHAR));
1664 if (str)
1666 LPWSTR ptr;
1668 CertNameToStrW(pCertContext->dwCertEncodingType, name,
1669 CERT_SIMPLE_NAME_STR, str, len);
1670 for (ptr = str; *ptr; ptr++)
1671 *ptr = tolowerW(*ptr);
1672 if (strstrW(str, pvPara))
1673 ret = TRUE;
1674 CryptMemFree(str);
1677 return ret;
1680 static PCCERT_CONTEXT find_cert_by_name_str_a(HCERTSTORE store, DWORD dwType,
1681 DWORD dwFlags, const void *pvPara, PCCERT_CONTEXT prev)
1683 PCCERT_CONTEXT found = NULL;
1685 TRACE("%s\n", debugstr_a(pvPara));
1687 if (pvPara)
1689 int len = MultiByteToWideChar(CP_ACP, 0, pvPara, -1, NULL, 0);
1690 LPWSTR str = CryptMemAlloc(len * sizeof(WCHAR));
1692 if (str)
1694 LPWSTR ptr;
1696 MultiByteToWideChar(CP_ACP, 0, pvPara, -1, str, len);
1697 for (ptr = str; *ptr; ptr++)
1698 *ptr = tolowerW(*ptr);
1699 found = cert_compare_certs_in_store(store, prev,
1700 compare_cert_by_name_str, dwType, dwFlags, str);
1701 CryptMemFree(str);
1704 else
1705 found = find_cert_any(store, dwType, dwFlags, NULL, prev);
1706 return found;
1709 static PCCERT_CONTEXT find_cert_by_name_str_w(HCERTSTORE store, DWORD dwType,
1710 DWORD dwFlags, const void *pvPara, PCCERT_CONTEXT prev)
1712 PCCERT_CONTEXT found = NULL;
1714 TRACE("%s\n", debugstr_w(pvPara));
1716 if (pvPara)
1718 DWORD len = strlenW(pvPara);
1719 LPWSTR str = CryptMemAlloc((len + 1) * sizeof(WCHAR));
1721 if (str)
1723 LPCWSTR src;
1724 LPWSTR dst;
1726 for (src = pvPara, dst = str; *src; src++, dst++)
1727 *dst = tolowerW(*src);
1728 *dst = 0;
1729 found = cert_compare_certs_in_store(store, prev,
1730 compare_cert_by_name_str, dwType, dwFlags, str);
1731 CryptMemFree(str);
1734 else
1735 found = find_cert_any(store, dwType, dwFlags, NULL, prev);
1736 return found;
1739 PCCERT_CONTEXT WINAPI CertFindCertificateInStore(HCERTSTORE hCertStore,
1740 DWORD dwCertEncodingType, DWORD dwFlags, DWORD dwType, const void *pvPara,
1741 PCCERT_CONTEXT pPrevCertContext)
1743 PCCERT_CONTEXT ret;
1744 CertFindFunc find = NULL;
1745 CertCompareFunc compare = NULL;
1747 TRACE("(%p, %08x, %08x, %08x, %p, %p)\n", hCertStore, dwCertEncodingType,
1748 dwFlags, dwType, pvPara, pPrevCertContext);
1750 switch (dwType >> CERT_COMPARE_SHIFT)
1752 case CERT_COMPARE_ANY:
1753 find = find_cert_any;
1754 break;
1755 case CERT_COMPARE_MD5_HASH:
1756 compare = compare_cert_by_md5_hash;
1757 break;
1758 case CERT_COMPARE_SHA1_HASH:
1759 compare = compare_cert_by_sha1_hash;
1760 break;
1761 case CERT_COMPARE_NAME:
1762 compare = compare_cert_by_name;
1763 break;
1764 case CERT_COMPARE_PUBLIC_KEY:
1765 compare = compare_cert_by_public_key;
1766 break;
1767 case CERT_COMPARE_NAME_STR_A:
1768 find = find_cert_by_name_str_a;
1769 break;
1770 case CERT_COMPARE_NAME_STR_W:
1771 find = find_cert_by_name_str_w;
1772 break;
1773 case CERT_COMPARE_SUBJECT_CERT:
1774 compare = compare_cert_by_subject_cert;
1775 break;
1776 case CERT_COMPARE_CERT_ID:
1777 compare = compare_cert_by_cert_id;
1778 break;
1779 case CERT_COMPARE_ISSUER_OF:
1780 find = find_cert_by_issuer;
1781 break;
1782 case CERT_COMPARE_EXISTING:
1783 compare = compare_existing_cert;
1784 break;
1785 case CERT_COMPARE_SIGNATURE_HASH:
1786 compare = compare_cert_by_signature_hash;
1787 break;
1788 default:
1789 FIXME("find type %08x unimplemented\n", dwType);
1792 if (find)
1793 ret = find(hCertStore, dwFlags, dwType, pvPara, pPrevCertContext);
1794 else if (compare)
1795 ret = cert_compare_certs_in_store(hCertStore, pPrevCertContext,
1796 compare, dwType, dwFlags, pvPara);
1797 else
1798 ret = NULL;
1799 if (!ret)
1800 SetLastError(CRYPT_E_NOT_FOUND);
1801 TRACE("returning %p\n", ret);
1802 return ret;
1805 PCCERT_CONTEXT WINAPI CertGetSubjectCertificateFromStore(HCERTSTORE hCertStore,
1806 DWORD dwCertEncodingType, PCERT_INFO pCertId)
1808 TRACE("(%p, %08x, %p)\n", hCertStore, dwCertEncodingType, pCertId);
1810 if (!pCertId)
1812 SetLastError(E_INVALIDARG);
1813 return NULL;
1815 return CertFindCertificateInStore(hCertStore, dwCertEncodingType, 0,
1816 CERT_FIND_SUBJECT_CERT, pCertId, NULL);
1819 BOOL WINAPI CertVerifySubjectCertificateContext(PCCERT_CONTEXT pSubject,
1820 PCCERT_CONTEXT pIssuer, DWORD *pdwFlags)
1822 static const DWORD supportedFlags = CERT_STORE_REVOCATION_FLAG |
1823 CERT_STORE_SIGNATURE_FLAG | CERT_STORE_TIME_VALIDITY_FLAG;
1825 if (*pdwFlags & ~supportedFlags)
1827 SetLastError(E_INVALIDARG);
1828 return FALSE;
1830 if (*pdwFlags & CERT_STORE_REVOCATION_FLAG)
1832 DWORD flags = 0;
1833 PCCRL_CONTEXT crl = CertGetCRLFromStore(pSubject->hCertStore, pSubject,
1834 NULL, &flags);
1836 /* FIXME: what if the CRL has expired? */
1837 if (crl)
1839 if (CertVerifyCRLRevocation(pSubject->dwCertEncodingType,
1840 pSubject->pCertInfo, 1, (PCRL_INFO *)&crl->pCrlInfo))
1841 *pdwFlags &= CERT_STORE_REVOCATION_FLAG;
1843 else
1844 *pdwFlags |= CERT_STORE_NO_CRL_FLAG;
1846 if (*pdwFlags & CERT_STORE_TIME_VALIDITY_FLAG)
1848 if (0 == CertVerifyTimeValidity(NULL, pSubject->pCertInfo))
1849 *pdwFlags &= ~CERT_STORE_TIME_VALIDITY_FLAG;
1851 if (*pdwFlags & CERT_STORE_SIGNATURE_FLAG)
1853 if (CryptVerifyCertificateSignatureEx(0, pSubject->dwCertEncodingType,
1854 CRYPT_VERIFY_CERT_SIGN_SUBJECT_CERT, (void *)pSubject,
1855 CRYPT_VERIFY_CERT_SIGN_ISSUER_CERT, (void *)pIssuer, 0, NULL))
1856 *pdwFlags &= ~CERT_STORE_SIGNATURE_FLAG;
1858 return TRUE;
1861 PCCERT_CONTEXT WINAPI CertGetIssuerCertificateFromStore(HCERTSTORE hCertStore,
1862 PCCERT_CONTEXT pSubjectContext, PCCERT_CONTEXT pPrevIssuerContext,
1863 DWORD *pdwFlags)
1865 PCCERT_CONTEXT ret;
1867 TRACE("(%p, %p, %p, %08x)\n", hCertStore, pSubjectContext,
1868 pPrevIssuerContext, *pdwFlags);
1870 if (!pSubjectContext)
1872 SetLastError(E_INVALIDARG);
1873 return NULL;
1876 ret = CertFindCertificateInStore(hCertStore,
1877 pSubjectContext->dwCertEncodingType, 0, CERT_FIND_ISSUER_OF,
1878 pSubjectContext, pPrevIssuerContext);
1879 if (ret)
1881 if (!CertVerifySubjectCertificateContext(pSubjectContext, ret,
1882 pdwFlags))
1884 CertFreeCertificateContext(ret);
1885 ret = NULL;
1887 if (CRYPT_IsCertificateSelfSigned(pSubjectContext))
1889 CertFreeCertificateContext(ret);
1890 ret = NULL;
1891 SetLastError(CRYPT_E_SELF_SIGNED);
1894 TRACE("returning %p\n", ret);
1895 return ret;
1898 typedef struct _OLD_CERT_REVOCATION_STATUS {
1899 DWORD cbSize;
1900 DWORD dwIndex;
1901 DWORD dwError;
1902 DWORD dwReason;
1903 } OLD_CERT_REVOCATION_STATUS;
1905 typedef BOOL (WINAPI *CertVerifyRevocationFunc)(DWORD, DWORD, DWORD,
1906 void **, DWORD, PCERT_REVOCATION_PARA, PCERT_REVOCATION_STATUS);
1908 BOOL WINAPI CertVerifyRevocation(DWORD dwEncodingType, DWORD dwRevType,
1909 DWORD cContext, PVOID rgpvContext[], DWORD dwFlags,
1910 PCERT_REVOCATION_PARA pRevPara, PCERT_REVOCATION_STATUS pRevStatus)
1912 BOOL ret;
1914 TRACE("(%08x, %d, %d, %p, %08x, %p, %p)\n", dwEncodingType, dwRevType,
1915 cContext, rgpvContext, dwFlags, pRevPara, pRevStatus);
1917 if (pRevStatus->cbSize != sizeof(OLD_CERT_REVOCATION_STATUS) &&
1918 pRevStatus->cbSize != sizeof(CERT_REVOCATION_STATUS))
1920 SetLastError(E_INVALIDARG);
1921 return FALSE;
1923 if (cContext)
1925 static HCRYPTOIDFUNCSET set = NULL;
1926 DWORD size;
1928 if (!set)
1929 set = CryptInitOIDFunctionSet(CRYPT_OID_VERIFY_REVOCATION_FUNC, 0);
1930 ret = CryptGetDefaultOIDDllList(set, dwEncodingType, NULL, &size);
1931 if (ret)
1933 if (size == 1)
1935 /* empty list */
1936 SetLastError(CRYPT_E_NO_REVOCATION_DLL);
1937 ret = FALSE;
1939 else
1941 LPWSTR dllList = CryptMemAlloc(size * sizeof(WCHAR)), ptr;
1943 if (dllList)
1945 ret = CryptGetDefaultOIDDllList(set, dwEncodingType,
1946 dllList, &size);
1947 if (ret)
1949 for (ptr = dllList; ret && *ptr;
1950 ptr += lstrlenW(ptr) + 1)
1952 CertVerifyRevocationFunc func;
1953 HCRYPTOIDFUNCADDR hFunc;
1955 ret = CryptGetDefaultOIDFunctionAddress(set,
1956 dwEncodingType, ptr, 0, (void **)&func, &hFunc);
1957 if (ret)
1959 ret = func(dwEncodingType, dwRevType, cContext,
1960 rgpvContext, dwFlags, pRevPara, pRevStatus);
1961 CryptFreeOIDFunctionAddress(hFunc, 0);
1965 CryptMemFree(dllList);
1967 else
1969 SetLastError(ERROR_OUTOFMEMORY);
1970 ret = FALSE;
1975 else
1976 ret = TRUE;
1977 return ret;
1980 PCRYPT_ATTRIBUTE WINAPI CertFindAttribute(LPCSTR pszObjId, DWORD cAttr,
1981 CRYPT_ATTRIBUTE rgAttr[])
1983 PCRYPT_ATTRIBUTE ret = NULL;
1984 DWORD i;
1986 TRACE("%s %d %p\n", debugstr_a(pszObjId), cAttr, rgAttr);
1988 if (!cAttr)
1989 return NULL;
1990 if (!pszObjId)
1992 SetLastError(ERROR_INVALID_PARAMETER);
1993 return NULL;
1996 for (i = 0; !ret && i < cAttr; i++)
1997 if (rgAttr[i].pszObjId && !strcmp(pszObjId, rgAttr[i].pszObjId))
1998 ret = &rgAttr[i];
1999 return ret;
2002 PCERT_EXTENSION WINAPI CertFindExtension(LPCSTR pszObjId, DWORD cExtensions,
2003 CERT_EXTENSION rgExtensions[])
2005 PCERT_EXTENSION ret = NULL;
2006 DWORD i;
2008 TRACE("%s %d %p\n", debugstr_a(pszObjId), cExtensions, rgExtensions);
2010 if (!cExtensions)
2011 return NULL;
2012 if (!pszObjId)
2014 SetLastError(ERROR_INVALID_PARAMETER);
2015 return NULL;
2018 for (i = 0; !ret && i < cExtensions; i++)
2019 if (rgExtensions[i].pszObjId && !strcmp(pszObjId,
2020 rgExtensions[i].pszObjId))
2021 ret = &rgExtensions[i];
2022 return ret;
2025 PCERT_RDN_ATTR WINAPI CertFindRDNAttr(LPCSTR pszObjId, PCERT_NAME_INFO pName)
2027 PCERT_RDN_ATTR ret = NULL;
2028 DWORD i, j;
2030 TRACE("%s %p\n", debugstr_a(pszObjId), pName);
2032 if (!pszObjId)
2034 SetLastError(ERROR_INVALID_PARAMETER);
2035 return NULL;
2038 for (i = 0; !ret && i < pName->cRDN; i++)
2039 for (j = 0; !ret && j < pName->rgRDN[i].cRDNAttr; j++)
2040 if (pName->rgRDN[i].rgRDNAttr[j].pszObjId && !strcmp(pszObjId,
2041 pName->rgRDN[i].rgRDNAttr[j].pszObjId))
2042 ret = &pName->rgRDN[i].rgRDNAttr[j];
2043 return ret;
2046 static BOOL find_matching_rdn_attr(DWORD dwFlags, const CERT_NAME_INFO *name,
2047 const CERT_RDN_ATTR *attr)
2049 DWORD i, j;
2050 BOOL match = FALSE;
2052 for (i = 0; !match && i < name->cRDN; i++)
2054 for (j = 0; j < name->rgRDN[i].cRDNAttr; j++)
2056 if (!strcmp(name->rgRDN[i].rgRDNAttr[j].pszObjId,
2057 attr->pszObjId) &&
2058 name->rgRDN[i].rgRDNAttr[j].dwValueType ==
2059 attr->dwValueType)
2061 if (dwFlags & CERT_UNICODE_IS_RDN_ATTRS_FLAG)
2063 LPCWSTR nameStr =
2064 (LPCWSTR)name->rgRDN[i].rgRDNAttr[j].Value.pbData;
2065 LPCWSTR attrStr = (LPCWSTR)attr->Value.pbData;
2067 if (attr->Value.cbData !=
2068 name->rgRDN[i].rgRDNAttr[j].Value.cbData)
2069 match = FALSE;
2070 else if (dwFlags & CERT_CASE_INSENSITIVE_IS_RDN_ATTRS_FLAG)
2071 match = !strncmpiW(nameStr, attrStr,
2072 attr->Value.cbData / sizeof(WCHAR));
2073 else
2074 match = !strncmpW(nameStr, attrStr,
2075 attr->Value.cbData / sizeof(WCHAR));
2076 TRACE("%s : %s => %d\n",
2077 debugstr_wn(nameStr, attr->Value.cbData / sizeof(WCHAR)),
2078 debugstr_wn(attrStr, attr->Value.cbData / sizeof(WCHAR)),
2079 match);
2081 else
2083 LPCSTR nameStr =
2084 (LPCSTR)name->rgRDN[i].rgRDNAttr[j].Value.pbData;
2085 LPCSTR attrStr = (LPCSTR)attr->Value.pbData;
2087 if (attr->Value.cbData !=
2088 name->rgRDN[i].rgRDNAttr[j].Value.cbData)
2089 match = FALSE;
2090 else if (dwFlags & CERT_CASE_INSENSITIVE_IS_RDN_ATTRS_FLAG)
2091 match = !strncasecmp(nameStr, attrStr,
2092 attr->Value.cbData);
2093 else
2094 match = !strncmp(nameStr, attrStr, attr->Value.cbData);
2095 TRACE("%s : %s => %d\n",
2096 debugstr_an(nameStr, attr->Value.cbData),
2097 debugstr_an(attrStr, attr->Value.cbData), match);
2102 return match;
2105 BOOL WINAPI CertIsRDNAttrsInCertificateName(DWORD dwCertEncodingType,
2106 DWORD dwFlags, PCERT_NAME_BLOB pCertName, PCERT_RDN pRDN)
2108 CERT_NAME_INFO *name;
2109 LPCSTR type;
2110 DWORD size;
2111 BOOL ret;
2113 TRACE("(%08x, %08x, %p, %p)\n", dwCertEncodingType, dwFlags, pCertName,
2114 pRDN);
2116 type = dwFlags & CERT_UNICODE_IS_RDN_ATTRS_FLAG ? X509_UNICODE_NAME :
2117 X509_NAME;
2118 if ((ret = CryptDecodeObjectEx(dwCertEncodingType, type, pCertName->pbData,
2119 pCertName->cbData, CRYPT_DECODE_ALLOC_FLAG, NULL, &name, &size)))
2121 DWORD i;
2123 for (i = 0; ret && i < pRDN->cRDNAttr; i++)
2124 ret = find_matching_rdn_attr(dwFlags, name, &pRDN->rgRDNAttr[i]);
2125 if (!ret)
2126 SetLastError(CRYPT_E_NO_MATCH);
2127 LocalFree(name);
2129 return ret;
2132 LONG WINAPI CertVerifyTimeValidity(LPFILETIME pTimeToVerify,
2133 PCERT_INFO pCertInfo)
2135 FILETIME fileTime;
2136 LONG ret;
2138 if (!pTimeToVerify)
2140 GetSystemTimeAsFileTime(&fileTime);
2141 pTimeToVerify = &fileTime;
2143 if ((ret = CompareFileTime(pTimeToVerify, &pCertInfo->NotBefore)) >= 0)
2145 ret = CompareFileTime(pTimeToVerify, &pCertInfo->NotAfter);
2146 if (ret < 0)
2147 ret = 0;
2149 return ret;
2152 BOOL WINAPI CertVerifyValidityNesting(PCERT_INFO pSubjectInfo,
2153 PCERT_INFO pIssuerInfo)
2155 TRACE("(%p, %p)\n", pSubjectInfo, pIssuerInfo);
2157 return CertVerifyTimeValidity(&pSubjectInfo->NotBefore, pIssuerInfo) == 0
2158 && CertVerifyTimeValidity(&pSubjectInfo->NotAfter, pIssuerInfo) == 0;
2161 BOOL WINAPI CryptHashCertificate(HCRYPTPROV_LEGACY hCryptProv, ALG_ID Algid,
2162 DWORD dwFlags, const BYTE *pbEncoded, DWORD cbEncoded, BYTE *pbComputedHash,
2163 DWORD *pcbComputedHash)
2165 BOOL ret = TRUE;
2166 HCRYPTHASH hHash = 0;
2168 TRACE("(%08lx, %d, %08x, %p, %d, %p, %p)\n", hCryptProv, Algid, dwFlags,
2169 pbEncoded, cbEncoded, pbComputedHash, pcbComputedHash);
2171 if (!hCryptProv)
2172 hCryptProv = CRYPT_GetDefaultProvider();
2173 if (!Algid)
2174 Algid = CALG_SHA1;
2175 if (ret)
2177 ret = CryptCreateHash(hCryptProv, Algid, 0, 0, &hHash);
2178 if (ret)
2180 ret = CryptHashData(hHash, pbEncoded, cbEncoded, 0);
2181 if (ret)
2182 ret = CryptGetHashParam(hHash, HP_HASHVAL, pbComputedHash,
2183 pcbComputedHash, 0);
2184 CryptDestroyHash(hHash);
2187 return ret;
2190 BOOL WINAPI CryptHashPublicKeyInfo(HCRYPTPROV_LEGACY hCryptProv, ALG_ID Algid,
2191 DWORD dwFlags, DWORD dwCertEncodingType, PCERT_PUBLIC_KEY_INFO pInfo,
2192 BYTE *pbComputedHash, DWORD *pcbComputedHash)
2194 BOOL ret = TRUE;
2195 HCRYPTHASH hHash = 0;
2197 TRACE("(%08lx, %d, %08x, %d, %p, %p, %p)\n", hCryptProv, Algid, dwFlags,
2198 dwCertEncodingType, pInfo, pbComputedHash, pcbComputedHash);
2200 if (!hCryptProv)
2201 hCryptProv = CRYPT_GetDefaultProvider();
2202 if (!Algid)
2203 Algid = CALG_MD5;
2204 if ((dwCertEncodingType & CERT_ENCODING_TYPE_MASK) != X509_ASN_ENCODING)
2206 SetLastError(ERROR_FILE_NOT_FOUND);
2207 return FALSE;
2209 if (ret)
2211 BYTE *buf;
2212 DWORD size = 0;
2214 ret = CRYPT_AsnEncodePubKeyInfoNoNull(dwCertEncodingType,
2215 X509_PUBLIC_KEY_INFO, pInfo, CRYPT_ENCODE_ALLOC_FLAG, NULL,
2216 (LPBYTE)&buf, &size);
2217 if (ret)
2219 ret = CryptCreateHash(hCryptProv, Algid, 0, 0, &hHash);
2220 if (ret)
2222 ret = CryptHashData(hHash, buf, size, 0);
2223 if (ret)
2224 ret = CryptGetHashParam(hHash, HP_HASHVAL, pbComputedHash,
2225 pcbComputedHash, 0);
2226 CryptDestroyHash(hHash);
2228 LocalFree(buf);
2231 return ret;
2234 BOOL WINAPI CryptHashToBeSigned(HCRYPTPROV_LEGACY hCryptProv,
2235 DWORD dwCertEncodingType, const BYTE *pbEncoded, DWORD cbEncoded,
2236 BYTE *pbComputedHash, DWORD *pcbComputedHash)
2238 BOOL ret;
2239 CERT_SIGNED_CONTENT_INFO *info;
2240 DWORD size;
2242 TRACE("(%08lx, %08x, %p, %d, %p, %d)\n", hCryptProv, dwCertEncodingType,
2243 pbEncoded, cbEncoded, pbComputedHash, *pcbComputedHash);
2245 ret = CryptDecodeObjectEx(dwCertEncodingType, X509_CERT,
2246 pbEncoded, cbEncoded, CRYPT_DECODE_ALLOC_FLAG, NULL, &info, &size);
2247 if (ret)
2249 PCCRYPT_OID_INFO oidInfo;
2250 HCRYPTHASH hHash;
2252 if (!hCryptProv)
2253 hCryptProv = CRYPT_GetDefaultProvider();
2254 oidInfo = CryptFindOIDInfo(CRYPT_OID_INFO_OID_KEY,
2255 info->SignatureAlgorithm.pszObjId, 0);
2256 if (!oidInfo)
2258 SetLastError(NTE_BAD_ALGID);
2259 ret = FALSE;
2261 else
2263 ret = CryptCreateHash(hCryptProv, oidInfo->u.Algid, 0, 0, &hHash);
2264 if (ret)
2266 ret = CryptHashData(hHash, info->ToBeSigned.pbData,
2267 info->ToBeSigned.cbData, 0);
2268 if (ret)
2269 ret = CryptGetHashParam(hHash, HP_HASHVAL, pbComputedHash,
2270 pcbComputedHash, 0);
2271 CryptDestroyHash(hHash);
2274 LocalFree(info);
2276 return ret;
2279 BOOL WINAPI CryptSignCertificate(HCRYPTPROV_OR_NCRYPT_KEY_HANDLE hCryptProv,
2280 DWORD dwKeySpec, DWORD dwCertEncodingType, const BYTE *pbEncodedToBeSigned,
2281 DWORD cbEncodedToBeSigned, PCRYPT_ALGORITHM_IDENTIFIER pSignatureAlgorithm,
2282 const void *pvHashAuxInfo, BYTE *pbSignature, DWORD *pcbSignature)
2284 BOOL ret;
2285 PCCRYPT_OID_INFO info;
2286 HCRYPTHASH hHash;
2288 TRACE("(%08lx, %d, %d, %p, %d, %p, %p, %p, %p)\n", hCryptProv,
2289 dwKeySpec, dwCertEncodingType, pbEncodedToBeSigned, cbEncodedToBeSigned,
2290 pSignatureAlgorithm, pvHashAuxInfo, pbSignature, pcbSignature);
2292 info = CryptFindOIDInfo(CRYPT_OID_INFO_OID_KEY,
2293 pSignatureAlgorithm->pszObjId, 0);
2294 if (!info)
2296 SetLastError(NTE_BAD_ALGID);
2297 return FALSE;
2299 if (info->dwGroupId == CRYPT_HASH_ALG_OID_GROUP_ID)
2301 if (!hCryptProv)
2302 hCryptProv = CRYPT_GetDefaultProvider();
2303 ret = CryptCreateHash(hCryptProv, info->u.Algid, 0, 0, &hHash);
2304 if (ret)
2306 ret = CryptHashData(hHash, pbEncodedToBeSigned,
2307 cbEncodedToBeSigned, 0);
2308 if (ret)
2309 ret = CryptGetHashParam(hHash, HP_HASHVAL, pbSignature,
2310 pcbSignature, 0);
2311 CryptDestroyHash(hHash);
2314 else
2316 if (!hCryptProv)
2318 SetLastError(ERROR_INVALID_PARAMETER);
2319 ret = FALSE;
2321 else
2323 ret = CryptCreateHash(hCryptProv, info->u.Algid, 0, 0, &hHash);
2324 if (ret)
2326 ret = CryptHashData(hHash, pbEncodedToBeSigned,
2327 cbEncodedToBeSigned, 0);
2328 if (ret)
2329 ret = CryptSignHashW(hHash, dwKeySpec, NULL, 0, pbSignature,
2330 pcbSignature);
2331 CryptDestroyHash(hHash);
2335 return ret;
2338 BOOL WINAPI CryptSignAndEncodeCertificate(HCRYPTPROV_OR_NCRYPT_KEY_HANDLE hCryptProv,
2339 DWORD dwKeySpec, DWORD dwCertEncodingType, LPCSTR lpszStructType,
2340 const void *pvStructInfo, PCRYPT_ALGORITHM_IDENTIFIER pSignatureAlgorithm,
2341 const void *pvHashAuxInfo, BYTE *pbEncoded, DWORD *pcbEncoded)
2343 BOOL ret;
2344 DWORD encodedSize, hashSize;
2346 TRACE("(%08lx, %d, %d, %s, %p, %p, %p, %p, %p)\n", hCryptProv, dwKeySpec,
2347 dwCertEncodingType, debugstr_a(lpszStructType), pvStructInfo,
2348 pSignatureAlgorithm, pvHashAuxInfo, pbEncoded, pcbEncoded);
2350 ret = CryptEncodeObject(dwCertEncodingType, lpszStructType, pvStructInfo,
2351 NULL, &encodedSize);
2352 if (ret)
2354 PBYTE encoded = CryptMemAlloc(encodedSize);
2356 if (encoded)
2358 ret = CryptEncodeObject(dwCertEncodingType, lpszStructType,
2359 pvStructInfo, encoded, &encodedSize);
2360 if (ret)
2362 ret = CryptSignCertificate(hCryptProv, dwKeySpec,
2363 dwCertEncodingType, encoded, encodedSize, pSignatureAlgorithm,
2364 pvHashAuxInfo, NULL, &hashSize);
2365 if (ret)
2367 PBYTE hash = CryptMemAlloc(hashSize);
2369 if (hash)
2371 ret = CryptSignCertificate(hCryptProv, dwKeySpec,
2372 dwCertEncodingType, encoded, encodedSize,
2373 pSignatureAlgorithm, pvHashAuxInfo, hash, &hashSize);
2374 if (ret)
2376 CERT_SIGNED_CONTENT_INFO info = { { 0 } };
2378 info.ToBeSigned.cbData = encodedSize;
2379 info.ToBeSigned.pbData = encoded;
2380 info.SignatureAlgorithm = *pSignatureAlgorithm;
2381 info.Signature.cbData = hashSize;
2382 info.Signature.pbData = hash;
2383 info.Signature.cUnusedBits = 0;
2384 ret = CryptEncodeObject(dwCertEncodingType,
2385 X509_CERT, &info, pbEncoded, pcbEncoded);
2387 CryptMemFree(hash);
2389 else
2390 ret = FALSE;
2393 CryptMemFree(encoded);
2395 else
2396 ret = FALSE;
2398 return ret;
2401 BOOL WINAPI CryptVerifyCertificateSignature(HCRYPTPROV_LEGACY hCryptProv,
2402 DWORD dwCertEncodingType, const BYTE *pbEncoded, DWORD cbEncoded,
2403 PCERT_PUBLIC_KEY_INFO pPublicKey)
2405 CRYPT_DATA_BLOB blob = { cbEncoded, (BYTE *)pbEncoded };
2407 return CryptVerifyCertificateSignatureEx(hCryptProv, dwCertEncodingType,
2408 CRYPT_VERIFY_CERT_SIGN_SUBJECT_BLOB, &blob,
2409 CRYPT_VERIFY_CERT_SIGN_ISSUER_PUBKEY, pPublicKey, 0, NULL);
2412 static BOOL CRYPT_VerifyCertSignatureFromPublicKeyInfo(HCRYPTPROV_LEGACY hCryptProv,
2413 DWORD dwCertEncodingType, PCERT_PUBLIC_KEY_INFO pubKeyInfo,
2414 const CERT_SIGNED_CONTENT_INFO *signedCert)
2416 BOOL ret;
2417 HCRYPTKEY key;
2418 PCCRYPT_OID_INFO info;
2419 ALG_ID pubKeyID, hashID;
2421 info = CryptFindOIDInfo(CRYPT_OID_INFO_OID_KEY,
2422 signedCert->SignatureAlgorithm.pszObjId, 0);
2423 if (!info || info->dwGroupId != CRYPT_SIGN_ALG_OID_GROUP_ID)
2425 SetLastError(NTE_BAD_ALGID);
2426 return FALSE;
2428 hashID = info->u.Algid;
2429 if (info->ExtraInfo.cbData >= sizeof(ALG_ID))
2430 pubKeyID = *(ALG_ID *)info->ExtraInfo.pbData;
2431 else
2432 pubKeyID = hashID;
2433 /* Load the default provider if necessary */
2434 if (!hCryptProv)
2435 hCryptProv = CRYPT_GetDefaultProvider();
2436 ret = CryptImportPublicKeyInfoEx(hCryptProv, dwCertEncodingType,
2437 pubKeyInfo, pubKeyID, 0, NULL, &key);
2438 if (ret)
2440 HCRYPTHASH hash;
2442 ret = CryptCreateHash(hCryptProv, hashID, 0, 0, &hash);
2443 if (ret)
2445 ret = CryptHashData(hash, signedCert->ToBeSigned.pbData,
2446 signedCert->ToBeSigned.cbData, 0);
2447 if (ret)
2448 ret = CryptVerifySignatureW(hash, signedCert->Signature.pbData,
2449 signedCert->Signature.cbData, key, NULL, 0);
2450 CryptDestroyHash(hash);
2452 CryptDestroyKey(key);
2454 return ret;
2457 BOOL WINAPI CryptVerifyCertificateSignatureEx(HCRYPTPROV_LEGACY hCryptProv,
2458 DWORD dwCertEncodingType, DWORD dwSubjectType, void *pvSubject,
2459 DWORD dwIssuerType, void *pvIssuer, DWORD dwFlags, void *pvReserved)
2461 BOOL ret = TRUE;
2462 CRYPT_DATA_BLOB subjectBlob;
2464 TRACE("(%08lx, %d, %d, %p, %d, %p, %08x, %p)\n", hCryptProv,
2465 dwCertEncodingType, dwSubjectType, pvSubject, dwIssuerType, pvIssuer,
2466 dwFlags, pvReserved);
2468 switch (dwSubjectType)
2470 case CRYPT_VERIFY_CERT_SIGN_SUBJECT_BLOB:
2472 PCRYPT_DATA_BLOB blob = pvSubject;
2474 subjectBlob.pbData = blob->pbData;
2475 subjectBlob.cbData = blob->cbData;
2476 break;
2478 case CRYPT_VERIFY_CERT_SIGN_SUBJECT_CERT:
2480 PCERT_CONTEXT context = pvSubject;
2482 subjectBlob.pbData = context->pbCertEncoded;
2483 subjectBlob.cbData = context->cbCertEncoded;
2484 break;
2486 case CRYPT_VERIFY_CERT_SIGN_SUBJECT_CRL:
2488 PCRL_CONTEXT context = pvSubject;
2490 subjectBlob.pbData = context->pbCrlEncoded;
2491 subjectBlob.cbData = context->cbCrlEncoded;
2492 break;
2494 default:
2495 SetLastError(E_INVALIDARG);
2496 ret = FALSE;
2499 if (ret)
2501 PCERT_SIGNED_CONTENT_INFO signedCert = NULL;
2502 DWORD size = 0;
2504 ret = CryptDecodeObjectEx(dwCertEncodingType, X509_CERT,
2505 subjectBlob.pbData, subjectBlob.cbData,
2506 CRYPT_DECODE_ALLOC_FLAG | CRYPT_DECODE_NOCOPY_FLAG, NULL,
2507 &signedCert, &size);
2508 if (ret)
2510 switch (dwIssuerType)
2512 case CRYPT_VERIFY_CERT_SIGN_ISSUER_PUBKEY:
2513 ret = CRYPT_VerifyCertSignatureFromPublicKeyInfo(hCryptProv,
2514 dwCertEncodingType, pvIssuer,
2515 signedCert);
2516 break;
2517 case CRYPT_VERIFY_CERT_SIGN_ISSUER_CERT:
2518 ret = CRYPT_VerifyCertSignatureFromPublicKeyInfo(hCryptProv,
2519 dwCertEncodingType,
2520 &((PCCERT_CONTEXT)pvIssuer)->pCertInfo->SubjectPublicKeyInfo,
2521 signedCert);
2522 break;
2523 case CRYPT_VERIFY_CERT_SIGN_ISSUER_CHAIN:
2524 FIXME("CRYPT_VERIFY_CERT_SIGN_ISSUER_CHAIN: stub\n");
2525 ret = FALSE;
2526 break;
2527 case CRYPT_VERIFY_CERT_SIGN_ISSUER_NULL:
2528 if (pvIssuer)
2530 SetLastError(E_INVALIDARG);
2531 ret = FALSE;
2533 else
2535 FIXME("unimplemented for NULL signer\n");
2536 SetLastError(E_INVALIDARG);
2537 ret = FALSE;
2539 break;
2540 default:
2541 SetLastError(E_INVALIDARG);
2542 ret = FALSE;
2544 LocalFree(signedCert);
2547 return ret;
2550 BOOL WINAPI CertGetIntendedKeyUsage(DWORD dwCertEncodingType,
2551 PCERT_INFO pCertInfo, BYTE *pbKeyUsage, DWORD cbKeyUsage)
2553 PCERT_EXTENSION ext;
2554 BOOL ret = FALSE;
2556 TRACE("(%08x, %p, %p, %d)\n", dwCertEncodingType, pCertInfo, pbKeyUsage,
2557 cbKeyUsage);
2559 ext = CertFindExtension(szOID_KEY_USAGE, pCertInfo->cExtension,
2560 pCertInfo->rgExtension);
2561 if (ext)
2563 CRYPT_BIT_BLOB usage;
2564 DWORD size = sizeof(usage);
2566 ret = CryptDecodeObjectEx(dwCertEncodingType, X509_BITS,
2567 ext->Value.pbData, ext->Value.cbData, CRYPT_DECODE_NOCOPY_FLAG, NULL,
2568 &usage, &size);
2569 if (ret)
2571 if (cbKeyUsage < usage.cbData)
2572 ret = FALSE;
2573 else
2575 memcpy(pbKeyUsage, usage.pbData, usage.cbData);
2576 if (cbKeyUsage > usage.cbData)
2577 memset(pbKeyUsage + usage.cbData, 0,
2578 cbKeyUsage - usage.cbData);
2582 else
2583 SetLastError(0);
2584 return ret;
2587 BOOL WINAPI CertGetEnhancedKeyUsage(PCCERT_CONTEXT pCertContext, DWORD dwFlags,
2588 PCERT_ENHKEY_USAGE pUsage, DWORD *pcbUsage)
2590 PCERT_ENHKEY_USAGE usage = NULL;
2591 DWORD bytesNeeded;
2592 BOOL ret = TRUE;
2594 if (!pCertContext || !pcbUsage)
2596 SetLastError(ERROR_INVALID_PARAMETER);
2597 return FALSE;
2600 TRACE("(%p, %08x, %p, %d)\n", pCertContext, dwFlags, pUsage, *pcbUsage);
2602 if (!(dwFlags & CERT_FIND_EXT_ONLY_ENHKEY_USAGE_FLAG))
2604 DWORD propSize = 0;
2606 if (CertGetCertificateContextProperty(pCertContext,
2607 CERT_ENHKEY_USAGE_PROP_ID, NULL, &propSize))
2609 LPBYTE buf = CryptMemAlloc(propSize);
2611 if (buf)
2613 if (CertGetCertificateContextProperty(pCertContext,
2614 CERT_ENHKEY_USAGE_PROP_ID, buf, &propSize))
2616 ret = CryptDecodeObjectEx(pCertContext->dwCertEncodingType,
2617 X509_ENHANCED_KEY_USAGE, buf, propSize,
2618 CRYPT_ENCODE_ALLOC_FLAG, NULL, &usage, &bytesNeeded);
2620 CryptMemFree(buf);
2624 if (!usage && !(dwFlags & CERT_FIND_PROP_ONLY_ENHKEY_USAGE_FLAG))
2626 PCERT_EXTENSION ext = CertFindExtension(szOID_ENHANCED_KEY_USAGE,
2627 pCertContext->pCertInfo->cExtension,
2628 pCertContext->pCertInfo->rgExtension);
2630 if (ext)
2632 ret = CryptDecodeObjectEx(pCertContext->dwCertEncodingType,
2633 X509_ENHANCED_KEY_USAGE, ext->Value.pbData, ext->Value.cbData,
2634 CRYPT_ENCODE_ALLOC_FLAG, NULL, &usage, &bytesNeeded);
2637 if (!usage)
2639 /* If a particular location is specified, this should fail. Otherwise
2640 * it should succeed with an empty usage. (This is true on Win2k and
2641 * later, which we emulate.)
2643 if (dwFlags)
2645 SetLastError(CRYPT_E_NOT_FOUND);
2646 ret = FALSE;
2648 else
2649 bytesNeeded = sizeof(CERT_ENHKEY_USAGE);
2652 if (ret)
2654 if (!pUsage)
2655 *pcbUsage = bytesNeeded;
2656 else if (*pcbUsage < bytesNeeded)
2658 SetLastError(ERROR_MORE_DATA);
2659 *pcbUsage = bytesNeeded;
2660 ret = FALSE;
2662 else
2664 *pcbUsage = bytesNeeded;
2665 if (usage)
2667 DWORD i;
2668 LPSTR nextOID = (LPSTR)((LPBYTE)pUsage +
2669 sizeof(CERT_ENHKEY_USAGE) +
2670 usage->cUsageIdentifier * sizeof(LPSTR));
2672 pUsage->cUsageIdentifier = usage->cUsageIdentifier;
2673 pUsage->rgpszUsageIdentifier = (LPSTR *)((LPBYTE)pUsage +
2674 sizeof(CERT_ENHKEY_USAGE));
2675 for (i = 0; i < usage->cUsageIdentifier; i++)
2677 pUsage->rgpszUsageIdentifier[i] = nextOID;
2678 strcpy(nextOID, usage->rgpszUsageIdentifier[i]);
2679 nextOID += strlen(nextOID) + 1;
2682 else
2683 pUsage->cUsageIdentifier = 0;
2686 if (usage)
2687 LocalFree(usage);
2688 TRACE("returning %d\n", ret);
2689 return ret;
2692 BOOL WINAPI CertSetEnhancedKeyUsage(PCCERT_CONTEXT pCertContext,
2693 PCERT_ENHKEY_USAGE pUsage)
2695 BOOL ret;
2697 TRACE("(%p, %p)\n", pCertContext, pUsage);
2699 if (pUsage)
2701 CRYPT_DATA_BLOB blob = { 0, NULL };
2703 ret = CryptEncodeObjectEx(X509_ASN_ENCODING, X509_ENHANCED_KEY_USAGE,
2704 pUsage, CRYPT_ENCODE_ALLOC_FLAG, NULL, &blob.pbData, &blob.cbData);
2705 if (ret)
2707 ret = CertSetCertificateContextProperty(pCertContext,
2708 CERT_ENHKEY_USAGE_PROP_ID, 0, &blob);
2709 LocalFree(blob.pbData);
2712 else
2713 ret = CertSetCertificateContextProperty(pCertContext,
2714 CERT_ENHKEY_USAGE_PROP_ID, 0, NULL);
2715 return ret;
2718 BOOL WINAPI CertAddEnhancedKeyUsageIdentifier(PCCERT_CONTEXT pCertContext,
2719 LPCSTR pszUsageIdentifier)
2721 BOOL ret;
2722 DWORD size;
2724 TRACE("(%p, %s)\n", pCertContext, debugstr_a(pszUsageIdentifier));
2726 if (CertGetEnhancedKeyUsage(pCertContext,
2727 CERT_FIND_PROP_ONLY_ENHKEY_USAGE_FLAG, NULL, &size))
2729 PCERT_ENHKEY_USAGE usage = CryptMemAlloc(size);
2731 if (usage)
2733 ret = CertGetEnhancedKeyUsage(pCertContext,
2734 CERT_FIND_PROP_ONLY_ENHKEY_USAGE_FLAG, usage, &size);
2735 if (ret)
2737 DWORD i;
2738 BOOL exists = FALSE;
2740 /* Make sure usage doesn't already exist */
2741 for (i = 0; !exists && i < usage->cUsageIdentifier; i++)
2743 if (!strcmp(usage->rgpszUsageIdentifier[i],
2744 pszUsageIdentifier))
2745 exists = TRUE;
2747 if (!exists)
2749 PCERT_ENHKEY_USAGE newUsage = CryptMemAlloc(size +
2750 sizeof(LPSTR) + strlen(pszUsageIdentifier) + 1);
2752 if (newUsage)
2754 LPSTR nextOID;
2756 newUsage->rgpszUsageIdentifier = (LPSTR *)
2757 ((LPBYTE)newUsage + sizeof(CERT_ENHKEY_USAGE));
2758 nextOID = (LPSTR)((LPBYTE)newUsage->rgpszUsageIdentifier
2759 + (usage->cUsageIdentifier + 1) * sizeof(LPSTR));
2760 for (i = 0; i < usage->cUsageIdentifier; i++)
2762 newUsage->rgpszUsageIdentifier[i] = nextOID;
2763 strcpy(nextOID, usage->rgpszUsageIdentifier[i]);
2764 nextOID += strlen(nextOID) + 1;
2766 newUsage->rgpszUsageIdentifier[i] = nextOID;
2767 strcpy(nextOID, pszUsageIdentifier);
2768 newUsage->cUsageIdentifier = i + 1;
2769 ret = CertSetEnhancedKeyUsage(pCertContext, newUsage);
2770 CryptMemFree(newUsage);
2772 else
2773 ret = FALSE;
2776 CryptMemFree(usage);
2778 else
2779 ret = FALSE;
2781 else
2783 PCERT_ENHKEY_USAGE usage = CryptMemAlloc(sizeof(CERT_ENHKEY_USAGE) +
2784 sizeof(LPSTR) + strlen(pszUsageIdentifier) + 1);
2786 if (usage)
2788 usage->rgpszUsageIdentifier =
2789 (LPSTR *)((LPBYTE)usage + sizeof(CERT_ENHKEY_USAGE));
2790 usage->rgpszUsageIdentifier[0] = (LPSTR)((LPBYTE)usage +
2791 sizeof(CERT_ENHKEY_USAGE) + sizeof(LPSTR));
2792 strcpy(usage->rgpszUsageIdentifier[0], pszUsageIdentifier);
2793 usage->cUsageIdentifier = 1;
2794 ret = CertSetEnhancedKeyUsage(pCertContext, usage);
2795 CryptMemFree(usage);
2797 else
2798 ret = FALSE;
2800 return ret;
2803 BOOL WINAPI CertRemoveEnhancedKeyUsageIdentifier(PCCERT_CONTEXT pCertContext,
2804 LPCSTR pszUsageIdentifier)
2806 BOOL ret;
2807 DWORD size;
2808 CERT_ENHKEY_USAGE usage;
2810 TRACE("(%p, %s)\n", pCertContext, debugstr_a(pszUsageIdentifier));
2812 size = sizeof(usage);
2813 ret = CertGetEnhancedKeyUsage(pCertContext,
2814 CERT_FIND_PROP_ONLY_ENHKEY_USAGE_FLAG, &usage, &size);
2815 if (!ret && GetLastError() == ERROR_MORE_DATA)
2817 PCERT_ENHKEY_USAGE pUsage = CryptMemAlloc(size);
2819 if (pUsage)
2821 ret = CertGetEnhancedKeyUsage(pCertContext,
2822 CERT_FIND_PROP_ONLY_ENHKEY_USAGE_FLAG, pUsage, &size);
2823 if (ret)
2825 if (pUsage->cUsageIdentifier)
2827 DWORD i;
2828 BOOL found = FALSE;
2830 for (i = 0; i < pUsage->cUsageIdentifier; i++)
2832 if (!strcmp(pUsage->rgpszUsageIdentifier[i],
2833 pszUsageIdentifier))
2834 found = TRUE;
2835 if (found && i < pUsage->cUsageIdentifier - 1)
2836 pUsage->rgpszUsageIdentifier[i] =
2837 pUsage->rgpszUsageIdentifier[i + 1];
2839 pUsage->cUsageIdentifier--;
2840 /* Remove the usage if it's empty */
2841 if (pUsage->cUsageIdentifier)
2842 ret = CertSetEnhancedKeyUsage(pCertContext, pUsage);
2843 else
2844 ret = CertSetEnhancedKeyUsage(pCertContext, NULL);
2847 CryptMemFree(pUsage);
2849 else
2850 ret = FALSE;
2852 else
2854 /* it fit in an empty usage, therefore there's nothing to remove */
2855 ret = TRUE;
2857 return ret;
2860 struct BitField
2862 DWORD cIndexes;
2863 DWORD *indexes;
2866 #define BITS_PER_DWORD (sizeof(DWORD) * 8)
2868 static void CRYPT_SetBitInField(struct BitField *field, DWORD bit)
2870 DWORD indexIndex = bit / BITS_PER_DWORD;
2872 if (indexIndex + 1 > field->cIndexes)
2874 if (field->cIndexes)
2875 field->indexes = CryptMemRealloc(field->indexes,
2876 (indexIndex + 1) * sizeof(DWORD));
2877 else
2878 field->indexes = CryptMemAlloc(sizeof(DWORD));
2879 if (field->indexes)
2881 field->indexes[indexIndex] = 0;
2882 field->cIndexes = indexIndex + 1;
2885 if (field->indexes)
2886 field->indexes[indexIndex] |= 1 << (bit % BITS_PER_DWORD);
2889 static BOOL CRYPT_IsBitInFieldSet(const struct BitField *field, DWORD bit)
2891 BOOL set;
2892 DWORD indexIndex = bit / BITS_PER_DWORD;
2894 assert(field->cIndexes);
2895 set = field->indexes[indexIndex] & (1 << (bit % BITS_PER_DWORD));
2896 return set;
2899 BOOL WINAPI CertGetValidUsages(DWORD cCerts, PCCERT_CONTEXT *rghCerts,
2900 int *cNumOIDs, LPSTR *rghOIDs, DWORD *pcbOIDs)
2902 BOOL ret = TRUE;
2903 DWORD i, cbOIDs = 0;
2904 BOOL allUsagesValid = TRUE;
2905 CERT_ENHKEY_USAGE validUsages = { 0, NULL };
2907 TRACE("(%d, %p, %d, %p, %d)\n", cCerts, rghCerts, *cNumOIDs,
2908 rghOIDs, *pcbOIDs);
2910 for (i = 0; i < cCerts; i++)
2912 CERT_ENHKEY_USAGE usage;
2913 DWORD size = sizeof(usage);
2915 ret = CertGetEnhancedKeyUsage(rghCerts[i], 0, &usage, &size);
2916 /* Success is deliberately ignored: it implies all usages are valid */
2917 if (!ret && GetLastError() == ERROR_MORE_DATA)
2919 PCERT_ENHKEY_USAGE pUsage = CryptMemAlloc(size);
2921 allUsagesValid = FALSE;
2922 if (pUsage)
2924 ret = CertGetEnhancedKeyUsage(rghCerts[i], 0, pUsage, &size);
2925 if (ret)
2927 if (!validUsages.cUsageIdentifier)
2929 DWORD j;
2931 cbOIDs = pUsage->cUsageIdentifier * sizeof(LPSTR);
2932 validUsages.cUsageIdentifier = pUsage->cUsageIdentifier;
2933 for (j = 0; j < validUsages.cUsageIdentifier; j++)
2934 cbOIDs += lstrlenA(pUsage->rgpszUsageIdentifier[j])
2935 + 1;
2936 validUsages.rgpszUsageIdentifier =
2937 CryptMemAlloc(cbOIDs);
2938 if (validUsages.rgpszUsageIdentifier)
2940 LPSTR nextOID = (LPSTR)
2941 ((LPBYTE)validUsages.rgpszUsageIdentifier +
2942 validUsages.cUsageIdentifier * sizeof(LPSTR));
2944 for (j = 0; j < validUsages.cUsageIdentifier; j++)
2946 validUsages.rgpszUsageIdentifier[j] = nextOID;
2947 lstrcpyA(validUsages.rgpszUsageIdentifier[j],
2948 pUsage->rgpszUsageIdentifier[j]);
2949 nextOID += lstrlenA(nextOID) + 1;
2953 else
2955 struct BitField validIndexes = { 0, NULL };
2956 DWORD j, k, numRemoved = 0;
2958 /* Merge: build a bitmap of all the indexes of
2959 * validUsages.rgpszUsageIdentifier that are in pUsage.
2961 for (j = 0; j < pUsage->cUsageIdentifier; j++)
2963 for (k = 0; k < validUsages.cUsageIdentifier; k++)
2965 if (!strcmp(pUsage->rgpszUsageIdentifier[j],
2966 validUsages.rgpszUsageIdentifier[k]))
2968 CRYPT_SetBitInField(&validIndexes, k);
2969 break;
2973 /* Merge by removing from validUsages those that are
2974 * not in the bitmap.
2976 for (j = 0; j < validUsages.cUsageIdentifier; j++)
2978 if (!CRYPT_IsBitInFieldSet(&validIndexes, j))
2980 if (j < validUsages.cUsageIdentifier - 1)
2982 memmove(&validUsages.rgpszUsageIdentifier[j],
2983 &validUsages.rgpszUsageIdentifier[j +
2984 numRemoved + 1],
2985 (validUsages.cUsageIdentifier - numRemoved
2986 - j - 1) * sizeof(LPSTR));
2987 cbOIDs -= lstrlenA(
2988 validUsages.rgpszUsageIdentifier[j]) + 1 +
2989 sizeof(LPSTR);
2990 validUsages.cUsageIdentifier--;
2991 numRemoved++;
2993 else
2994 validUsages.cUsageIdentifier--;
2997 CryptMemFree(validIndexes.indexes);
3000 CryptMemFree(pUsage);
3004 ret = TRUE;
3005 if (allUsagesValid)
3007 *cNumOIDs = -1;
3008 *pcbOIDs = 0;
3010 else
3012 *cNumOIDs = validUsages.cUsageIdentifier;
3013 if (!rghOIDs)
3014 *pcbOIDs = cbOIDs;
3015 else if (*pcbOIDs < cbOIDs)
3017 *pcbOIDs = cbOIDs;
3018 SetLastError(ERROR_MORE_DATA);
3019 ret = FALSE;
3021 else
3023 LPSTR nextOID = (LPSTR)((LPBYTE)rghOIDs +
3024 validUsages.cUsageIdentifier * sizeof(LPSTR));
3026 *pcbOIDs = cbOIDs;
3027 for (i = 0; i < validUsages.cUsageIdentifier; i++)
3029 rghOIDs[i] = nextOID;
3030 lstrcpyA(nextOID, validUsages.rgpszUsageIdentifier[i]);
3031 nextOID += lstrlenA(nextOID) + 1;
3035 CryptMemFree(validUsages.rgpszUsageIdentifier);
3036 TRACE("cNumOIDs: %d\n", *cNumOIDs);
3037 TRACE("returning %d\n", ret);
3038 return ret;
3041 /* Sets the CERT_KEY_PROV_INFO_PROP_ID property of context from pInfo, or, if
3042 * pInfo is NULL, from the attributes of hProv.
3044 static void CertContext_SetKeyProvInfo(PCCERT_CONTEXT context,
3045 const CRYPT_KEY_PROV_INFO *pInfo, HCRYPTPROV hProv)
3047 CRYPT_KEY_PROV_INFO info = { 0 };
3048 BOOL ret;
3050 if (!pInfo)
3052 DWORD size;
3053 int len;
3055 ret = CryptGetProvParam(hProv, PP_CONTAINER, NULL, &size, 0);
3056 if (ret)
3058 LPSTR szContainer = CryptMemAlloc(size);
3060 if (szContainer)
3062 ret = CryptGetProvParam(hProv, PP_CONTAINER,
3063 (BYTE *)szContainer, &size, 0);
3064 if (ret)
3066 len = MultiByteToWideChar(CP_ACP, 0, szContainer, -1,
3067 NULL, 0);
3068 if (len)
3070 info.pwszContainerName = CryptMemAlloc(len *
3071 sizeof(WCHAR));
3072 MultiByteToWideChar(CP_ACP, 0, szContainer, -1,
3073 info.pwszContainerName, len);
3076 CryptMemFree(szContainer);
3079 ret = CryptGetProvParam(hProv, PP_NAME, NULL, &size, 0);
3080 if (ret)
3082 LPSTR szProvider = CryptMemAlloc(size);
3084 if (szProvider)
3086 ret = CryptGetProvParam(hProv, PP_NAME, (BYTE *)szProvider,
3087 &size, 0);
3088 if (ret)
3090 len = MultiByteToWideChar(CP_ACP, 0, szProvider, -1,
3091 NULL, 0);
3092 if (len)
3094 info.pwszProvName = CryptMemAlloc(len *
3095 sizeof(WCHAR));
3096 MultiByteToWideChar(CP_ACP, 0, szProvider, -1,
3097 info.pwszProvName, len);
3100 CryptMemFree(szProvider);
3103 /* in case no CRYPT_KEY_PROV_INFO given,
3104 * we always use AT_SIGNATURE key spec
3106 info.dwKeySpec = AT_SIGNATURE;
3107 size = sizeof(info.dwProvType);
3108 ret = CryptGetProvParam(hProv, PP_PROVTYPE, (LPBYTE)&info.dwProvType,
3109 &size, 0);
3110 if (!ret)
3111 info.dwProvType = PROV_RSA_FULL;
3112 pInfo = &info;
3115 CertSetCertificateContextProperty(context, CERT_KEY_PROV_INFO_PROP_ID,
3116 0, pInfo);
3118 if (pInfo == &info)
3120 CryptMemFree(info.pwszContainerName);
3121 CryptMemFree(info.pwszProvName);
3125 /* Creates a signed certificate context from the unsigned, encoded certificate
3126 * in blob, using the crypto provider hProv and the signature algorithm sigAlgo.
3128 static PCCERT_CONTEXT CRYPT_CreateSignedCert(const CRYPT_DER_BLOB *blob,
3129 HCRYPTPROV hProv, DWORD dwKeySpec, PCRYPT_ALGORITHM_IDENTIFIER sigAlgo)
3131 PCCERT_CONTEXT context = NULL;
3132 BOOL ret;
3133 DWORD sigSize = 0;
3135 ret = CryptSignCertificate(hProv, dwKeySpec, X509_ASN_ENCODING,
3136 blob->pbData, blob->cbData, sigAlgo, NULL, NULL, &sigSize);
3137 if (ret)
3139 LPBYTE sig = CryptMemAlloc(sigSize);
3141 ret = CryptSignCertificate(hProv, dwKeySpec, X509_ASN_ENCODING,
3142 blob->pbData, blob->cbData, sigAlgo, NULL, sig, &sigSize);
3143 if (ret)
3145 CERT_SIGNED_CONTENT_INFO signedInfo;
3146 BYTE *encodedSignedCert = NULL;
3147 DWORD encodedSignedCertSize = 0;
3149 signedInfo.ToBeSigned.cbData = blob->cbData;
3150 signedInfo.ToBeSigned.pbData = blob->pbData;
3151 signedInfo.SignatureAlgorithm = *sigAlgo;
3152 signedInfo.Signature.cbData = sigSize;
3153 signedInfo.Signature.pbData = sig;
3154 signedInfo.Signature.cUnusedBits = 0;
3155 ret = CryptEncodeObjectEx(X509_ASN_ENCODING, X509_CERT,
3156 &signedInfo, CRYPT_ENCODE_ALLOC_FLAG, NULL,
3157 &encodedSignedCert, &encodedSignedCertSize);
3158 if (ret)
3160 context = CertCreateCertificateContext(X509_ASN_ENCODING,
3161 encodedSignedCert, encodedSignedCertSize);
3162 LocalFree(encodedSignedCert);
3165 CryptMemFree(sig);
3167 return context;
3170 /* Copies data from the parameters into info, where:
3171 * pSerialNumber: The serial number. Must not be NULL.
3172 * pSubjectIssuerBlob: Specifies both the subject and issuer for info.
3173 * Must not be NULL
3174 * pSignatureAlgorithm: Optional.
3175 * pStartTime: The starting time of the certificate. If NULL, the current
3176 * system time is used.
3177 * pEndTime: The ending time of the certificate. If NULL, one year past the
3178 * starting time is used.
3179 * pubKey: The public key of the certificate. Must not be NULL.
3180 * pExtensions: Extensions to be included with the certificate. Optional.
3182 static void CRYPT_MakeCertInfo(PCERT_INFO info, const CRYPT_DATA_BLOB *pSerialNumber,
3183 const CERT_NAME_BLOB *pSubjectIssuerBlob,
3184 const CRYPT_ALGORITHM_IDENTIFIER *pSignatureAlgorithm, const SYSTEMTIME *pStartTime,
3185 const SYSTEMTIME *pEndTime, const CERT_PUBLIC_KEY_INFO *pubKey,
3186 const CERT_EXTENSIONS *pExtensions)
3188 static CHAR oid[] = szOID_RSA_SHA1RSA;
3190 assert(info);
3191 assert(pSerialNumber);
3192 assert(pSubjectIssuerBlob);
3193 assert(pubKey);
3195 if (pExtensions && pExtensions->cExtension)
3196 info->dwVersion = CERT_V3;
3197 else
3198 info->dwVersion = CERT_V1;
3199 info->SerialNumber.cbData = pSerialNumber->cbData;
3200 info->SerialNumber.pbData = pSerialNumber->pbData;
3201 if (pSignatureAlgorithm)
3202 info->SignatureAlgorithm = *pSignatureAlgorithm;
3203 else
3205 info->SignatureAlgorithm.pszObjId = oid;
3206 info->SignatureAlgorithm.Parameters.cbData = 0;
3207 info->SignatureAlgorithm.Parameters.pbData = NULL;
3209 info->Issuer.cbData = pSubjectIssuerBlob->cbData;
3210 info->Issuer.pbData = pSubjectIssuerBlob->pbData;
3211 if (pStartTime)
3212 SystemTimeToFileTime(pStartTime, &info->NotBefore);
3213 else
3214 GetSystemTimeAsFileTime(&info->NotBefore);
3215 if (pEndTime)
3216 SystemTimeToFileTime(pEndTime, &info->NotAfter);
3217 else
3219 SYSTEMTIME endTime;
3221 if (FileTimeToSystemTime(&info->NotBefore, &endTime))
3223 endTime.wYear++;
3224 SystemTimeToFileTime(&endTime, &info->NotAfter);
3227 info->Subject.cbData = pSubjectIssuerBlob->cbData;
3228 info->Subject.pbData = pSubjectIssuerBlob->pbData;
3229 info->SubjectPublicKeyInfo = *pubKey;
3230 if (pExtensions)
3232 info->cExtension = pExtensions->cExtension;
3233 info->rgExtension = pExtensions->rgExtension;
3235 else
3237 info->cExtension = 0;
3238 info->rgExtension = NULL;
3242 typedef RPC_STATUS (RPC_ENTRY *UuidCreateFunc)(UUID *);
3243 typedef RPC_STATUS (RPC_ENTRY *UuidToStringFunc)(UUID *, unsigned char **);
3244 typedef RPC_STATUS (RPC_ENTRY *RpcStringFreeFunc)(unsigned char **);
3246 static HCRYPTPROV CRYPT_CreateKeyProv(void)
3248 HCRYPTPROV hProv = 0;
3249 HMODULE rpcrt = LoadLibraryA("rpcrt4");
3251 if (rpcrt)
3253 UuidCreateFunc uuidCreate = (UuidCreateFunc)GetProcAddress(rpcrt,
3254 "UuidCreate");
3255 UuidToStringFunc uuidToString = (UuidToStringFunc)GetProcAddress(rpcrt,
3256 "UuidToStringA");
3257 RpcStringFreeFunc rpcStringFree = (RpcStringFreeFunc)GetProcAddress(
3258 rpcrt, "RpcStringFreeA");
3260 if (uuidCreate && uuidToString && rpcStringFree)
3262 UUID uuid;
3263 RPC_STATUS status = uuidCreate(&uuid);
3265 if (status == RPC_S_OK || status == RPC_S_UUID_LOCAL_ONLY)
3267 unsigned char *uuidStr;
3269 status = uuidToString(&uuid, &uuidStr);
3270 if (status == RPC_S_OK)
3272 BOOL ret = CryptAcquireContextA(&hProv, (LPCSTR)uuidStr,
3273 MS_DEF_PROV_A, PROV_RSA_FULL, CRYPT_NEWKEYSET);
3275 if (ret)
3277 HCRYPTKEY key;
3279 ret = CryptGenKey(hProv, AT_SIGNATURE, 0, &key);
3280 if (ret)
3281 CryptDestroyKey(key);
3283 rpcStringFree(&uuidStr);
3287 FreeLibrary(rpcrt);
3289 return hProv;
3292 PCCERT_CONTEXT WINAPI CertCreateSelfSignCertificate(HCRYPTPROV_OR_NCRYPT_KEY_HANDLE hProv,
3293 PCERT_NAME_BLOB pSubjectIssuerBlob, DWORD dwFlags,
3294 PCRYPT_KEY_PROV_INFO pKeyProvInfo,
3295 PCRYPT_ALGORITHM_IDENTIFIER pSignatureAlgorithm, PSYSTEMTIME pStartTime,
3296 PSYSTEMTIME pEndTime, PCERT_EXTENSIONS pExtensions)
3298 PCCERT_CONTEXT context = NULL;
3299 BOOL ret, releaseContext = FALSE;
3300 PCERT_PUBLIC_KEY_INFO pubKey = NULL;
3301 DWORD pubKeySize = 0, dwKeySpec;
3303 TRACE("(%08lx, %p, %08x, %p, %p, %p, %p, %p)\n", hProv,
3304 pSubjectIssuerBlob, dwFlags, pKeyProvInfo, pSignatureAlgorithm, pStartTime,
3305 pExtensions, pExtensions);
3307 if(!pSubjectIssuerBlob)
3309 SetLastError(ERROR_INVALID_PARAMETER);
3310 return NULL;
3313 dwKeySpec = pKeyProvInfo ? pKeyProvInfo->dwKeySpec : AT_SIGNATURE;
3314 if (!hProv)
3316 if (!pKeyProvInfo)
3318 hProv = CRYPT_CreateKeyProv();
3319 releaseContext = TRUE;
3321 else if (pKeyProvInfo->dwFlags & CERT_SET_KEY_PROV_HANDLE_PROP_ID)
3323 SetLastError(NTE_BAD_FLAGS);
3324 return NULL;
3326 else
3328 HCRYPTKEY hKey = 0;
3329 /* acquire the context using the given information*/
3330 ret = CryptAcquireContextW(&hProv,pKeyProvInfo->pwszContainerName,
3331 pKeyProvInfo->pwszProvName,pKeyProvInfo->dwProvType,
3332 pKeyProvInfo->dwFlags);
3333 if (!ret)
3335 if(GetLastError() != NTE_BAD_KEYSET)
3336 return NULL;
3337 /* create the key set */
3338 ret = CryptAcquireContextW(&hProv,pKeyProvInfo->pwszContainerName,
3339 pKeyProvInfo->pwszProvName,pKeyProvInfo->dwProvType,
3340 pKeyProvInfo->dwFlags|CRYPT_NEWKEYSET);
3341 if (!ret)
3342 return NULL;
3344 /* check if the key is here */
3345 ret = CryptGetUserKey(hProv,dwKeySpec,&hKey);
3346 if(!ret)
3348 if (NTE_NO_KEY == GetLastError())
3349 { /* generate the key */
3350 ret = CryptGenKey(hProv,dwKeySpec,0,&hKey);
3352 if (!ret)
3354 CryptReleaseContext(hProv,0);
3355 SetLastError(NTE_BAD_KEYSET);
3356 return NULL;
3359 CryptDestroyKey(hKey);
3360 releaseContext = TRUE;
3364 ret = CryptExportPublicKeyInfo(hProv, dwKeySpec, X509_ASN_ENCODING, NULL,
3365 &pubKeySize);
3366 if (!ret)
3367 goto end;
3368 pubKey = CryptMemAlloc(pubKeySize);
3369 if (pubKey)
3371 ret = CryptExportPublicKeyInfo(hProv, dwKeySpec, X509_ASN_ENCODING,
3372 pubKey, &pubKeySize);
3373 if (ret)
3375 CERT_INFO info = { 0 };
3376 CRYPT_DER_BLOB blob = { 0, NULL };
3377 BYTE serial[16];
3378 CRYPT_DATA_BLOB serialBlob = { sizeof(serial), serial };
3380 CryptGenRandom(hProv, sizeof(serial), serial);
3381 CRYPT_MakeCertInfo(&info, &serialBlob, pSubjectIssuerBlob,
3382 pSignatureAlgorithm, pStartTime, pEndTime, pubKey, pExtensions);
3383 ret = CryptEncodeObjectEx(X509_ASN_ENCODING, X509_CERT_TO_BE_SIGNED,
3384 &info, CRYPT_ENCODE_ALLOC_FLAG, NULL, &blob.pbData,
3385 &blob.cbData);
3386 if (ret)
3388 if (!(dwFlags & CERT_CREATE_SELFSIGN_NO_SIGN))
3389 context = CRYPT_CreateSignedCert(&blob, hProv,dwKeySpec,
3390 &info.SignatureAlgorithm);
3391 else
3392 context = CertCreateCertificateContext(X509_ASN_ENCODING,
3393 blob.pbData, blob.cbData);
3394 if (context && !(dwFlags & CERT_CREATE_SELFSIGN_NO_KEY_INFO))
3395 CertContext_SetKeyProvInfo(context, pKeyProvInfo, hProv);
3396 LocalFree(blob.pbData);
3399 CryptMemFree(pubKey);
3401 end:
3402 if (releaseContext)
3403 CryptReleaseContext(hProv, 0);
3404 return context;
3407 BOOL WINAPI CertVerifyCTLUsage(DWORD dwEncodingType, DWORD dwSubjectType,
3408 void *pvSubject, PCTL_USAGE pSubjectUsage, DWORD dwFlags,
3409 PCTL_VERIFY_USAGE_PARA pVerifyUsagePara,
3410 PCTL_VERIFY_USAGE_STATUS pVerifyUsageStatus)
3412 FIXME("(0x%x, %d, %p, %p, 0x%x, %p, %p): stub\n", dwEncodingType,
3413 dwSubjectType, pvSubject, pSubjectUsage, dwFlags, pVerifyUsagePara,
3414 pVerifyUsageStatus);
3415 SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
3416 return FALSE;
3419 const void * WINAPI CertCreateContext(DWORD dwContextType, DWORD dwEncodingType,
3420 const BYTE *pbEncoded, DWORD cbEncoded,
3421 DWORD dwFlags, PCERT_CREATE_CONTEXT_PARA pCreatePara)
3423 TRACE("(0x%x, 0x%x, %p, %d, 0x%08x, %p)\n", dwContextType, dwEncodingType,
3424 pbEncoded, cbEncoded, dwFlags, pCreatePara);
3426 if (dwFlags)
3428 FIXME("dwFlags 0x%08x not handled\n", dwFlags);
3429 return NULL;
3431 if (pCreatePara)
3433 FIXME("pCreatePara not handled\n");
3434 return NULL;
3437 switch (dwContextType)
3439 case CERT_STORE_CERTIFICATE_CONTEXT:
3440 return CertCreateCertificateContext(dwEncodingType, pbEncoded, cbEncoded);
3441 case CERT_STORE_CRL_CONTEXT:
3442 return CertCreateCRLContext(dwEncodingType, pbEncoded, cbEncoded);
3443 case CERT_STORE_CTL_CONTEXT:
3444 return CertCreateCTLContext(dwEncodingType, pbEncoded, cbEncoded);
3445 default:
3446 WARN("unknown context type: 0x%x\n", dwContextType);
3447 return NULL;