dmime: Remove DECLSPEC_HIDDEN usage.
[wine.git] / dlls / crypt32 / cert.c
blobb9645770ce17871d64ab45d58fedd4003be4914b
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 "ntstatus.h"
25 #define WIN32_NO_STATUS
26 #include "windef.h"
27 #include "winbase.h"
28 #include "winternl.h"
29 #define CRYPT_OID_INFO_HAS_EXTRA_FIELDS
30 #include "wincrypt.h"
31 #include "snmp.h"
32 #include "bcrypt.h"
33 #include "winnls.h"
34 #include "rpc.h"
35 #include "wine/debug.h"
36 #include "crypt32_private.h"
38 WINE_DEFAULT_DEBUG_CHANNEL(crypt);
40 /* Internal version of CertGetCertificateContextProperty that gets properties
41 * directly from the context (or the context it's linked to, depending on its
42 * type.) Doesn't handle special-case properties, since they are handled by
43 * CertGetCertificateContextProperty, and are particular to the store in which
44 * the property exists (which is separate from the context.)
46 static BOOL CertContext_GetProperty(cert_t *cert, DWORD dwPropId,
47 void *pvData, DWORD *pcbData);
49 /* Internal version of CertSetCertificateContextProperty that sets properties
50 * directly on the context (or the context it's linked to, depending on its
51 * type.) Doesn't handle special cases, since they're handled by
52 * CertSetCertificateContextProperty anyway.
54 static BOOL CertContext_SetProperty(cert_t *cert, DWORD dwPropId,
55 DWORD dwFlags, const void *pvData);
57 BOOL WINAPI CertAddEncodedCertificateToStore(HCERTSTORE hCertStore,
58 DWORD dwCertEncodingType, const BYTE *pbCertEncoded, DWORD cbCertEncoded,
59 DWORD dwAddDisposition, PCCERT_CONTEXT *ppCertContext)
61 PCCERT_CONTEXT cert = CertCreateCertificateContext(dwCertEncodingType,
62 pbCertEncoded, cbCertEncoded);
63 BOOL ret;
65 TRACE("(%p, %08lx, %p, %ld, %08lx, %p)\n", hCertStore, dwCertEncodingType,
66 pbCertEncoded, cbCertEncoded, dwAddDisposition, ppCertContext);
68 if (cert)
70 ret = CertAddCertificateContextToStore(hCertStore, cert,
71 dwAddDisposition, ppCertContext);
72 CertFreeCertificateContext(cert);
74 else
75 ret = FALSE;
76 return ret;
79 BOOL WINAPI CertAddEncodedCertificateToSystemStoreA(LPCSTR pszCertStoreName,
80 const BYTE *pbCertEncoded, DWORD cbCertEncoded)
82 HCERTSTORE store;
83 BOOL ret = FALSE;
85 TRACE("(%s, %p, %ld)\n", debugstr_a(pszCertStoreName), pbCertEncoded,
86 cbCertEncoded);
88 store = CertOpenSystemStoreA(0, pszCertStoreName);
89 if (store)
91 ret = CertAddEncodedCertificateToStore(store, X509_ASN_ENCODING,
92 pbCertEncoded, cbCertEncoded, CERT_STORE_ADD_USE_EXISTING, NULL);
93 CertCloseStore(store, 0);
95 return ret;
98 BOOL WINAPI CertAddEncodedCertificateToSystemStoreW(LPCWSTR pszCertStoreName,
99 const BYTE *pbCertEncoded, DWORD cbCertEncoded)
101 HCERTSTORE store;
102 BOOL ret = FALSE;
104 TRACE("(%s, %p, %ld)\n", debugstr_w(pszCertStoreName), pbCertEncoded,
105 cbCertEncoded);
107 store = CertOpenSystemStoreW(0, pszCertStoreName);
108 if (store)
110 ret = CertAddEncodedCertificateToStore(store, X509_ASN_ENCODING,
111 pbCertEncoded, cbCertEncoded, CERT_STORE_ADD_USE_EXISTING, NULL);
112 CertCloseStore(store, 0);
114 return ret;
117 static const context_vtbl_t cert_vtbl;
119 static void Cert_free(context_t *context)
121 cert_t *cert = (cert_t*)context;
123 CryptMemFree(cert->ctx.pbCertEncoded);
124 LocalFree(cert->ctx.pCertInfo);
127 static context_t *Cert_clone(context_t *context, WINECRYPT_CERTSTORE *store, BOOL use_link)
129 cert_t *cert;
131 if(use_link) {
132 cert = (cert_t*)Context_CreateLinkContext(sizeof(CERT_CONTEXT), context, store);
133 if(!cert)
134 return NULL;
135 }else {
136 const cert_t *cloned = (const cert_t*)context;
137 DWORD size = 0;
138 BOOL res;
140 cert = (cert_t*)Context_CreateDataContext(sizeof(CERT_CONTEXT), &cert_vtbl, store);
141 if(!cert)
142 return NULL;
144 Context_CopyProperties(&cert->ctx, &cloned->ctx);
146 cert->ctx.dwCertEncodingType = cloned->ctx.dwCertEncodingType;
147 cert->ctx.pbCertEncoded = CryptMemAlloc(cloned->ctx.cbCertEncoded);
148 memcpy(cert->ctx.pbCertEncoded, cloned->ctx.pbCertEncoded, cloned->ctx.cbCertEncoded);
149 cert->ctx.cbCertEncoded = cloned->ctx.cbCertEncoded;
151 /* FIXME: We don't need to decode the object here, we could just clone cert info. */
152 res = CryptDecodeObjectEx(cert->ctx.dwCertEncodingType, X509_CERT_TO_BE_SIGNED,
153 cert->ctx.pbCertEncoded, cert->ctx.cbCertEncoded, CRYPT_DECODE_ALLOC_FLAG, NULL,
154 &cert->ctx.pCertInfo, &size);
155 if(!res) {
156 CertFreeCertificateContext(&cert->ctx);
157 return NULL;
161 cert->ctx.hCertStore = store;
162 return &cert->base;
165 static const context_vtbl_t cert_vtbl = {
166 Cert_free,
167 Cert_clone
170 static BOOL add_cert_to_store(WINECRYPT_CERTSTORE *store, const CERT_CONTEXT *cert,
171 DWORD add_disposition, BOOL use_link, PCCERT_CONTEXT *ret_context)
173 const CERT_CONTEXT *existing = NULL;
174 BOOL ret = TRUE, inherit_props = FALSE;
175 context_t *new_context = NULL;
177 switch (add_disposition)
179 case CERT_STORE_ADD_ALWAYS:
180 break;
181 case CERT_STORE_ADD_NEW:
182 case CERT_STORE_ADD_REPLACE_EXISTING:
183 case CERT_STORE_ADD_REPLACE_EXISTING_INHERIT_PROPERTIES:
184 case CERT_STORE_ADD_USE_EXISTING:
185 case CERT_STORE_ADD_NEWER:
186 case CERT_STORE_ADD_NEWER_INHERIT_PROPERTIES:
188 BYTE hashToAdd[20];
189 DWORD size = sizeof(hashToAdd);
191 ret = CertGetCertificateContextProperty(cert, CERT_HASH_PROP_ID,
192 hashToAdd, &size);
193 if (ret)
195 CRYPT_HASH_BLOB blob = { sizeof(hashToAdd), hashToAdd };
197 existing = CertFindCertificateInStore(store, cert->dwCertEncodingType, 0,
198 CERT_FIND_SHA1_HASH, &blob, NULL);
200 break;
202 default:
203 FIXME("Unimplemented add disposition %ld\n", add_disposition);
204 SetLastError(E_INVALIDARG);
205 return FALSE;
208 switch (add_disposition)
210 case CERT_STORE_ADD_ALWAYS:
211 break;
212 case CERT_STORE_ADD_NEW:
213 if (existing)
215 TRACE("found matching certificate, not adding\n");
216 SetLastError(CRYPT_E_EXISTS);
217 return FALSE;
219 break;
220 case CERT_STORE_ADD_REPLACE_EXISTING:
221 break;
222 case CERT_STORE_ADD_REPLACE_EXISTING_INHERIT_PROPERTIES:
223 if (use_link)
224 FIXME("CERT_STORE_ADD_REPLACE_EXISTING_INHERIT_PROPERTIES: semi-stub for links\n");
225 if (existing)
226 inherit_props = TRUE;
227 break;
228 case CERT_STORE_ADD_USE_EXISTING:
229 if(use_link)
230 FIXME("CERT_STORE_ADD_USE_EXISTING: semi-stub for links\n");
231 if (existing)
233 Context_CopyProperties(existing, cert);
234 if (ret_context)
235 *ret_context = CertDuplicateCertificateContext(existing);
236 return TRUE;
238 break;
239 case CERT_STORE_ADD_NEWER:
240 if (existing && CompareFileTime(&existing->pCertInfo->NotBefore, &cert->pCertInfo->NotBefore) >= 0)
242 TRACE("existing certificate is newer, not adding\n");
243 SetLastError(CRYPT_E_EXISTS);
244 return FALSE;
246 break;
247 case CERT_STORE_ADD_NEWER_INHERIT_PROPERTIES:
248 if (existing)
250 if (CompareFileTime(&existing->pCertInfo->NotBefore, &cert->pCertInfo->NotBefore) >= 0)
252 TRACE("existing certificate is newer, not adding\n");
253 SetLastError(CRYPT_E_EXISTS);
254 return FALSE;
256 inherit_props = TRUE;
258 break;
261 /* FIXME: We have tests that this works, but what should we really do in this case? */
262 if(!store) {
263 if(ret_context)
264 *ret_context = CertDuplicateCertificateContext(cert);
265 return TRUE;
268 ret = store->vtbl->certs.addContext(store, context_from_ptr(cert), existing ? context_from_ptr(existing) : NULL,
269 (ret_context || inherit_props) ? &new_context : NULL, use_link);
270 if(!ret)
271 return FALSE;
273 if(inherit_props)
274 Context_CopyProperties(context_ptr(new_context), existing);
276 if(ret_context)
277 *ret_context = context_ptr(new_context);
278 else if(new_context)
279 Context_Release(new_context);
281 TRACE("returning %d\n", ret);
282 return ret;
285 BOOL WINAPI CertAddCertificateContextToStore(HCERTSTORE hCertStore, PCCERT_CONTEXT pCertContext,
286 DWORD dwAddDisposition, PCCERT_CONTEXT *ppStoreContext)
288 WINECRYPT_CERTSTORE *store = hCertStore;
290 TRACE("(%p, %p, %08lx, %p)\n", hCertStore, pCertContext, dwAddDisposition, ppStoreContext);
292 return add_cert_to_store(store, pCertContext, dwAddDisposition, FALSE, ppStoreContext);
295 BOOL WINAPI CertAddCertificateLinkToStore(HCERTSTORE hCertStore,
296 PCCERT_CONTEXT pCertContext, DWORD dwAddDisposition,
297 PCCERT_CONTEXT *ppCertContext)
299 static int calls;
300 WINECRYPT_CERTSTORE *store = (WINECRYPT_CERTSTORE*)hCertStore;
302 if (!(calls++))
303 FIXME("(%p, %p, %08lx, %p): semi-stub\n", hCertStore, pCertContext,
304 dwAddDisposition, ppCertContext);
305 if (store->dwMagic != WINE_CRYPTCERTSTORE_MAGIC)
306 return FALSE;
307 if (store->type == StoreTypeCollection)
309 SetLastError(E_INVALIDARG);
310 return FALSE;
312 return add_cert_to_store(hCertStore, pCertContext, dwAddDisposition, TRUE, ppCertContext);
315 PCCERT_CONTEXT WINAPI CertCreateCertificateContext(DWORD dwCertEncodingType,
316 const BYTE *pbCertEncoded, DWORD cbCertEncoded)
318 cert_t *cert = NULL;
319 BYTE *data = NULL;
320 BOOL ret;
321 PCERT_INFO certInfo = NULL;
322 DWORD size = 0;
324 TRACE("(%08lx, %p, %ld)\n", dwCertEncodingType, pbCertEncoded,
325 cbCertEncoded);
327 if ((dwCertEncodingType & CERT_ENCODING_TYPE_MASK) != X509_ASN_ENCODING)
329 SetLastError(E_INVALIDARG);
330 return NULL;
333 ret = CryptDecodeObjectEx(dwCertEncodingType, X509_CERT_TO_BE_SIGNED,
334 pbCertEncoded, cbCertEncoded, CRYPT_DECODE_ALLOC_FLAG, NULL,
335 &certInfo, &size);
336 if (!ret)
337 return NULL;
339 cert = (cert_t*)Context_CreateDataContext(sizeof(CERT_CONTEXT), &cert_vtbl, &empty_store);
340 if (!cert)
341 return NULL;
342 data = CryptMemAlloc(cbCertEncoded);
343 if (!data)
345 Context_Release(&cert->base);
346 return NULL;
349 memcpy(data, pbCertEncoded, cbCertEncoded);
350 cert->ctx.dwCertEncodingType = dwCertEncodingType;
351 cert->ctx.pbCertEncoded = data;
352 cert->ctx.cbCertEncoded = cbCertEncoded;
353 cert->ctx.pCertInfo = certInfo;
354 cert->ctx.hCertStore = &empty_store;
356 return &cert->ctx;
359 PCCERT_CONTEXT WINAPI CertDuplicateCertificateContext(PCCERT_CONTEXT pCertContext)
361 TRACE("(%p)\n", pCertContext);
363 if (!pCertContext)
364 return NULL;
366 Context_AddRef(&cert_from_ptr(pCertContext)->base);
367 return pCertContext;
370 BOOL WINAPI CertFreeCertificateContext(PCCERT_CONTEXT pCertContext)
372 TRACE("(%p)\n", pCertContext);
374 if (pCertContext)
375 Context_Release(&cert_from_ptr(pCertContext)->base);
376 return TRUE;
379 DWORD WINAPI CertEnumCertificateContextProperties(PCCERT_CONTEXT pCertContext,
380 DWORD dwPropId)
382 cert_t *cert = cert_from_ptr(pCertContext);
383 DWORD ret;
385 TRACE("(%p, %ld)\n", pCertContext, dwPropId);
387 if (cert->base.properties)
388 ret = ContextPropertyList_EnumPropIDs(cert->base.properties, dwPropId);
389 else
390 ret = 0;
391 return ret;
394 static BOOL CertContext_GetHashProp(cert_t *cert, DWORD dwPropId,
395 ALG_ID algID, const BYTE *toHash, DWORD toHashLen, void *pvData,
396 DWORD *pcbData)
398 BOOL ret = CryptHashCertificate(0, algID, 0, toHash, toHashLen, pvData,
399 pcbData);
400 if (ret && pvData)
402 CRYPT_DATA_BLOB blob = { *pcbData, pvData };
404 ret = CertContext_SetProperty(cert, dwPropId, 0, &blob);
406 return ret;
409 static BOOL CertContext_CopyParam(void *pvData, DWORD *pcbData, const void *pb,
410 DWORD cb)
412 BOOL ret = TRUE;
414 if (!pvData)
415 *pcbData = cb;
416 else if (*pcbData < cb)
418 SetLastError(ERROR_MORE_DATA);
419 *pcbData = cb;
420 ret = FALSE;
422 else
424 memcpy(pvData, pb, cb);
425 *pcbData = cb;
427 return ret;
430 void CRYPT_ConvertKeyContext(const struct store_CERT_KEY_CONTEXT *src, CERT_KEY_CONTEXT *dst)
432 dst->cbSize = sizeof(*dst);
433 dst->hCryptProv = src->hCryptProv;
434 dst->dwKeySpec = src->dwKeySpec;
438 * Fix offsets in a continuous block of memory of CRYPT_KEY_PROV_INFO with
439 * its associated data.
441 static void fix_KeyProvInfoProperty(CRYPT_KEY_PROV_INFO *info)
443 BYTE *data;
444 DWORD i;
446 data = (BYTE *)(info + 1) + sizeof(CRYPT_KEY_PROV_PARAM) * info->cProvParam;
448 if (info->pwszContainerName)
450 info->pwszContainerName = (LPWSTR)data;
451 data += (lstrlenW(info->pwszContainerName) + 1) * sizeof(WCHAR);
454 if (info->pwszProvName)
456 info->pwszProvName = (LPWSTR)data;
457 data += (lstrlenW(info->pwszProvName) + 1) * sizeof(WCHAR);
460 info->rgProvParam = info->cProvParam ? (CRYPT_KEY_PROV_PARAM *)(info + 1) : NULL;
462 for (i = 0; i < info->cProvParam; i++)
464 info->rgProvParam[i].pbData = info->rgProvParam[i].cbData ? data : NULL;
465 data += info->rgProvParam[i].cbData;
470 * Copy to a continuous block of memory of CRYPT_KEY_PROV_INFO with
471 * its associated data.
473 static void copy_KeyProvInfoProperty(const CRYPT_KEY_PROV_INFO *from, CRYPT_KEY_PROV_INFO *to)
475 BYTE *data;
476 DWORD i;
478 data = (BYTE *)(to + 1) + sizeof(CRYPT_KEY_PROV_PARAM) * from->cProvParam;
480 if (from->pwszContainerName)
482 to->pwszContainerName = (LPWSTR)data;
483 lstrcpyW((LPWSTR)data, from->pwszContainerName);
484 data += (lstrlenW(from->pwszContainerName) + 1) * sizeof(WCHAR);
486 else
487 to->pwszContainerName = NULL;
489 if (from->pwszProvName)
491 to->pwszProvName = (LPWSTR)data;
492 lstrcpyW((LPWSTR)data, from->pwszProvName);
493 data += (lstrlenW(from->pwszProvName) + 1) * sizeof(WCHAR);
495 else
496 to->pwszProvName = NULL;
498 to->dwProvType = from->dwProvType;
499 to->dwFlags = from->dwFlags;
500 to->cProvParam = from->cProvParam;
501 to->rgProvParam = from->cProvParam ? (CRYPT_KEY_PROV_PARAM *)(to + 1) : NULL;
502 to->dwKeySpec = from->dwKeySpec;
504 for (i = 0; i < from->cProvParam; i++)
506 to->rgProvParam[i].dwParam = from->rgProvParam[i].dwParam;
507 to->rgProvParam[i].dwFlags = from->rgProvParam[i].dwFlags;
508 to->rgProvParam[i].cbData = from->rgProvParam[i].cbData;
509 to->rgProvParam[i].pbData = from->rgProvParam[i].cbData ? data : NULL;
510 memcpy(data, from->rgProvParam[i].pbData, from->rgProvParam[i].cbData);
511 data += from->rgProvParam[i].cbData;
515 static BOOL CertContext_GetProperty(cert_t *cert, DWORD dwPropId,
516 void *pvData, DWORD *pcbData)
518 BOOL ret;
519 CRYPT_DATA_BLOB blob;
521 TRACE("(%p, %ld, %p, %p)\n", cert, dwPropId, pvData, pcbData);
523 if (cert->base.properties)
524 ret = ContextPropertyList_FindProperty(cert->base.properties, dwPropId, &blob);
525 else
526 ret = FALSE;
527 if (ret)
529 CERT_KEY_CONTEXT ctx;
530 if (dwPropId == CERT_KEY_CONTEXT_PROP_ID)
532 CRYPT_ConvertKeyContext((const struct store_CERT_KEY_CONTEXT *)blob.pbData, &ctx);
533 blob.pbData = (BYTE *)&ctx;
534 blob.cbData = ctx.cbSize;
536 ret = CertContext_CopyParam(pvData, pcbData, blob.pbData, blob.cbData);
538 else
540 /* Implicit properties */
541 switch (dwPropId)
543 case CERT_SHA1_HASH_PROP_ID:
544 ret = CertContext_GetHashProp(cert, dwPropId, CALG_SHA1,
545 cert->ctx.pbCertEncoded, cert->ctx.cbCertEncoded, pvData,
546 pcbData);
547 break;
548 case CERT_MD5_HASH_PROP_ID:
549 ret = CertContext_GetHashProp(cert, dwPropId, CALG_MD5,
550 cert->ctx.pbCertEncoded, cert->ctx.cbCertEncoded, pvData,
551 pcbData);
552 break;
553 case CERT_SUBJECT_NAME_MD5_HASH_PROP_ID:
554 ret = CertContext_GetHashProp(cert, dwPropId, CALG_MD5,
555 cert->ctx.pCertInfo->Subject.pbData,
556 cert->ctx.pCertInfo->Subject.cbData,
557 pvData, pcbData);
558 break;
559 case CERT_SUBJECT_PUBLIC_KEY_MD5_HASH_PROP_ID:
560 ret = CertContext_GetHashProp(cert, dwPropId, CALG_MD5,
561 cert->ctx.pCertInfo->SubjectPublicKeyInfo.PublicKey.pbData,
562 cert->ctx.pCertInfo->SubjectPublicKeyInfo.PublicKey.cbData,
563 pvData, pcbData);
564 break;
565 case CERT_ISSUER_SERIAL_NUMBER_MD5_HASH_PROP_ID:
566 ret = CertContext_GetHashProp(cert, dwPropId, CALG_MD5,
567 cert->ctx.pCertInfo->SerialNumber.pbData,
568 cert->ctx.pCertInfo->SerialNumber.cbData,
569 pvData, pcbData);
570 break;
571 case CERT_SIGNATURE_HASH_PROP_ID:
572 ret = CryptHashToBeSigned(0, cert->ctx.dwCertEncodingType,
573 cert->ctx.pbCertEncoded, cert->ctx.cbCertEncoded, pvData,
574 pcbData);
575 if (ret && pvData)
577 CRYPT_DATA_BLOB blob = { *pcbData, pvData };
579 ret = CertContext_SetProperty(cert, dwPropId, 0, &blob);
581 break;
582 case CERT_KEY_IDENTIFIER_PROP_ID:
584 PCERT_EXTENSION ext = CertFindExtension(
585 szOID_SUBJECT_KEY_IDENTIFIER, cert->ctx.pCertInfo->cExtension,
586 cert->ctx.pCertInfo->rgExtension);
588 if (ext)
590 CRYPT_DATA_BLOB value;
591 DWORD size = sizeof(value);
593 ret = CryptDecodeObjectEx(X509_ASN_ENCODING,
594 szOID_SUBJECT_KEY_IDENTIFIER, ext->Value.pbData,
595 ext->Value.cbData, CRYPT_DECODE_NOCOPY_FLAG, NULL, &value,
596 &size);
597 if (ret)
599 ret = CertContext_CopyParam(pvData, pcbData, value.pbData,
600 value.cbData);
601 CertContext_SetProperty(cert, dwPropId, 0, &value);
604 else
605 SetLastError(ERROR_INVALID_DATA);
606 break;
608 default:
609 SetLastError(CRYPT_E_NOT_FOUND);
612 TRACE("returning %d\n", ret);
613 return ret;
616 BOOL WINAPI CertGetCertificateContextProperty(PCCERT_CONTEXT pCertContext,
617 DWORD dwPropId, void *pvData, DWORD *pcbData)
619 cert_t *cert = cert_from_ptr(pCertContext);
620 BOOL ret;
622 TRACE("(%p, %ld, %p, %p)\n", pCertContext, dwPropId, pvData, pcbData);
624 switch (dwPropId)
626 case 0:
627 case CERT_CERT_PROP_ID:
628 case CERT_CRL_PROP_ID:
629 case CERT_CTL_PROP_ID:
630 SetLastError(E_INVALIDARG);
631 ret = FALSE;
632 break;
633 case CERT_ACCESS_STATE_PROP_ID:
634 ret = CertGetStoreProperty(cert->ctx.hCertStore, dwPropId, pvData, pcbData);
635 break;
636 case CERT_KEY_PROV_HANDLE_PROP_ID:
638 CERT_KEY_CONTEXT keyContext;
639 DWORD size = sizeof(keyContext);
641 ret = CertContext_GetProperty(cert,
642 CERT_KEY_CONTEXT_PROP_ID, &keyContext, &size);
643 if (ret)
644 ret = CertContext_CopyParam(pvData, pcbData, &keyContext.hCryptProv,
645 sizeof(keyContext.hCryptProv));
646 break;
648 case CERT_KEY_PROV_INFO_PROP_ID:
649 ret = CertContext_GetProperty(cert, dwPropId, pvData, pcbData);
650 if (ret && pvData)
651 fix_KeyProvInfoProperty(pvData);
652 break;
653 default:
654 ret = CertContext_GetProperty(cert, dwPropId, pvData,
655 pcbData);
658 TRACE("returning %d\n", ret);
659 return ret;
663 * Create a continuous block of memory for CRYPT_KEY_PROV_INFO with
664 * its associated data, and add it to the certificate properties.
666 static BOOL CertContext_SetKeyProvInfoProperty(CONTEXT_PROPERTY_LIST *properties, const CRYPT_KEY_PROV_INFO *info)
668 CRYPT_KEY_PROV_INFO *prop;
669 DWORD size = sizeof(CRYPT_KEY_PROV_INFO), i;
670 BOOL ret;
672 if (info->pwszContainerName)
673 size += (lstrlenW(info->pwszContainerName) + 1) * sizeof(WCHAR);
674 if (info->pwszProvName)
675 size += (lstrlenW(info->pwszProvName) + 1) * sizeof(WCHAR);
677 for (i = 0; i < info->cProvParam; i++)
678 size += sizeof(CRYPT_KEY_PROV_PARAM) + info->rgProvParam[i].cbData;
680 prop = CryptMemAlloc(size);
681 if (!prop)
683 SetLastError(ERROR_OUTOFMEMORY);
684 return FALSE;
687 copy_KeyProvInfoProperty(info, prop);
689 ret = ContextPropertyList_SetProperty(properties, CERT_KEY_PROV_INFO_PROP_ID, (const BYTE *)prop, size);
690 CryptMemFree(prop);
692 return ret;
695 static BOOL CertContext_SetKeyContextProperty(CONTEXT_PROPERTY_LIST *properties,
696 const CERT_KEY_CONTEXT *keyContext)
698 struct store_CERT_KEY_CONTEXT ctx;
700 ctx.cbSize = sizeof(ctx);
701 ctx.hCryptProv = keyContext->hCryptProv;
702 ctx.dwKeySpec = keyContext->dwKeySpec;
704 return ContextPropertyList_SetProperty(properties, CERT_KEY_CONTEXT_PROP_ID,
705 (const BYTE *)&ctx, ctx.cbSize);
708 static BOOL CertContext_SetProperty(cert_t *cert, DWORD dwPropId,
709 DWORD dwFlags, const void *pvData)
711 BOOL ret;
713 TRACE("(%p, %ld, %08lx, %p)\n", cert, dwPropId, dwFlags, pvData);
715 if (!cert->base.properties)
716 ret = FALSE;
717 else if (dwPropId >= CERT_FIRST_USER_PROP_ID && dwPropId <= CERT_LAST_USER_PROP_ID)
719 if (pvData)
721 const CRYPT_DATA_BLOB *blob = pvData;
722 ret = ContextPropertyList_SetProperty(cert->base.properties, dwPropId, blob->pbData, blob->cbData);
724 else
726 ContextPropertyList_RemoveProperty(cert->base.properties, dwPropId);
727 ret = TRUE;
730 else
732 switch (dwPropId)
734 case CERT_AUTO_ENROLL_PROP_ID:
735 case CERT_CTL_USAGE_PROP_ID: /* same as CERT_ENHKEY_USAGE_PROP_ID */
736 case CERT_DESCRIPTION_PROP_ID:
737 case CERT_FRIENDLY_NAME_PROP_ID:
738 case CERT_HASH_PROP_ID:
739 case CERT_KEY_IDENTIFIER_PROP_ID:
740 case CERT_MD5_HASH_PROP_ID:
741 case CERT_NEXT_UPDATE_LOCATION_PROP_ID:
742 case CERT_PUBKEY_ALG_PARA_PROP_ID:
743 case CERT_PVK_FILE_PROP_ID:
744 case CERT_SIGNATURE_HASH_PROP_ID:
745 case CERT_ISSUER_PUBLIC_KEY_MD5_HASH_PROP_ID:
746 case CERT_SUBJECT_NAME_MD5_HASH_PROP_ID:
747 case CERT_EXTENDED_ERROR_INFO_PROP_ID:
748 case CERT_SUBJECT_PUBLIC_KEY_MD5_HASH_PROP_ID:
749 case CERT_ENROLLMENT_PROP_ID:
750 case CERT_CROSS_CERT_DIST_POINTS_PROP_ID:
751 case CERT_OCSP_RESPONSE_PROP_ID:
752 case CERT_RENEWAL_PROP_ID:
754 if (pvData)
756 const CRYPT_DATA_BLOB *blob = pvData;
758 ret = ContextPropertyList_SetProperty(cert->base.properties, dwPropId,
759 blob->pbData, blob->cbData);
761 else
763 ContextPropertyList_RemoveProperty(cert->base.properties, dwPropId);
764 ret = TRUE;
766 break;
768 case CERT_DATE_STAMP_PROP_ID:
769 if (pvData)
770 ret = ContextPropertyList_SetProperty(cert->base.properties, dwPropId,
771 pvData, sizeof(FILETIME));
772 else
774 ContextPropertyList_RemoveProperty(cert->base.properties, dwPropId);
775 ret = TRUE;
777 break;
778 case CERT_KEY_CONTEXT_PROP_ID:
779 if (pvData)
781 const CERT_KEY_CONTEXT *keyContext = pvData;
783 if (keyContext->cbSize != sizeof(CERT_KEY_CONTEXT))
785 SetLastError(E_INVALIDARG);
786 ret = FALSE;
788 else
789 ret = CertContext_SetKeyContextProperty(cert->base.properties, pvData);
791 else
793 ContextPropertyList_RemoveProperty(cert->base.properties, dwPropId);
794 ret = TRUE;
796 break;
797 case CERT_KEY_PROV_INFO_PROP_ID:
798 if (pvData)
799 ret = CertContext_SetKeyProvInfoProperty(cert->base.properties, pvData);
800 else
802 ContextPropertyList_RemoveProperty(cert->base.properties, dwPropId);
803 ret = TRUE;
805 break;
806 case CERT_KEY_PROV_HANDLE_PROP_ID:
808 CERT_KEY_CONTEXT keyContext;
809 DWORD size = sizeof(keyContext);
811 ret = CertContext_GetProperty(cert, CERT_KEY_CONTEXT_PROP_ID,
812 &keyContext, &size);
813 if (ret)
815 if (!(dwFlags & CERT_STORE_NO_CRYPT_RELEASE_FLAG))
816 CryptReleaseContext(keyContext.hCryptProv, 0);
818 keyContext.cbSize = sizeof(keyContext);
819 if (pvData)
820 keyContext.hCryptProv = *(const HCRYPTPROV *)pvData;
821 else
823 keyContext.hCryptProv = 0;
824 keyContext.dwKeySpec = AT_SIGNATURE;
826 ret = CertContext_SetProperty(cert, CERT_KEY_CONTEXT_PROP_ID,
827 0, &keyContext);
828 break;
830 default:
831 FIXME("%ld: stub\n", dwPropId);
832 ret = FALSE;
835 TRACE("returning %d\n", ret);
836 return ret;
839 BOOL WINAPI CertSetCertificateContextProperty(PCCERT_CONTEXT pCertContext,
840 DWORD dwPropId, DWORD dwFlags, const void *pvData)
842 BOOL ret;
844 TRACE("(%p, %ld, %08lx, %p)\n", pCertContext, dwPropId, dwFlags, pvData);
846 /* Handle special cases for "read-only"/invalid prop IDs. Windows just
847 * crashes on most of these, I'll be safer.
849 switch (dwPropId)
851 case 0:
852 case CERT_ACCESS_STATE_PROP_ID:
853 case CERT_CERT_PROP_ID:
854 case CERT_CRL_PROP_ID:
855 case CERT_CTL_PROP_ID:
856 SetLastError(E_INVALIDARG);
857 return FALSE;
859 ret = CertContext_SetProperty(cert_from_ptr(pCertContext), dwPropId, dwFlags,
860 pvData);
861 TRACE("returning %d\n", ret);
862 return ret;
865 /* Acquires the private key using the key provider info, retrieving info from
866 * the certificate if info is NULL. The acquired provider is returned in
867 * *phCryptProv, and the key spec for the provider is returned in *pdwKeySpec.
869 static BOOL CRYPT_AcquirePrivateKeyFromProvInfo(PCCERT_CONTEXT pCert, DWORD dwFlags,
870 PCRYPT_KEY_PROV_INFO info, HCRYPTPROV *phCryptProv, DWORD *pdwKeySpec)
872 DWORD size = 0;
873 BOOL allocated = FALSE, ret = TRUE;
875 if (!info)
877 ret = CertGetCertificateContextProperty(pCert,
878 CERT_KEY_PROV_INFO_PROP_ID, 0, &size);
879 if (ret)
881 info = CryptMemAlloc(size);
882 if (info)
884 ret = CertGetCertificateContextProperty(pCert,
885 CERT_KEY_PROV_INFO_PROP_ID, info, &size);
886 allocated = TRUE;
888 else
890 SetLastError(ERROR_OUTOFMEMORY);
891 ret = FALSE;
894 else
895 SetLastError(CRYPT_E_NO_KEY_PROPERTY);
897 if (ret)
899 ret = CryptAcquireContextW(phCryptProv, info->pwszContainerName,
900 info->pwszProvName, info->dwProvType, (dwFlags & CRYPT_ACQUIRE_SILENT_FLAG) ? CRYPT_SILENT : 0);
901 if (ret)
903 DWORD i;
905 for (i = 0; i < info->cProvParam; i++)
907 CryptSetProvParam(*phCryptProv,
908 info->rgProvParam[i].dwParam, info->rgProvParam[i].pbData,
909 info->rgProvParam[i].dwFlags);
911 *pdwKeySpec = info->dwKeySpec;
913 else
914 SetLastError(CRYPT_E_NO_KEY_PROPERTY);
916 if (allocated)
917 CryptMemFree(info);
918 return ret;
921 BOOL WINAPI CryptAcquireCertificatePrivateKey(PCCERT_CONTEXT pCert,
922 DWORD dwFlags, void *pvReserved, HCRYPTPROV_OR_NCRYPT_KEY_HANDLE *phCryptProv,
923 DWORD *pdwKeySpec, BOOL *pfCallerFreeProv)
925 BOOL ret = FALSE, cache = FALSE;
926 PCRYPT_KEY_PROV_INFO info = NULL;
927 CERT_KEY_CONTEXT keyContext;
928 DWORD size;
929 PCCERT_CONTEXT cert_in_store = NULL;
931 TRACE("(%p, %08lx, %p, %p, %p, %p)\n", pCert, dwFlags, pvReserved,
932 phCryptProv, pdwKeySpec, pfCallerFreeProv);
934 if (dwFlags & CRYPT_ACQUIRE_USE_PROV_INFO_FLAG)
936 DWORD size = 0;
938 ret = CertGetCertificateContextProperty(pCert,
939 CERT_KEY_PROV_INFO_PROP_ID, 0, &size);
941 if (!ret)
943 HCERTSTORE hstore;
945 hstore = CertOpenStore(CERT_STORE_PROV_SYSTEM_W, 0, 0,
946 CERT_SYSTEM_STORE_CURRENT_USER, L"My");
947 if (hstore)
949 cert_in_store = CertFindCertificateInStore(hstore, pCert->dwCertEncodingType, 0,
950 CERT_FIND_EXISTING, pCert, NULL);
951 if (cert_in_store)
953 ret = CertGetCertificateContextProperty(cert_in_store, CERT_KEY_PROV_INFO_PROP_ID, 0, &size);
954 if (ret)
955 pCert = cert_in_store;
956 else
958 CertFreeCertificateContext(cert_in_store);
959 cert_in_store = NULL;
963 CertCloseStore(hstore, 0);
967 if (ret)
969 info = CryptMemAlloc(size);
970 ret = CertGetCertificateContextProperty(pCert,
971 CERT_KEY_PROV_INFO_PROP_ID, info, &size);
972 if (ret)
973 cache = info->dwFlags & CERT_SET_KEY_CONTEXT_PROP_ID;
976 else if (dwFlags & CRYPT_ACQUIRE_CACHE_FLAG)
977 cache = TRUE;
978 *phCryptProv = 0;
979 if (cache)
981 size = sizeof(keyContext);
982 ret = CertGetCertificateContextProperty(pCert, CERT_KEY_CONTEXT_PROP_ID,
983 &keyContext, &size);
984 if (ret)
986 *phCryptProv = keyContext.hCryptProv;
987 if (pdwKeySpec)
988 *pdwKeySpec = keyContext.dwKeySpec;
989 if (pfCallerFreeProv)
990 *pfCallerFreeProv = FALSE;
993 if (!*phCryptProv)
995 ret = CRYPT_AcquirePrivateKeyFromProvInfo(pCert, dwFlags, info,
996 &keyContext.hCryptProv, &keyContext.dwKeySpec);
997 if (ret)
999 *phCryptProv = keyContext.hCryptProv;
1000 if (pdwKeySpec)
1001 *pdwKeySpec = keyContext.dwKeySpec;
1002 if (cache)
1004 keyContext.cbSize = sizeof(keyContext);
1005 if (CertSetCertificateContextProperty(pCert,
1006 CERT_KEY_CONTEXT_PROP_ID, 0, &keyContext))
1008 if (pfCallerFreeProv)
1009 *pfCallerFreeProv = FALSE;
1012 else
1014 if (pfCallerFreeProv)
1015 *pfCallerFreeProv = TRUE;
1019 CryptMemFree(info);
1020 if (cert_in_store)
1021 CertFreeCertificateContext(cert_in_store);
1022 if (ret) SetLastError(0);
1023 return ret;
1026 static BOOL key_prov_info_matches_cert(PCCERT_CONTEXT pCert,
1027 const CRYPT_KEY_PROV_INFO *keyProvInfo)
1029 HCRYPTPROV csp;
1030 BOOL matches = FALSE;
1032 if (CryptAcquireContextW(&csp, keyProvInfo->pwszContainerName,
1033 keyProvInfo->pwszProvName, keyProvInfo->dwProvType, keyProvInfo->dwFlags))
1035 DWORD size;
1037 /* Need to sign something to verify the sig. What to sign? Why not
1038 * the certificate itself?
1040 if (CryptSignAndEncodeCertificate(csp, AT_SIGNATURE,
1041 pCert->dwCertEncodingType, X509_CERT_TO_BE_SIGNED, pCert->pCertInfo,
1042 &pCert->pCertInfo->SignatureAlgorithm, NULL, NULL, &size))
1044 BYTE *certEncoded = CryptMemAlloc(size);
1046 if (certEncoded)
1048 if (CryptSignAndEncodeCertificate(csp, AT_SIGNATURE,
1049 pCert->dwCertEncodingType, X509_CERT_TO_BE_SIGNED,
1050 pCert->pCertInfo, &pCert->pCertInfo->SignatureAlgorithm,
1051 NULL, certEncoded, &size))
1053 if (size == pCert->cbCertEncoded &&
1054 !memcmp(certEncoded, pCert->pbCertEncoded, size))
1055 matches = TRUE;
1057 CryptMemFree(certEncoded);
1060 CryptReleaseContext(csp, 0);
1062 return matches;
1065 static BOOL container_matches_cert(PCCERT_CONTEXT pCert, LPCSTR container,
1066 CRYPT_KEY_PROV_INFO *keyProvInfo)
1068 CRYPT_KEY_PROV_INFO copy;
1069 WCHAR containerW[MAX_PATH];
1070 BOOL matches;
1072 MultiByteToWideChar(CP_ACP, 0, container, -1, containerW, ARRAY_SIZE(containerW));
1073 /* We make a copy of the CRYPT_KEY_PROV_INFO because the caller expects
1074 * keyProvInfo->pwszContainerName to be NULL or a heap-allocated container
1075 * name.
1077 copy = *keyProvInfo;
1078 copy.pwszContainerName = containerW;
1079 matches = key_prov_info_matches_cert(pCert, &copy);
1080 if (matches)
1082 keyProvInfo->pwszContainerName =
1083 CryptMemAlloc((lstrlenW(containerW) + 1) * sizeof(WCHAR));
1084 if (keyProvInfo->pwszContainerName)
1086 lstrcpyW(keyProvInfo->pwszContainerName, containerW);
1087 keyProvInfo->dwKeySpec = AT_SIGNATURE;
1089 else
1090 matches = FALSE;
1092 return matches;
1095 /* Searches the provider named keyProvInfo.pwszProvName for a container whose
1096 * private key matches pCert's public key. Upon success, updates keyProvInfo
1097 * with the matching container's info (free keyProvInfo.pwszContainerName upon
1098 * success.)
1099 * Returns TRUE if found, FALSE if not.
1101 static BOOL find_key_prov_info_in_provider(PCCERT_CONTEXT pCert,
1102 CRYPT_KEY_PROV_INFO *keyProvInfo)
1104 HCRYPTPROV defProvider;
1105 BOOL ret, found = FALSE;
1106 char containerA[MAX_PATH];
1108 assert(keyProvInfo->pwszContainerName == NULL);
1109 if ((ret = CryptAcquireContextW(&defProvider, NULL,
1110 keyProvInfo->pwszProvName, keyProvInfo->dwProvType,
1111 keyProvInfo->dwFlags | CRYPT_VERIFYCONTEXT)))
1113 DWORD enumFlags = keyProvInfo->dwFlags | CRYPT_FIRST;
1115 while (ret && !found)
1117 DWORD size = sizeof(containerA);
1119 ret = CryptGetProvParam(defProvider, PP_ENUMCONTAINERS,
1120 (BYTE *)containerA, &size, enumFlags);
1121 if (ret)
1122 found = container_matches_cert(pCert, containerA, keyProvInfo);
1123 if (enumFlags & CRYPT_FIRST)
1125 enumFlags &= ~CRYPT_FIRST;
1126 enumFlags |= CRYPT_NEXT;
1129 CryptReleaseContext(defProvider, 0);
1131 return found;
1134 static BOOL find_matching_provider(PCCERT_CONTEXT pCert, DWORD dwFlags)
1136 BOOL found = FALSE, ret = TRUE;
1137 DWORD index = 0, cbProvName = 0;
1138 CRYPT_KEY_PROV_INFO keyProvInfo;
1140 TRACE("(%p, %08lx)\n", pCert, dwFlags);
1142 memset(&keyProvInfo, 0, sizeof(keyProvInfo));
1143 while (ret && !found)
1145 DWORD size = 0;
1147 ret = CryptEnumProvidersW(index, NULL, 0, &keyProvInfo.dwProvType,
1148 NULL, &size);
1149 if (ret)
1151 if (size <= cbProvName)
1152 ret = CryptEnumProvidersW(index, NULL, 0,
1153 &keyProvInfo.dwProvType, keyProvInfo.pwszProvName, &size);
1154 else
1156 CryptMemFree(keyProvInfo.pwszProvName);
1157 keyProvInfo.pwszProvName = CryptMemAlloc(size);
1158 if (keyProvInfo.pwszProvName)
1160 cbProvName = size;
1161 ret = CryptEnumProvidersW(index, NULL, 0,
1162 &keyProvInfo.dwProvType, keyProvInfo.pwszProvName, &size);
1163 if (ret)
1165 if (dwFlags & CRYPT_FIND_SILENT_KEYSET_FLAG)
1166 keyProvInfo.dwFlags |= CRYPT_SILENT;
1167 if (dwFlags & CRYPT_FIND_USER_KEYSET_FLAG ||
1168 !(dwFlags & (CRYPT_FIND_USER_KEYSET_FLAG |
1169 CRYPT_FIND_MACHINE_KEYSET_FLAG)))
1171 keyProvInfo.dwFlags |= CRYPT_USER_KEYSET;
1172 found = find_key_prov_info_in_provider(pCert,
1173 &keyProvInfo);
1175 if (!found)
1177 if (dwFlags & CRYPT_FIND_MACHINE_KEYSET_FLAG ||
1178 !(dwFlags & (CRYPT_FIND_USER_KEYSET_FLAG |
1179 CRYPT_FIND_MACHINE_KEYSET_FLAG)))
1181 keyProvInfo.dwFlags &= ~CRYPT_USER_KEYSET;
1182 keyProvInfo.dwFlags |= CRYPT_MACHINE_KEYSET;
1183 found = find_key_prov_info_in_provider(pCert,
1184 &keyProvInfo);
1189 else
1190 ret = FALSE;
1192 index++;
1195 if (found)
1196 CertSetCertificateContextProperty(pCert, CERT_KEY_PROV_INFO_PROP_ID,
1197 0, &keyProvInfo);
1198 CryptMemFree(keyProvInfo.pwszProvName);
1199 CryptMemFree(keyProvInfo.pwszContainerName);
1200 return found;
1203 static BOOL cert_prov_info_matches_cert(PCCERT_CONTEXT pCert)
1205 BOOL matches = FALSE;
1206 DWORD size;
1208 if (CertGetCertificateContextProperty(pCert, CERT_KEY_PROV_INFO_PROP_ID,
1209 NULL, &size))
1211 CRYPT_KEY_PROV_INFO *keyProvInfo = CryptMemAlloc(size);
1213 if (keyProvInfo)
1215 if (CertGetCertificateContextProperty(pCert,
1216 CERT_KEY_PROV_INFO_PROP_ID, keyProvInfo, &size))
1217 matches = key_prov_info_matches_cert(pCert, keyProvInfo);
1218 CryptMemFree(keyProvInfo);
1221 return matches;
1224 BOOL WINAPI CryptFindCertificateKeyProvInfo(PCCERT_CONTEXT pCert,
1225 DWORD dwFlags, void *pvReserved)
1227 BOOL matches;
1229 TRACE("(%p, %08lx, %p)\n", pCert, dwFlags, pvReserved);
1231 matches = cert_prov_info_matches_cert(pCert);
1232 if (!matches)
1233 matches = find_matching_provider(pCert, dwFlags);
1234 return matches;
1237 BOOL WINAPI CertCompareCertificate(DWORD dwCertEncodingType,
1238 PCERT_INFO pCertId1, PCERT_INFO pCertId2)
1240 BOOL ret;
1242 TRACE("(%08lx, %p, %p)\n", dwCertEncodingType, pCertId1, pCertId2);
1244 ret = CertCompareCertificateName(dwCertEncodingType, &pCertId1->Issuer,
1245 &pCertId2->Issuer) && CertCompareIntegerBlob(&pCertId1->SerialNumber,
1246 &pCertId2->SerialNumber);
1247 TRACE("returning %d\n", ret);
1248 return ret;
1251 BOOL WINAPI CertCompareCertificateName(DWORD dwCertEncodingType,
1252 PCERT_NAME_BLOB pCertName1, PCERT_NAME_BLOB pCertName2)
1254 BOOL ret;
1256 TRACE("(%08lx, %p, %p)\n", dwCertEncodingType, pCertName1, pCertName2);
1258 if (pCertName1->cbData == pCertName2->cbData)
1260 if (pCertName1->cbData)
1261 ret = !memcmp(pCertName1->pbData, pCertName2->pbData,
1262 pCertName1->cbData);
1263 else
1264 ret = TRUE;
1266 else
1267 ret = FALSE;
1268 TRACE("returning %d\n", ret);
1269 return ret;
1272 /* Returns the number of significant bytes in pInt, where a byte is
1273 * insignificant if it's a leading 0 for positive numbers or a leading 0xff
1274 * for negative numbers. pInt is assumed to be little-endian.
1276 static DWORD CRYPT_significantBytes(const CRYPT_INTEGER_BLOB *pInt)
1278 DWORD ret = pInt->cbData;
1280 while (ret > 1)
1282 if (pInt->pbData[ret - 2] <= 0x7f && pInt->pbData[ret - 1] == 0)
1283 ret--;
1284 else if (pInt->pbData[ret - 2] >= 0x80 && pInt->pbData[ret - 1] == 0xff)
1285 ret--;
1286 else
1287 break;
1289 return ret;
1292 BOOL WINAPI CertCompareIntegerBlob(PCRYPT_INTEGER_BLOB pInt1,
1293 PCRYPT_INTEGER_BLOB pInt2)
1295 BOOL ret;
1296 DWORD cb1, cb2;
1298 TRACE("(%p, %p)\n", pInt1, pInt2);
1300 cb1 = CRYPT_significantBytes(pInt1);
1301 cb2 = CRYPT_significantBytes(pInt2);
1302 if (cb1 == cb2)
1304 if (cb1)
1305 ret = !memcmp(pInt1->pbData, pInt2->pbData, cb1);
1306 else
1307 ret = TRUE;
1309 else
1310 ret = FALSE;
1311 TRACE("returning %d\n", ret);
1312 return ret;
1315 BOOL WINAPI CertComparePublicKeyInfo(DWORD dwCertEncodingType,
1316 PCERT_PUBLIC_KEY_INFO pPublicKey1, PCERT_PUBLIC_KEY_INFO pPublicKey2)
1318 BOOL ret;
1320 TRACE("(%08lx, %p, %p)\n", dwCertEncodingType, pPublicKey1, pPublicKey2);
1322 /* RSA public key data should start with ASN_SEQUENCE,
1323 * otherwise it's not a RSA_CSP_PUBLICKEYBLOB.
1325 if (!pPublicKey1->PublicKey.cbData || pPublicKey1->PublicKey.pbData[0] != ASN_SEQUENCE)
1326 dwCertEncodingType = 0;
1328 switch (GET_CERT_ENCODING_TYPE(dwCertEncodingType))
1330 case 0: /* Seems to mean "raw binary bits" */
1331 if (pPublicKey1->PublicKey.cbData == pPublicKey2->PublicKey.cbData &&
1332 pPublicKey1->PublicKey.cUnusedBits == pPublicKey2->PublicKey.cUnusedBits)
1334 if (pPublicKey2->PublicKey.cbData)
1335 ret = !memcmp(pPublicKey1->PublicKey.pbData,
1336 pPublicKey2->PublicKey.pbData, pPublicKey1->PublicKey.cbData);
1337 else
1338 ret = TRUE;
1340 else
1341 ret = FALSE;
1342 break;
1343 default:
1344 WARN("Unknown encoding type %08lx\n", dwCertEncodingType);
1345 /* FALLTHROUGH */
1346 case X509_ASN_ENCODING:
1348 BLOBHEADER *pblob1, *pblob2;
1349 DWORD length;
1350 ret = FALSE;
1351 if (CryptDecodeObject(dwCertEncodingType, RSA_CSP_PUBLICKEYBLOB,
1352 pPublicKey1->PublicKey.pbData, pPublicKey1->PublicKey.cbData,
1353 CRYPT_DECODE_ALLOC_FLAG, &pblob1, &length))
1355 if (CryptDecodeObject(dwCertEncodingType, RSA_CSP_PUBLICKEYBLOB,
1356 pPublicKey2->PublicKey.pbData, pPublicKey2->PublicKey.cbData,
1357 CRYPT_DECODE_ALLOC_FLAG, &pblob2, &length))
1359 /* The RSAPUBKEY structure directly follows the BLOBHEADER */
1360 RSAPUBKEY *pk1 = (LPVOID)(pblob1 + 1),
1361 *pk2 = (LPVOID)(pblob2 + 1);
1362 ret = (pk1->bitlen == pk2->bitlen) && (pk1->pubexp == pk2->pubexp)
1363 && !memcmp(pk1 + 1, pk2 + 1, pk1->bitlen/8);
1365 LocalFree(pblob2);
1367 LocalFree(pblob1);
1370 break;
1373 return ret;
1376 DWORD WINAPI CertGetPublicKeyLength(DWORD dwCertEncodingType,
1377 PCERT_PUBLIC_KEY_INFO pPublicKey)
1379 DWORD len = 0;
1381 TRACE("(%08lx, %p)\n", dwCertEncodingType, pPublicKey);
1383 if (GET_CERT_ENCODING_TYPE(dwCertEncodingType) != X509_ASN_ENCODING)
1385 SetLastError(ERROR_FILE_NOT_FOUND);
1386 return 0;
1388 if (pPublicKey->Algorithm.pszObjId &&
1389 !strcmp(pPublicKey->Algorithm.pszObjId, szOID_RSA_DH))
1391 FIXME("unimplemented for DH public keys\n");
1392 SetLastError(CRYPT_E_ASN1_BADTAG);
1394 else
1396 PCCRYPT_OID_INFO info;
1397 DWORD size;
1398 PBYTE buf;
1399 BOOL ret;
1401 info = CryptFindOIDInfo(CRYPT_OID_INFO_OID_KEY, pPublicKey->Algorithm.pszObjId, 0);
1402 if (info)
1404 HCRYPTKEY key;
1406 TRACE("public key algid %#x (%s)\n", info->u.Algid, debugstr_a(pPublicKey->Algorithm.pszObjId));
1408 ret = CryptImportPublicKeyInfo(I_CryptGetDefaultCryptProv(info->u.Algid), dwCertEncodingType, pPublicKey, &key);
1409 if (ret)
1411 size = sizeof(len);
1412 ret = CryptGetKeyParam(key, KP_KEYLEN, (BYTE *)&len, &size, 0);
1413 CryptDestroyKey(key);
1414 return len;
1416 /* fallback to RSA */
1419 ret = CryptDecodeObjectEx(dwCertEncodingType,
1420 RSA_CSP_PUBLICKEYBLOB, pPublicKey->PublicKey.pbData,
1421 pPublicKey->PublicKey.cbData, CRYPT_DECODE_ALLOC_FLAG, NULL, &buf,
1422 &size);
1424 if (ret)
1426 RSAPUBKEY *rsaPubKey = (RSAPUBKEY *)(buf + sizeof(BLOBHEADER));
1428 len = rsaPubKey->bitlen;
1429 LocalFree(buf);
1432 return len;
1435 typedef BOOL (*CertCompareFunc)(PCCERT_CONTEXT pCertContext, DWORD dwType,
1436 DWORD dwFlags, const void *pvPara);
1438 static BOOL compare_cert_by_md5_hash(PCCERT_CONTEXT pCertContext, DWORD dwType,
1439 DWORD dwFlags, const void *pvPara)
1441 BOOL ret;
1442 BYTE hash[16];
1443 DWORD size = sizeof(hash);
1445 ret = CertGetCertificateContextProperty(pCertContext,
1446 CERT_MD5_HASH_PROP_ID, hash, &size);
1447 if (ret)
1449 const CRYPT_HASH_BLOB *pHash = pvPara;
1451 if (size == pHash->cbData)
1452 ret = !memcmp(pHash->pbData, hash, size);
1453 else
1454 ret = FALSE;
1456 return ret;
1459 static BOOL compare_cert_by_sha1_hash(PCCERT_CONTEXT pCertContext, DWORD dwType,
1460 DWORD dwFlags, const void *pvPara)
1462 BOOL ret;
1463 BYTE hash[20];
1464 DWORD size = sizeof(hash);
1466 ret = CertGetCertificateContextProperty(pCertContext,
1467 CERT_SHA1_HASH_PROP_ID, hash, &size);
1468 if (ret)
1470 const CRYPT_HASH_BLOB *pHash = pvPara;
1472 if (size == pHash->cbData)
1473 ret = !memcmp(pHash->pbData, hash, size);
1474 else
1475 ret = FALSE;
1477 return ret;
1480 static BOOL compare_cert_by_name(PCCERT_CONTEXT pCertContext, DWORD dwType,
1481 DWORD dwFlags, const void *pvPara)
1483 CERT_NAME_BLOB *blob = (CERT_NAME_BLOB *)pvPara, *toCompare;
1484 BOOL ret;
1486 if (dwType & CERT_INFO_SUBJECT_FLAG)
1487 toCompare = &pCertContext->pCertInfo->Subject;
1488 else
1489 toCompare = &pCertContext->pCertInfo->Issuer;
1490 ret = CertCompareCertificateName(pCertContext->dwCertEncodingType,
1491 toCompare, blob);
1492 return ret;
1495 static BOOL compare_cert_by_public_key(PCCERT_CONTEXT pCertContext,
1496 DWORD dwType, DWORD dwFlags, const void *pvPara)
1498 CERT_PUBLIC_KEY_INFO *publicKey = (CERT_PUBLIC_KEY_INFO *)pvPara;
1499 BOOL ret;
1501 ret = CertComparePublicKeyInfo(pCertContext->dwCertEncodingType,
1502 &pCertContext->pCertInfo->SubjectPublicKeyInfo, publicKey);
1503 return ret;
1506 static BOOL compare_cert_by_subject_cert(PCCERT_CONTEXT pCertContext,
1507 DWORD dwType, DWORD dwFlags, const void *pvPara)
1509 CERT_INFO *pCertInfo = (CERT_INFO *)pvPara;
1510 BOOL ret;
1512 /* Matching serial number and subject match.. */
1513 ret = CertCompareCertificateName(pCertContext->dwCertEncodingType,
1514 &pCertContext->pCertInfo->Subject, &pCertInfo->Issuer);
1515 if (ret)
1516 ret = CertCompareIntegerBlob(&pCertContext->pCertInfo->SerialNumber,
1517 &pCertInfo->SerialNumber);
1518 else
1520 /* failing that, if the serial number and issuer match, we match */
1521 ret = CertCompareIntegerBlob(&pCertContext->pCertInfo->SerialNumber,
1522 &pCertInfo->SerialNumber);
1523 if (ret)
1524 ret = CertCompareCertificateName(pCertContext->dwCertEncodingType,
1525 &pCertContext->pCertInfo->Issuer, &pCertInfo->Issuer);
1527 TRACE("returning %d\n", ret);
1528 return ret;
1531 static BOOL compare_cert_by_cert_id(PCCERT_CONTEXT pCertContext, DWORD dwType,
1532 DWORD dwFlags, const void *pvPara)
1534 CERT_ID *id = (CERT_ID *)pvPara;
1535 BOOL ret;
1537 switch (id->dwIdChoice)
1539 case CERT_ID_ISSUER_SERIAL_NUMBER:
1540 ret = CertCompareCertificateName(pCertContext->dwCertEncodingType,
1541 &pCertContext->pCertInfo->Issuer, &id->u.IssuerSerialNumber.Issuer);
1542 if (ret)
1543 ret = CertCompareIntegerBlob(&pCertContext->pCertInfo->SerialNumber,
1544 &id->u.IssuerSerialNumber.SerialNumber);
1545 break;
1546 case CERT_ID_SHA1_HASH:
1547 ret = compare_cert_by_sha1_hash(pCertContext, dwType, dwFlags,
1548 &id->u.HashId);
1549 break;
1550 case CERT_ID_KEY_IDENTIFIER:
1552 DWORD size = 0;
1554 ret = CertGetCertificateContextProperty(pCertContext,
1555 CERT_KEY_IDENTIFIER_PROP_ID, NULL, &size);
1556 if (ret && size == id->u.KeyId.cbData)
1558 LPBYTE buf = CryptMemAlloc(size);
1560 if (buf)
1562 CertGetCertificateContextProperty(pCertContext,
1563 CERT_KEY_IDENTIFIER_PROP_ID, buf, &size);
1564 ret = !memcmp(buf, id->u.KeyId.pbData, size);
1565 CryptMemFree(buf);
1567 else
1568 ret = FALSE;
1570 else
1571 ret = FALSE;
1572 break;
1574 default:
1575 ret = FALSE;
1576 break;
1578 return ret;
1581 static BOOL compare_existing_cert(PCCERT_CONTEXT pCertContext, DWORD dwType,
1582 DWORD dwFlags, const void *pvPara)
1584 PCCERT_CONTEXT toCompare = pvPara;
1585 return CertCompareCertificate(pCertContext->dwCertEncodingType,
1586 pCertContext->pCertInfo, toCompare->pCertInfo);
1589 static BOOL compare_cert_by_signature_hash(PCCERT_CONTEXT pCertContext, DWORD dwType,
1590 DWORD dwFlags, const void *pvPara)
1592 const CRYPT_HASH_BLOB *hash = pvPara;
1593 DWORD size = 0;
1594 BOOL ret;
1596 ret = CertGetCertificateContextProperty(pCertContext,
1597 CERT_SIGNATURE_HASH_PROP_ID, NULL, &size);
1598 if (ret && size == hash->cbData)
1600 LPBYTE buf = CryptMemAlloc(size);
1602 if (buf)
1604 CertGetCertificateContextProperty(pCertContext,
1605 CERT_SIGNATURE_HASH_PROP_ID, buf, &size);
1606 ret = !memcmp(buf, hash->pbData, size);
1607 CryptMemFree(buf);
1609 else
1610 ret = FALSE;
1612 else
1613 ret = FALSE;
1614 return ret;
1617 static inline PCCERT_CONTEXT cert_compare_certs_in_store(HCERTSTORE store,
1618 PCCERT_CONTEXT prev, CertCompareFunc compare, DWORD dwType, DWORD dwFlags,
1619 const void *pvPara)
1621 BOOL matches = FALSE;
1622 PCCERT_CONTEXT ret;
1624 ret = prev;
1625 do {
1626 ret = CertEnumCertificatesInStore(store, ret);
1627 if (ret)
1628 matches = compare(ret, dwType, dwFlags, pvPara);
1629 } while (ret != NULL && !matches);
1630 return ret;
1633 typedef PCCERT_CONTEXT (*CertFindFunc)(HCERTSTORE store, DWORD dwType,
1634 DWORD dwFlags, const void *pvPara, PCCERT_CONTEXT prev);
1636 static PCCERT_CONTEXT find_cert_any(HCERTSTORE store, DWORD dwType,
1637 DWORD dwFlags, const void *pvPara, PCCERT_CONTEXT prev)
1639 return CertEnumCertificatesInStore(store, prev);
1642 static PCCERT_CONTEXT find_cert_by_issuer(HCERTSTORE store, DWORD dwType,
1643 DWORD dwFlags, const void *pvPara, PCCERT_CONTEXT prev)
1645 BOOL ret;
1646 PCCERT_CONTEXT found = NULL, subject = pvPara;
1647 PCERT_EXTENSION ext;
1648 DWORD size;
1650 if ((ext = CertFindExtension(szOID_AUTHORITY_KEY_IDENTIFIER,
1651 subject->pCertInfo->cExtension, subject->pCertInfo->rgExtension)))
1653 CERT_AUTHORITY_KEY_ID_INFO *info;
1655 ret = CryptDecodeObjectEx(subject->dwCertEncodingType,
1656 X509_AUTHORITY_KEY_ID, ext->Value.pbData, ext->Value.cbData,
1657 CRYPT_DECODE_ALLOC_FLAG | CRYPT_DECODE_NOCOPY_FLAG, NULL,
1658 &info, &size);
1659 if (ret)
1661 CERT_ID id;
1663 if (info->CertIssuer.cbData && info->CertSerialNumber.cbData)
1665 id.dwIdChoice = CERT_ID_ISSUER_SERIAL_NUMBER;
1666 memcpy(&id.u.IssuerSerialNumber.Issuer, &info->CertIssuer,
1667 sizeof(CERT_NAME_BLOB));
1668 memcpy(&id.u.IssuerSerialNumber.SerialNumber,
1669 &info->CertSerialNumber, sizeof(CRYPT_INTEGER_BLOB));
1671 else if (info->KeyId.cbData)
1673 id.dwIdChoice = CERT_ID_KEY_IDENTIFIER;
1674 memcpy(&id.u.KeyId, &info->KeyId, sizeof(CRYPT_HASH_BLOB));
1676 else
1677 ret = FALSE;
1678 if (ret)
1679 found = cert_compare_certs_in_store(store, prev,
1680 compare_cert_by_cert_id, dwType, dwFlags, &id);
1681 LocalFree(info);
1684 else if ((ext = CertFindExtension(szOID_AUTHORITY_KEY_IDENTIFIER2,
1685 subject->pCertInfo->cExtension, subject->pCertInfo->rgExtension)))
1687 CERT_AUTHORITY_KEY_ID2_INFO *info;
1689 ret = CryptDecodeObjectEx(subject->dwCertEncodingType,
1690 X509_AUTHORITY_KEY_ID2, ext->Value.pbData, ext->Value.cbData,
1691 CRYPT_DECODE_ALLOC_FLAG | CRYPT_DECODE_NOCOPY_FLAG, NULL,
1692 &info, &size);
1693 if (ret)
1695 CERT_ID id;
1697 if (info->AuthorityCertIssuer.cAltEntry &&
1698 info->AuthorityCertSerialNumber.cbData)
1700 PCERT_ALT_NAME_ENTRY directoryName = NULL;
1701 DWORD i;
1703 for (i = 0; !directoryName &&
1704 i < info->AuthorityCertIssuer.cAltEntry; i++)
1705 if (info->AuthorityCertIssuer.rgAltEntry[i].dwAltNameChoice
1706 == CERT_ALT_NAME_DIRECTORY_NAME)
1707 directoryName =
1708 &info->AuthorityCertIssuer.rgAltEntry[i];
1709 if (directoryName)
1711 id.dwIdChoice = CERT_ID_ISSUER_SERIAL_NUMBER;
1712 memcpy(&id.u.IssuerSerialNumber.Issuer,
1713 &directoryName->u.DirectoryName, sizeof(CERT_NAME_BLOB));
1714 memcpy(&id.u.IssuerSerialNumber.SerialNumber,
1715 &info->AuthorityCertSerialNumber,
1716 sizeof(CRYPT_INTEGER_BLOB));
1718 else
1720 FIXME("no supported name type in authority key id2\n");
1721 ret = FALSE;
1724 else if (info->KeyId.cbData)
1726 id.dwIdChoice = CERT_ID_KEY_IDENTIFIER;
1727 memcpy(&id.u.KeyId, &info->KeyId, sizeof(CRYPT_HASH_BLOB));
1729 else
1730 ret = FALSE;
1731 if (ret)
1732 found = cert_compare_certs_in_store(store, prev,
1733 compare_cert_by_cert_id, dwType, dwFlags, &id);
1734 LocalFree(info);
1737 else
1738 found = cert_compare_certs_in_store(store, prev,
1739 compare_cert_by_name, CERT_COMPARE_NAME | CERT_COMPARE_SUBJECT_CERT,
1740 dwFlags, &subject->pCertInfo->Issuer);
1741 return found;
1744 static BOOL compare_cert_by_name_str(PCCERT_CONTEXT pCertContext,
1745 DWORD dwType, DWORD dwFlags, const void *pvPara)
1747 PCERT_NAME_BLOB name;
1748 DWORD len;
1749 BOOL ret = FALSE;
1751 if (dwType & CERT_INFO_SUBJECT_FLAG)
1752 name = &pCertContext->pCertInfo->Subject;
1753 else
1754 name = &pCertContext->pCertInfo->Issuer;
1755 len = CertNameToStrW(pCertContext->dwCertEncodingType, name,
1756 CERT_SIMPLE_NAME_STR, NULL, 0);
1757 if (len)
1759 LPWSTR str = CryptMemAlloc(len * sizeof(WCHAR));
1761 if (str)
1763 CertNameToStrW(pCertContext->dwCertEncodingType, name,
1764 CERT_SIMPLE_NAME_STR, str, len);
1765 wcslwr(str);
1766 if (wcsstr(str, pvPara))
1767 ret = TRUE;
1768 CryptMemFree(str);
1771 return ret;
1774 static PCCERT_CONTEXT find_cert_by_name_str_a(HCERTSTORE store, DWORD dwType,
1775 DWORD dwFlags, const void *pvPara, PCCERT_CONTEXT prev)
1777 PCCERT_CONTEXT found = NULL;
1779 TRACE("%s\n", debugstr_a(pvPara));
1781 if (pvPara)
1783 int len = MultiByteToWideChar(CP_ACP, 0, pvPara, -1, NULL, 0);
1784 LPWSTR str = CryptMemAlloc(len * sizeof(WCHAR));
1786 if (str)
1788 MultiByteToWideChar(CP_ACP, 0, pvPara, -1, str, len);
1789 wcslwr(str);
1790 found = cert_compare_certs_in_store(store, prev,
1791 compare_cert_by_name_str, dwType, dwFlags, str);
1792 CryptMemFree(str);
1795 else
1796 found = find_cert_any(store, dwType, dwFlags, NULL, prev);
1797 return found;
1800 static PCCERT_CONTEXT find_cert_by_name_str_w(HCERTSTORE store, DWORD dwType,
1801 DWORD dwFlags, const void *pvPara, PCCERT_CONTEXT prev)
1803 PCCERT_CONTEXT found = NULL;
1805 TRACE("%s\n", debugstr_w(pvPara));
1807 if (pvPara)
1809 DWORD len = lstrlenW(pvPara);
1810 LPWSTR str = CryptMemAlloc((len + 1) * sizeof(WCHAR));
1812 if (str)
1814 wcscpy( str, pvPara );
1815 wcslwr( str );
1816 found = cert_compare_certs_in_store(store, prev,
1817 compare_cert_by_name_str, dwType, dwFlags, str);
1818 CryptMemFree(str);
1821 else
1822 found = find_cert_any(store, dwType, dwFlags, NULL, prev);
1823 return found;
1826 PCCERT_CONTEXT WINAPI CertFindCertificateInStore(HCERTSTORE hCertStore,
1827 DWORD dwCertEncodingType, DWORD dwFlags, DWORD dwType, const void *pvPara,
1828 PCCERT_CONTEXT pPrevCertContext)
1830 PCCERT_CONTEXT ret;
1831 CertFindFunc find = NULL;
1832 CertCompareFunc compare = NULL;
1833 CERT_ID cert_id;
1835 TRACE("(%p, %08lx, %08lx, %08lx, %p, %p)\n", hCertStore, dwCertEncodingType,
1836 dwFlags, dwType, pvPara, pPrevCertContext);
1838 switch (dwType >> CERT_COMPARE_SHIFT)
1840 case CERT_COMPARE_ANY:
1841 find = find_cert_any;
1842 break;
1843 case CERT_COMPARE_MD5_HASH:
1844 compare = compare_cert_by_md5_hash;
1845 break;
1846 case CERT_COMPARE_SHA1_HASH:
1847 compare = compare_cert_by_sha1_hash;
1848 break;
1849 case CERT_COMPARE_NAME:
1850 compare = compare_cert_by_name;
1851 break;
1852 case CERT_COMPARE_PUBLIC_KEY:
1853 compare = compare_cert_by_public_key;
1854 break;
1855 case CERT_COMPARE_NAME_STR_A:
1856 find = find_cert_by_name_str_a;
1857 break;
1858 case CERT_COMPARE_NAME_STR_W:
1859 find = find_cert_by_name_str_w;
1860 break;
1861 case CERT_COMPARE_SUBJECT_CERT:
1862 compare = compare_cert_by_subject_cert;
1863 break;
1864 case CERT_COMPARE_KEY_IDENTIFIER:
1865 cert_id.dwIdChoice = CERT_ID_KEY_IDENTIFIER;
1866 cert_id.u.KeyId = *(const CRYPT_HASH_BLOB *)pvPara;
1867 pvPara = &cert_id;
1868 /* fall through */
1869 case CERT_COMPARE_CERT_ID:
1870 compare = compare_cert_by_cert_id;
1871 break;
1872 case CERT_COMPARE_ISSUER_OF:
1873 find = find_cert_by_issuer;
1874 break;
1875 case CERT_COMPARE_EXISTING:
1876 compare = compare_existing_cert;
1877 break;
1878 case CERT_COMPARE_SIGNATURE_HASH:
1879 compare = compare_cert_by_signature_hash;
1880 break;
1881 default:
1882 FIXME("find type %08lx unimplemented\n", dwType);
1885 if (find)
1886 ret = find(hCertStore, dwType, dwFlags, pvPara, pPrevCertContext);
1887 else if (compare)
1888 ret = cert_compare_certs_in_store(hCertStore, pPrevCertContext,
1889 compare, dwType, dwFlags, pvPara);
1890 else
1891 ret = NULL;
1892 if (!ret)
1893 SetLastError(CRYPT_E_NOT_FOUND);
1894 TRACE("returning %p\n", ret);
1895 return ret;
1898 PCCERT_CONTEXT WINAPI CertGetSubjectCertificateFromStore(HCERTSTORE hCertStore,
1899 DWORD dwCertEncodingType, PCERT_INFO pCertId)
1901 TRACE("(%p, %08lx, %p)\n", hCertStore, dwCertEncodingType, pCertId);
1903 if (!pCertId)
1905 SetLastError(E_INVALIDARG);
1906 return NULL;
1908 return CertFindCertificateInStore(hCertStore, dwCertEncodingType, 0,
1909 CERT_FIND_SUBJECT_CERT, pCertId, NULL);
1912 BOOL WINAPI CertVerifySubjectCertificateContext(PCCERT_CONTEXT pSubject,
1913 PCCERT_CONTEXT pIssuer, DWORD *pdwFlags)
1915 static const DWORD supportedFlags = CERT_STORE_REVOCATION_FLAG |
1916 CERT_STORE_SIGNATURE_FLAG | CERT_STORE_TIME_VALIDITY_FLAG;
1918 if (*pdwFlags & ~supportedFlags)
1920 SetLastError(E_INVALIDARG);
1921 return FALSE;
1923 if (*pdwFlags & CERT_STORE_REVOCATION_FLAG)
1925 DWORD flags = 0;
1926 PCCRL_CONTEXT crl = CertGetCRLFromStore(pSubject->hCertStore, pSubject,
1927 NULL, &flags);
1929 /* FIXME: what if the CRL has expired? */
1930 if (crl)
1932 if (CertVerifyCRLRevocation(pSubject->dwCertEncodingType,
1933 pSubject->pCertInfo, 1, (PCRL_INFO *)&crl->pCrlInfo))
1934 *pdwFlags &= CERT_STORE_REVOCATION_FLAG;
1936 else
1937 *pdwFlags |= CERT_STORE_NO_CRL_FLAG;
1939 if (*pdwFlags & CERT_STORE_TIME_VALIDITY_FLAG)
1941 if (0 == CertVerifyTimeValidity(NULL, pSubject->pCertInfo))
1942 *pdwFlags &= ~CERT_STORE_TIME_VALIDITY_FLAG;
1944 if (*pdwFlags & CERT_STORE_SIGNATURE_FLAG)
1946 if (CryptVerifyCertificateSignatureEx(0, pSubject->dwCertEncodingType,
1947 CRYPT_VERIFY_CERT_SIGN_SUBJECT_CERT, (void *)pSubject,
1948 CRYPT_VERIFY_CERT_SIGN_ISSUER_CERT, (void *)pIssuer, 0, NULL))
1949 *pdwFlags &= ~CERT_STORE_SIGNATURE_FLAG;
1951 return TRUE;
1954 PCCERT_CONTEXT WINAPI CertGetIssuerCertificateFromStore(HCERTSTORE hCertStore,
1955 PCCERT_CONTEXT pSubjectContext, PCCERT_CONTEXT pPrevIssuerContext,
1956 DWORD *pdwFlags)
1958 PCCERT_CONTEXT ret;
1960 TRACE("(%p, %p, %p, %08lx)\n", hCertStore, pSubjectContext,
1961 pPrevIssuerContext, *pdwFlags);
1963 if (!pSubjectContext)
1965 SetLastError(E_INVALIDARG);
1966 return NULL;
1969 ret = CertFindCertificateInStore(hCertStore,
1970 pSubjectContext->dwCertEncodingType, 0, CERT_FIND_ISSUER_OF,
1971 pSubjectContext, pPrevIssuerContext);
1972 if (ret)
1974 if (!CertVerifySubjectCertificateContext(pSubjectContext, ret,
1975 pdwFlags))
1977 CertFreeCertificateContext(ret);
1978 ret = NULL;
1980 if (CRYPT_IsCertificateSelfSigned(pSubjectContext))
1982 CertFreeCertificateContext(ret);
1983 ret = NULL;
1984 SetLastError(CRYPT_E_SELF_SIGNED);
1987 TRACE("returning %p\n", ret);
1988 return ret;
1991 typedef struct _OLD_CERT_REVOCATION_STATUS {
1992 DWORD cbSize;
1993 DWORD dwIndex;
1994 DWORD dwError;
1995 DWORD dwReason;
1996 } OLD_CERT_REVOCATION_STATUS;
1998 typedef BOOL (WINAPI *CertVerifyRevocationFunc)(DWORD, DWORD, DWORD,
1999 void **, DWORD, PCERT_REVOCATION_PARA, PCERT_REVOCATION_STATUS);
2001 BOOL WINAPI CertVerifyRevocation(DWORD dwEncodingType, DWORD dwRevType,
2002 DWORD cContext, PVOID rgpvContext[], DWORD dwFlags,
2003 PCERT_REVOCATION_PARA pRevPara, PCERT_REVOCATION_STATUS pRevStatus)
2005 BOOL ret;
2007 TRACE("(%08lx, %ld, %ld, %p, %08lx, %p, %p)\n", dwEncodingType, dwRevType,
2008 cContext, rgpvContext, dwFlags, pRevPara, pRevStatus);
2010 if (pRevStatus->cbSize != sizeof(OLD_CERT_REVOCATION_STATUS) &&
2011 pRevStatus->cbSize != sizeof(CERT_REVOCATION_STATUS))
2013 SetLastError(E_INVALIDARG);
2014 return FALSE;
2016 if (cContext)
2018 static HCRYPTOIDFUNCSET set = NULL;
2019 DWORD size;
2021 if (!set)
2022 set = CryptInitOIDFunctionSet(CRYPT_OID_VERIFY_REVOCATION_FUNC, 0);
2023 ret = CryptGetDefaultOIDDllList(set, dwEncodingType, NULL, &size);
2024 if (ret)
2026 if (size == 1)
2028 /* empty list */
2029 SetLastError(CRYPT_E_NO_REVOCATION_DLL);
2030 ret = FALSE;
2032 else
2034 LPWSTR dllList = CryptMemAlloc(size * sizeof(WCHAR)), ptr;
2036 if (dllList)
2038 ret = CryptGetDefaultOIDDllList(set, dwEncodingType,
2039 dllList, &size);
2040 if (ret)
2042 for (ptr = dllList; ret && *ptr;
2043 ptr += lstrlenW(ptr) + 1)
2045 CertVerifyRevocationFunc func;
2046 HCRYPTOIDFUNCADDR hFunc;
2048 ret = CryptGetDefaultOIDFunctionAddress(set,
2049 dwEncodingType, ptr, 0, (void **)&func, &hFunc);
2050 if (ret)
2052 ret = func(dwEncodingType, dwRevType, cContext,
2053 rgpvContext, dwFlags, pRevPara, pRevStatus);
2054 CryptFreeOIDFunctionAddress(hFunc, 0);
2058 CryptMemFree(dllList);
2060 else
2062 SetLastError(ERROR_OUTOFMEMORY);
2063 ret = FALSE;
2068 else
2069 ret = TRUE;
2070 return ret;
2073 PCRYPT_ATTRIBUTE WINAPI CertFindAttribute(LPCSTR pszObjId, DWORD cAttr,
2074 CRYPT_ATTRIBUTE rgAttr[])
2076 PCRYPT_ATTRIBUTE ret = NULL;
2077 DWORD i;
2079 TRACE("%s %ld %p\n", debugstr_a(pszObjId), cAttr, rgAttr);
2081 if (!cAttr)
2082 return NULL;
2083 if (!pszObjId)
2085 SetLastError(ERROR_INVALID_PARAMETER);
2086 return NULL;
2089 for (i = 0; !ret && i < cAttr; i++)
2090 if (rgAttr[i].pszObjId && !strcmp(pszObjId, rgAttr[i].pszObjId))
2091 ret = &rgAttr[i];
2092 return ret;
2095 PCERT_EXTENSION WINAPI CertFindExtension(LPCSTR pszObjId, DWORD cExtensions,
2096 CERT_EXTENSION rgExtensions[])
2098 PCERT_EXTENSION ret = NULL;
2099 DWORD i;
2101 TRACE("%s %ld %p\n", debugstr_a(pszObjId), cExtensions, rgExtensions);
2103 if (!cExtensions)
2104 return NULL;
2105 if (!pszObjId)
2107 SetLastError(ERROR_INVALID_PARAMETER);
2108 return NULL;
2111 for (i = 0; !ret && i < cExtensions; i++)
2112 if (rgExtensions[i].pszObjId && !strcmp(pszObjId,
2113 rgExtensions[i].pszObjId))
2114 ret = &rgExtensions[i];
2115 return ret;
2118 PCERT_RDN_ATTR WINAPI CertFindRDNAttr(LPCSTR pszObjId, PCERT_NAME_INFO pName)
2120 PCERT_RDN_ATTR ret = NULL;
2121 DWORD i, j;
2123 TRACE("%s %p\n", debugstr_a(pszObjId), pName);
2125 if (!pszObjId)
2127 SetLastError(ERROR_INVALID_PARAMETER);
2128 return NULL;
2131 for (i = 0; !ret && i < pName->cRDN; i++)
2132 for (j = 0; !ret && j < pName->rgRDN[i].cRDNAttr; j++)
2133 if (pName->rgRDN[i].rgRDNAttr[j].pszObjId && !strcmp(pszObjId,
2134 pName->rgRDN[i].rgRDNAttr[j].pszObjId))
2135 ret = &pName->rgRDN[i].rgRDNAttr[j];
2136 return ret;
2139 static BOOL find_matching_rdn_attr(DWORD dwFlags, const CERT_NAME_INFO *name,
2140 const CERT_RDN_ATTR *attr)
2142 DWORD i, j;
2143 BOOL match = FALSE;
2145 for (i = 0; !match && i < name->cRDN; i++)
2147 for (j = 0; j < name->rgRDN[i].cRDNAttr; j++)
2149 if (!strcmp(name->rgRDN[i].rgRDNAttr[j].pszObjId,
2150 attr->pszObjId) &&
2151 name->rgRDN[i].rgRDNAttr[j].dwValueType ==
2152 attr->dwValueType)
2154 if (dwFlags & CERT_UNICODE_IS_RDN_ATTRS_FLAG)
2156 LPCWSTR nameStr =
2157 (LPCWSTR)name->rgRDN[i].rgRDNAttr[j].Value.pbData;
2158 LPCWSTR attrStr = (LPCWSTR)attr->Value.pbData;
2160 if (attr->Value.cbData !=
2161 name->rgRDN[i].rgRDNAttr[j].Value.cbData)
2162 match = FALSE;
2163 else if (dwFlags & CERT_CASE_INSENSITIVE_IS_RDN_ATTRS_FLAG)
2164 match = !wcsnicmp(nameStr, attrStr,
2165 attr->Value.cbData / sizeof(WCHAR));
2166 else
2167 match = !wcsncmp(nameStr, attrStr,
2168 attr->Value.cbData / sizeof(WCHAR));
2169 TRACE("%s : %s => %d\n",
2170 debugstr_wn(nameStr, attr->Value.cbData / sizeof(WCHAR)),
2171 debugstr_wn(attrStr, attr->Value.cbData / sizeof(WCHAR)),
2172 match);
2174 else
2176 LPCSTR nameStr =
2177 (LPCSTR)name->rgRDN[i].rgRDNAttr[j].Value.pbData;
2178 LPCSTR attrStr = (LPCSTR)attr->Value.pbData;
2180 if (attr->Value.cbData !=
2181 name->rgRDN[i].rgRDNAttr[j].Value.cbData)
2182 match = FALSE;
2183 else if (dwFlags & CERT_CASE_INSENSITIVE_IS_RDN_ATTRS_FLAG)
2184 match = !_strnicmp(nameStr, attrStr,
2185 attr->Value.cbData);
2186 else
2187 match = !strncmp(nameStr, attrStr, attr->Value.cbData);
2188 TRACE("%s : %s => %d\n",
2189 debugstr_an(nameStr, attr->Value.cbData),
2190 debugstr_an(attrStr, attr->Value.cbData), match);
2195 return match;
2198 BOOL WINAPI CertIsRDNAttrsInCertificateName(DWORD dwCertEncodingType,
2199 DWORD dwFlags, PCERT_NAME_BLOB pCertName, PCERT_RDN pRDN)
2201 CERT_NAME_INFO *name;
2202 LPCSTR type;
2203 DWORD size;
2204 BOOL ret;
2206 TRACE("(%08lx, %08lx, %p, %p)\n", dwCertEncodingType, dwFlags, pCertName,
2207 pRDN);
2209 type = dwFlags & CERT_UNICODE_IS_RDN_ATTRS_FLAG ? X509_UNICODE_NAME :
2210 X509_NAME;
2211 if ((ret = CryptDecodeObjectEx(dwCertEncodingType, type, pCertName->pbData,
2212 pCertName->cbData, CRYPT_DECODE_ALLOC_FLAG, NULL, &name, &size)))
2214 DWORD i;
2216 for (i = 0; ret && i < pRDN->cRDNAttr; i++)
2217 ret = find_matching_rdn_attr(dwFlags, name, &pRDN->rgRDNAttr[i]);
2218 if (!ret)
2219 SetLastError(CRYPT_E_NO_MATCH);
2220 LocalFree(name);
2222 return ret;
2225 LONG WINAPI CertVerifyTimeValidity(LPFILETIME pTimeToVerify,
2226 PCERT_INFO pCertInfo)
2228 FILETIME fileTime;
2229 LONG ret;
2231 if (!pTimeToVerify)
2233 GetSystemTimeAsFileTime(&fileTime);
2234 pTimeToVerify = &fileTime;
2236 if ((ret = CompareFileTime(pTimeToVerify, &pCertInfo->NotBefore)) >= 0)
2238 ret = CompareFileTime(pTimeToVerify, &pCertInfo->NotAfter);
2239 if (ret < 0)
2240 ret = 0;
2242 return ret;
2245 BOOL WINAPI CertVerifyValidityNesting(PCERT_INFO pSubjectInfo,
2246 PCERT_INFO pIssuerInfo)
2248 TRACE("(%p, %p)\n", pSubjectInfo, pIssuerInfo);
2250 return CertVerifyTimeValidity(&pSubjectInfo->NotBefore, pIssuerInfo) == 0
2251 && CertVerifyTimeValidity(&pSubjectInfo->NotAfter, pIssuerInfo) == 0;
2254 BOOL WINAPI CryptHashCertificate(HCRYPTPROV_LEGACY hCryptProv, ALG_ID Algid,
2255 DWORD dwFlags, const BYTE *pbEncoded, DWORD cbEncoded, BYTE *pbComputedHash,
2256 DWORD *pcbComputedHash)
2258 BOOL ret = TRUE;
2259 HCRYPTHASH hHash = 0;
2261 TRACE("(%08Ix, %d, %08lx, %p, %ld, %p, %p)\n", hCryptProv, Algid, dwFlags,
2262 pbEncoded, cbEncoded, pbComputedHash, pcbComputedHash);
2264 if (!hCryptProv)
2265 hCryptProv = I_CryptGetDefaultCryptProv(Algid);
2266 if (!Algid)
2267 Algid = CALG_SHA1;
2268 if (ret)
2270 ret = CryptCreateHash(hCryptProv, Algid, 0, 0, &hHash);
2271 if (ret)
2273 ret = CryptHashData(hHash, pbEncoded, cbEncoded, 0);
2274 if (ret)
2275 ret = CryptGetHashParam(hHash, HP_HASHVAL, pbComputedHash,
2276 pcbComputedHash, 0);
2277 CryptDestroyHash(hHash);
2280 return ret;
2283 BOOL WINAPI CryptHashCertificate2(LPCWSTR pwszCNGHashAlgid, DWORD dwFlags,
2284 void *pvReserved, const BYTE *pbEncoded, DWORD cbEncoded, BYTE *pbComputedHash,
2285 DWORD *pcbComputedHash)
2287 BCRYPT_HASH_HANDLE hash = NULL;
2288 BCRYPT_ALG_HANDLE alg = NULL;
2289 NTSTATUS status;
2290 DWORD hash_len;
2291 DWORD hash_len_size;
2293 TRACE("(%s, %08lx, %p, %p, %ld, %p, %p)\n", debugstr_w(pwszCNGHashAlgid),
2294 dwFlags, pvReserved, pbEncoded, cbEncoded, pbComputedHash, pcbComputedHash);
2296 if ((status = BCryptOpenAlgorithmProvider(&alg, pwszCNGHashAlgid, NULL, 0)))
2298 if (status == STATUS_NOT_IMPLEMENTED)
2299 status = STATUS_NOT_FOUND;
2300 goto done;
2303 if ((status = BCryptCreateHash(alg, &hash, NULL, 0, NULL, 0, 0)))
2304 goto done;
2306 if ((status = BCryptGetProperty(hash, BCRYPT_HASH_LENGTH, (BYTE *)&hash_len, sizeof(hash_len), &hash_len_size, 0)))
2307 goto done;
2309 if (!pbComputedHash)
2311 *pcbComputedHash = hash_len;
2312 goto done;
2315 if (*pcbComputedHash < hash_len)
2317 status = ERROR_MORE_DATA;
2318 goto done;
2321 *pcbComputedHash = hash_len;
2323 if ((status = BCryptHashData(hash, (BYTE *)pbEncoded, cbEncoded, 0)))
2324 goto done;
2326 if ((status = BCryptFinishHash(hash, pbComputedHash, hash_len, 0)))
2327 goto done;
2329 done:
2330 if (hash) BCryptDestroyHash(hash);
2331 if (alg) BCryptCloseAlgorithmProvider(alg, 0);
2332 if (status) SetLastError(status);
2333 return !status;
2336 BOOL WINAPI CryptHashPublicKeyInfo(HCRYPTPROV_LEGACY hCryptProv, ALG_ID Algid,
2337 DWORD dwFlags, DWORD dwCertEncodingType, PCERT_PUBLIC_KEY_INFO pInfo,
2338 BYTE *pbComputedHash, DWORD *pcbComputedHash)
2340 BOOL ret = TRUE;
2341 HCRYPTHASH hHash = 0;
2343 TRACE("(%08Ix, %d, %08lx, %ld, %p, %p, %p)\n", hCryptProv, Algid, dwFlags,
2344 dwCertEncodingType, pInfo, pbComputedHash, pcbComputedHash);
2346 if (!hCryptProv)
2347 hCryptProv = I_CryptGetDefaultCryptProv(0);
2348 if (!Algid)
2349 Algid = CALG_MD5;
2350 if ((dwCertEncodingType & CERT_ENCODING_TYPE_MASK) != X509_ASN_ENCODING)
2352 SetLastError(ERROR_FILE_NOT_FOUND);
2353 return FALSE;
2355 if (ret)
2357 BYTE *buf;
2358 DWORD size = 0;
2360 ret = CRYPT_AsnEncodePubKeyInfoNoNull(dwCertEncodingType,
2361 X509_PUBLIC_KEY_INFO, pInfo, CRYPT_ENCODE_ALLOC_FLAG, NULL,
2362 (LPBYTE)&buf, &size);
2363 if (ret)
2365 ret = CryptCreateHash(hCryptProv, Algid, 0, 0, &hHash);
2366 if (ret)
2368 ret = CryptHashData(hHash, buf, size, 0);
2369 if (ret)
2370 ret = CryptGetHashParam(hHash, HP_HASHVAL, pbComputedHash,
2371 pcbComputedHash, 0);
2372 CryptDestroyHash(hHash);
2374 LocalFree(buf);
2377 return ret;
2380 BOOL WINAPI CryptHashToBeSigned(HCRYPTPROV_LEGACY hCryptProv,
2381 DWORD dwCertEncodingType, const BYTE *pbEncoded, DWORD cbEncoded,
2382 BYTE *pbComputedHash, DWORD *pcbComputedHash)
2384 BOOL ret;
2385 CERT_SIGNED_CONTENT_INFO *info;
2386 DWORD size;
2388 TRACE("(%08Ix, %08lx, %p, %ld, %p, %ld)\n", hCryptProv, dwCertEncodingType,
2389 pbEncoded, cbEncoded, pbComputedHash, *pcbComputedHash);
2391 ret = CryptDecodeObjectEx(dwCertEncodingType, X509_CERT,
2392 pbEncoded, cbEncoded, CRYPT_DECODE_ALLOC_FLAG, NULL, &info, &size);
2393 if (ret)
2395 PCCRYPT_OID_INFO oidInfo;
2396 HCRYPTHASH hHash;
2398 if (!hCryptProv)
2399 hCryptProv = I_CryptGetDefaultCryptProv(0);
2400 oidInfo = CryptFindOIDInfo(CRYPT_OID_INFO_OID_KEY,
2401 info->SignatureAlgorithm.pszObjId, 0);
2402 if (!oidInfo)
2404 SetLastError(NTE_BAD_ALGID);
2405 ret = FALSE;
2407 else
2409 ret = CryptCreateHash(hCryptProv, oidInfo->u.Algid, 0, 0, &hHash);
2410 if (ret)
2412 ret = CryptHashData(hHash, info->ToBeSigned.pbData,
2413 info->ToBeSigned.cbData, 0);
2414 if (ret)
2415 ret = CryptGetHashParam(hHash, HP_HASHVAL, pbComputedHash,
2416 pcbComputedHash, 0);
2417 CryptDestroyHash(hHash);
2420 LocalFree(info);
2422 return ret;
2425 BOOL WINAPI CryptSignCertificate(HCRYPTPROV_OR_NCRYPT_KEY_HANDLE hCryptProv,
2426 DWORD dwKeySpec, DWORD dwCertEncodingType, const BYTE *pbEncodedToBeSigned,
2427 DWORD cbEncodedToBeSigned, PCRYPT_ALGORITHM_IDENTIFIER pSignatureAlgorithm,
2428 const void *pvHashAuxInfo, BYTE *pbSignature, DWORD *pcbSignature)
2430 BOOL ret;
2431 PCCRYPT_OID_INFO info;
2432 HCRYPTHASH hHash;
2434 TRACE("(%08Ix, %ld, %ld, %p, %ld, %p, %p, %p, %p)\n", hCryptProv,
2435 dwKeySpec, dwCertEncodingType, pbEncodedToBeSigned, cbEncodedToBeSigned,
2436 pSignatureAlgorithm, pvHashAuxInfo, pbSignature, pcbSignature);
2438 info = CryptFindOIDInfo(CRYPT_OID_INFO_OID_KEY,
2439 pSignatureAlgorithm->pszObjId, 0);
2440 if (!info)
2442 SetLastError(NTE_BAD_ALGID);
2443 return FALSE;
2445 if (info->dwGroupId == CRYPT_HASH_ALG_OID_GROUP_ID)
2447 if (!hCryptProv)
2448 hCryptProv = I_CryptGetDefaultCryptProv(0);
2449 ret = CryptCreateHash(hCryptProv, info->u.Algid, 0, 0, &hHash);
2450 if (ret)
2452 ret = CryptHashData(hHash, pbEncodedToBeSigned,
2453 cbEncodedToBeSigned, 0);
2454 if (ret)
2455 ret = CryptGetHashParam(hHash, HP_HASHVAL, pbSignature,
2456 pcbSignature, 0);
2457 CryptDestroyHash(hHash);
2460 else
2462 if (!hCryptProv)
2464 SetLastError(ERROR_INVALID_PARAMETER);
2465 ret = FALSE;
2467 else
2469 ret = CryptCreateHash(hCryptProv, info->u.Algid, 0, 0, &hHash);
2470 if (ret)
2472 ret = CryptHashData(hHash, pbEncodedToBeSigned,
2473 cbEncodedToBeSigned, 0);
2474 if (ret)
2475 ret = CryptSignHashW(hHash, dwKeySpec, NULL, 0, pbSignature,
2476 pcbSignature);
2477 CryptDestroyHash(hHash);
2481 return ret;
2484 BOOL WINAPI CryptSignAndEncodeCertificate(HCRYPTPROV_OR_NCRYPT_KEY_HANDLE hCryptProv,
2485 DWORD dwKeySpec, DWORD dwCertEncodingType, LPCSTR lpszStructType,
2486 const void *pvStructInfo, PCRYPT_ALGORITHM_IDENTIFIER pSignatureAlgorithm,
2487 const void *pvHashAuxInfo, BYTE *pbEncoded, DWORD *pcbEncoded)
2489 BOOL ret;
2490 DWORD encodedSize, hashSize;
2492 TRACE("(%08Ix, %ld, %ld, %s, %p, %p, %p, %p, %p)\n", hCryptProv, dwKeySpec,
2493 dwCertEncodingType, debugstr_a(lpszStructType), pvStructInfo,
2494 pSignatureAlgorithm, pvHashAuxInfo, pbEncoded, pcbEncoded);
2496 ret = CryptEncodeObject(dwCertEncodingType, lpszStructType, pvStructInfo,
2497 NULL, &encodedSize);
2498 if (ret)
2500 PBYTE encoded = CryptMemAlloc(encodedSize);
2502 if (encoded)
2504 ret = CryptEncodeObject(dwCertEncodingType, lpszStructType,
2505 pvStructInfo, encoded, &encodedSize);
2506 if (ret)
2508 ret = CryptSignCertificate(hCryptProv, dwKeySpec,
2509 dwCertEncodingType, encoded, encodedSize, pSignatureAlgorithm,
2510 pvHashAuxInfo, NULL, &hashSize);
2511 if (ret)
2513 PBYTE hash = CryptMemAlloc(hashSize);
2515 if (hash)
2517 ret = CryptSignCertificate(hCryptProv, dwKeySpec,
2518 dwCertEncodingType, encoded, encodedSize,
2519 pSignatureAlgorithm, pvHashAuxInfo, hash, &hashSize);
2520 if (ret)
2522 CERT_SIGNED_CONTENT_INFO info = { { 0 } };
2524 info.ToBeSigned.cbData = encodedSize;
2525 info.ToBeSigned.pbData = encoded;
2526 info.SignatureAlgorithm = *pSignatureAlgorithm;
2527 info.Signature.cbData = hashSize;
2528 info.Signature.pbData = hash;
2529 info.Signature.cUnusedBits = 0;
2530 ret = CryptEncodeObject(dwCertEncodingType,
2531 X509_CERT, &info, pbEncoded, pcbEncoded);
2533 CryptMemFree(hash);
2535 else
2536 ret = FALSE;
2539 CryptMemFree(encoded);
2541 else
2542 ret = FALSE;
2544 return ret;
2547 BOOL WINAPI CryptVerifyCertificateSignature(HCRYPTPROV_LEGACY hCryptProv,
2548 DWORD dwCertEncodingType, const BYTE *pbEncoded, DWORD cbEncoded,
2549 PCERT_PUBLIC_KEY_INFO pPublicKey)
2551 CRYPT_DATA_BLOB blob = { cbEncoded, (BYTE *)pbEncoded };
2553 return CryptVerifyCertificateSignatureEx(hCryptProv, dwCertEncodingType,
2554 CRYPT_VERIFY_CERT_SIGN_SUBJECT_BLOB, &blob,
2555 CRYPT_VERIFY_CERT_SIGN_ISSUER_PUBKEY, pPublicKey, 0, NULL);
2558 static BOOL CRYPT_VerifySignature(HCRYPTPROV_LEGACY hCryptProv, DWORD dwCertEncodingType,
2559 CERT_PUBLIC_KEY_INFO *pubKeyInfo, const CERT_SIGNED_CONTENT_INFO *signedCert, const CRYPT_OID_INFO *info)
2561 BOOL ret;
2562 HCRYPTKEY key;
2563 ALG_ID pubKeyID, hashID;
2565 hashID = info->u.Algid;
2566 if (info->ExtraInfo.cbData >= sizeof(ALG_ID))
2567 pubKeyID = *(ALG_ID *)info->ExtraInfo.pbData;
2568 else
2569 pubKeyID = hashID;
2570 /* Load the default provider if necessary */
2571 if (!hCryptProv)
2572 hCryptProv = I_CryptGetDefaultCryptProv(hashID);
2573 ret = CryptImportPublicKeyInfoEx(hCryptProv, dwCertEncodingType,
2574 pubKeyInfo, pubKeyID, 0, NULL, &key);
2575 if (ret)
2577 HCRYPTHASH hash;
2579 ret = CryptCreateHash(hCryptProv, hashID, 0, 0, &hash);
2580 if (ret)
2582 ret = CryptHashData(hash, signedCert->ToBeSigned.pbData,
2583 signedCert->ToBeSigned.cbData, 0);
2584 if (ret)
2585 ret = CryptVerifySignatureW(hash, signedCert->Signature.pbData,
2586 signedCert->Signature.cbData, key, NULL, 0);
2587 CryptDestroyHash(hash);
2589 CryptDestroyKey(key);
2591 return ret;
2594 static BOOL CNG_CalcHash(const WCHAR *algorithm, const CERT_SIGNED_CONTENT_INFO *signedCert,
2595 BYTE **hash_value, DWORD *hash_len)
2597 BCRYPT_HASH_HANDLE hash = NULL;
2598 BCRYPT_ALG_HANDLE alg = NULL;
2599 NTSTATUS status;
2600 DWORD size;
2602 if ((status = BCryptOpenAlgorithmProvider(&alg, algorithm, NULL, 0)))
2603 goto done;
2605 if ((status = BCryptCreateHash(alg, &hash, NULL, 0, NULL, 0, 0)))
2606 goto done;
2608 if ((status = BCryptHashData(hash, signedCert->ToBeSigned.pbData, signedCert->ToBeSigned.cbData, 0)))
2609 goto done;
2611 if ((status = BCryptGetProperty(hash, BCRYPT_HASH_LENGTH, (BYTE *)hash_len, sizeof(*hash_len), &size, 0)))
2612 goto done;
2614 if (!(*hash_value = CryptMemAlloc(*hash_len)))
2616 status = STATUS_NO_MEMORY;
2617 goto done;
2620 if ((status = BCryptFinishHash(hash, *hash_value, *hash_len, 0)))
2622 CryptMemFree(*hash_value);
2623 goto done;
2626 done:
2627 if (hash) BCryptDestroyHash(hash);
2628 if (alg) BCryptCloseAlgorithmProvider(alg, 0);
2629 if (status) SetLastError(RtlNtStatusToDosError(status));
2630 return status == 0;
2633 static BOOL CNG_ImportECCPubKey(CERT_PUBLIC_KEY_INFO *pubKeyInfo, BCRYPT_KEY_HANDLE *key)
2635 DWORD blob_magic, ecckey_len, size;
2636 BCRYPT_ALG_HANDLE alg_handle;
2637 BCRYPT_ECCKEY_BLOB *ecckey;
2638 char **ecc_curve;
2639 NTSTATUS status;
2641 if (!pubKeyInfo->PublicKey.cbData)
2643 SetLastError(NTE_BAD_ALGID);
2644 return FALSE;
2647 if (pubKeyInfo->PublicKey.pbData[0] != 0x4)
2649 FIXME("Compressed ECC curves (%02x) not yet supported\n", pubKeyInfo->PublicKey.pbData[0]);
2650 SetLastError(NTE_BAD_ALGID);
2651 return FALSE;
2654 if (!CryptDecodeObjectEx(X509_ASN_ENCODING, X509_OBJECT_IDENTIFIER, pubKeyInfo->Algorithm.Parameters.pbData,
2655 pubKeyInfo->Algorithm.Parameters.cbData, CRYPT_DECODE_ALLOC_FLAG, NULL, &ecc_curve, &size))
2656 return FALSE;
2658 if (!strcmp(*ecc_curve, szOID_ECC_CURVE_P256))
2660 alg_handle = BCRYPT_ECDSA_P256_ALG_HANDLE;
2661 blob_magic = BCRYPT_ECDSA_PUBLIC_P256_MAGIC;
2663 else if (!strcmp(*ecc_curve, szOID_ECC_CURVE_P384))
2665 alg_handle = BCRYPT_ECDSA_P384_ALG_HANDLE;
2666 blob_magic = BCRYPT_ECDSA_PUBLIC_P384_MAGIC;
2668 else
2670 FIXME("Unsupported ecc curve type: %s\n", *ecc_curve);
2671 alg_handle = NULL;
2672 blob_magic = 0;
2674 LocalFree(ecc_curve);
2676 if (!alg_handle)
2678 SetLastError(NTE_BAD_ALGID);
2679 return FALSE;
2682 ecckey_len = sizeof(BCRYPT_ECCKEY_BLOB) + pubKeyInfo->PublicKey.cbData - 1;
2683 if (!(ecckey = CryptMemAlloc(ecckey_len)))
2684 return STATUS_NO_MEMORY;
2686 ecckey->dwMagic = blob_magic;
2687 ecckey->cbKey = (pubKeyInfo->PublicKey.cbData - 1) / 2;
2688 memcpy(ecckey + 1, pubKeyInfo->PublicKey.pbData + 1, pubKeyInfo->PublicKey.cbData - 1);
2690 status = BCryptImportKeyPair(alg_handle, NULL, BCRYPT_ECCPUBLIC_BLOB, key, (BYTE*)ecckey, ecckey_len, 0);
2691 CryptMemFree(ecckey);
2693 if (status) SetLastError(RtlNtStatusToDosError(status));
2694 return !status;
2697 static BOOL CNG_ImportRSAPubKey(CERT_PUBLIC_KEY_INFO *info, BCRYPT_KEY_HANDLE *key)
2699 DWORD size, modulus_len, i;
2700 BLOBHEADER *hdr;
2701 RSAPUBKEY *rsapubkey;
2702 BCRYPT_ALG_HANDLE alg_handle;
2703 BCRYPT_RSAKEY_BLOB *rsakey;
2704 BYTE *s, *d;
2705 NTSTATUS status;
2707 if (!info->PublicKey.cbData)
2709 SetLastError(NTE_BAD_ALGID);
2710 return FALSE;
2713 if (!CryptDecodeObjectEx(X509_ASN_ENCODING, RSA_CSP_PUBLICKEYBLOB, info->PublicKey.pbData,
2714 info->PublicKey.cbData, CRYPT_DECODE_ALLOC_FLAG, NULL, &hdr, &size))
2716 WARN("CryptDecodeObjectEx failed\n");
2717 return FALSE;
2720 if (hdr->aiKeyAlg == CALG_RSA_KEYX)
2721 alg_handle = BCRYPT_RSA_ALG_HANDLE;
2722 else if (hdr->aiKeyAlg == CALG_RSA_SIGN)
2723 alg_handle = BCRYPT_RSA_SIGN_ALG_HANDLE;
2724 else
2726 FIXME("Unsupported RSA algorithm: %#x\n", hdr->aiKeyAlg);
2727 LocalFree(hdr);
2728 SetLastError(NTE_BAD_ALGID);
2729 return FALSE;
2732 rsapubkey = (RSAPUBKEY *)(hdr + 1);
2734 modulus_len = size - sizeof(*hdr) - sizeof(*rsapubkey);
2735 if (modulus_len != rsapubkey->bitlen / 8)
2736 FIXME("RSA pubkey has wrong modulus_len %lu\n", modulus_len);
2738 size = sizeof(*rsakey) + sizeof(ULONG) + modulus_len;
2739 if (!(rsakey = CryptMemAlloc(size)))
2740 return STATUS_NO_MEMORY;
2742 rsakey->Magic = BCRYPT_RSAPUBLIC_MAGIC;
2743 rsakey->BitLength = rsapubkey->bitlen;
2744 rsakey->cbPublicExp = sizeof(ULONG);
2745 rsakey->cbModulus = modulus_len;
2746 rsakey->cbPrime1 = 0;
2747 rsakey->cbPrime2 = 0;
2749 d = (BYTE *)(rsakey + 1);
2750 /* According to MSDN modulus and pubexp are in LE while
2751 * BCRYPT_RSAKEY_BLOB is supposed to have them in BE format */
2752 *(ULONG *)d = RtlUlongByteSwap(rsapubkey->pubexp);
2753 d += sizeof(ULONG);
2754 s = (BYTE *)(rsapubkey + 1);
2755 for (i = 0; i < modulus_len; i++)
2756 d[i] = s[modulus_len - i - 1];
2758 status = BCryptImportKeyPair(alg_handle, NULL, BCRYPT_RSAPUBLIC_BLOB, key, (BYTE *)rsakey, size, 0);
2759 CryptMemFree(rsakey);
2761 LocalFree(hdr);
2762 if (status) SetLastError(RtlNtStatusToDosError(status));
2763 return !status;
2766 BOOL CNG_ImportPubKey(CERT_PUBLIC_KEY_INFO *pubKeyInfo, BCRYPT_KEY_HANDLE *key)
2768 if (!strcmp(pubKeyInfo->Algorithm.pszObjId, szOID_ECC_PUBLIC_KEY))
2769 return CNG_ImportECCPubKey(pubKeyInfo, key);
2771 if (!strcmp(pubKeyInfo->Algorithm.pszObjId, szOID_RSA_RSA))
2772 return CNG_ImportRSAPubKey(pubKeyInfo, key);
2774 FIXME("Unsupported public key type: %s\n", debugstr_a(pubKeyInfo->Algorithm.pszObjId));
2775 SetLastError(NTE_BAD_ALGID);
2776 return FALSE;
2779 static BOOL CNG_PrepareSignatureECC(BYTE *encoded_sig, DWORD encoded_size, BYTE **sig_value, DWORD *sig_len)
2781 CERT_ECC_SIGNATURE *ecc_sig;
2782 DWORD size;
2783 int i;
2785 if (!CryptDecodeObjectEx(X509_ASN_ENCODING, X509_ECC_SIGNATURE, encoded_sig, encoded_size,
2786 CRYPT_DECODE_ALLOC_FLAG, NULL, &ecc_sig, &size))
2787 return FALSE;
2789 if (!ecc_sig->r.cbData || !ecc_sig->s.cbData)
2791 LocalFree(ecc_sig);
2792 SetLastError(ERROR_INVALID_DATA);
2793 return FALSE;
2796 *sig_len = ecc_sig->r.cbData + ecc_sig->s.cbData;
2797 if (!(*sig_value = CryptMemAlloc(*sig_len)))
2799 LocalFree(ecc_sig);
2800 SetLastError(ERROR_OUTOFMEMORY);
2801 return FALSE;
2804 for (i = 0; i < ecc_sig->r.cbData; i++)
2805 (*sig_value)[i] = ecc_sig->r.pbData[ecc_sig->r.cbData - i - 1];
2806 for (i = 0; i < ecc_sig->s.cbData; i++)
2807 (*sig_value)[ecc_sig->r.cbData + i] = ecc_sig->s.pbData[ecc_sig->s.cbData - i - 1];
2809 LocalFree(ecc_sig);
2810 return TRUE;
2813 static BOOL CNG_PrepareSignature(CERT_PUBLIC_KEY_INFO *pubKeyInfo, const CERT_SIGNED_CONTENT_INFO *signedCert,
2814 BYTE **sig_value, DWORD *sig_len)
2816 BYTE *encoded_sig;
2817 BOOL ret = FALSE;
2818 int i;
2820 if (!signedCert->Signature.cbData)
2822 SetLastError(ERROR_INVALID_DATA);
2823 return FALSE;
2826 if (!(encoded_sig = CryptMemAlloc(signedCert->Signature.cbData)))
2828 SetLastError(ERROR_OUTOFMEMORY);
2829 return FALSE;
2832 for (i = 0; i < signedCert->Signature.cbData; i++)
2833 encoded_sig[i] = signedCert->Signature.pbData[signedCert->Signature.cbData - i - 1];
2835 if (!strcmp(pubKeyInfo->Algorithm.pszObjId, szOID_ECC_PUBLIC_KEY))
2836 ret = CNG_PrepareSignatureECC(encoded_sig, signedCert->Signature.cbData, sig_value, sig_len);
2837 else
2839 FIXME("Unsupported public key type: %s\n", debugstr_a(pubKeyInfo->Algorithm.pszObjId));
2840 SetLastError(NTE_BAD_ALGID);
2843 CryptMemFree(encoded_sig);
2844 return ret;
2847 static BOOL CNG_VerifySignature(HCRYPTPROV_LEGACY hCryptProv, DWORD dwCertEncodingType,
2848 CERT_PUBLIC_KEY_INFO *pubKeyInfo, const CERT_SIGNED_CONTENT_INFO *signedCert, const CRYPT_OID_INFO *info)
2850 BCRYPT_KEY_HANDLE key = NULL;
2851 BYTE *hash_value = NULL, *sig_value;
2852 DWORD hash_len, sig_len;
2853 NTSTATUS status;
2854 BOOL ret;
2856 ret = CNG_ImportPubKey(pubKeyInfo, &key);
2857 if (ret)
2859 ret = CNG_CalcHash(info->pwszCNGAlgid, signedCert, &hash_value, &hash_len);
2860 if (ret)
2862 ret = CNG_PrepareSignature(pubKeyInfo, signedCert, &sig_value, &sig_len);
2863 if (ret)
2865 status = BCryptVerifySignature(key, NULL, hash_value, hash_len, sig_value, sig_len, 0);
2866 if (status)
2868 FIXME("Failed to verify signature: %08lx\n", status);
2869 SetLastError(RtlNtStatusToDosError(status));
2870 ret = FALSE;
2872 CryptMemFree(sig_value);
2874 CryptMemFree(hash_value);
2876 BCryptDestroyKey(key);
2879 return ret;
2882 static BOOL CRYPT_VerifyCertSignatureFromPublicKeyInfo(HCRYPTPROV_LEGACY hCryptProv, DWORD dwCertEncodingType,
2883 CERT_PUBLIC_KEY_INFO *pubKeyInfo, const CERT_SIGNED_CONTENT_INFO *signedCert)
2885 CCRYPT_OID_INFO *info;
2887 info = CryptFindOIDInfo(CRYPT_OID_INFO_OID_KEY, signedCert->SignatureAlgorithm.pszObjId, 0);
2888 if (!info || info->dwGroupId != CRYPT_SIGN_ALG_OID_GROUP_ID)
2890 SetLastError(NTE_BAD_ALGID);
2891 return FALSE;
2894 if (info->u.Algid == CALG_OID_INFO_CNG_ONLY)
2895 return CNG_VerifySignature(hCryptProv, dwCertEncodingType, pubKeyInfo, signedCert, info);
2896 else
2897 return CRYPT_VerifySignature(hCryptProv, dwCertEncodingType, pubKeyInfo, signedCert, info);
2900 BOOL WINAPI CryptVerifyCertificateSignatureEx(HCRYPTPROV_LEGACY hCryptProv,
2901 DWORD dwCertEncodingType, DWORD dwSubjectType, void *pvSubject,
2902 DWORD dwIssuerType, void *pvIssuer, DWORD dwFlags, void *pvReserved)
2904 BOOL ret = TRUE;
2905 CRYPT_DATA_BLOB subjectBlob;
2907 TRACE("(%08Ix, %ld, %ld, %p, %ld, %p, %08lx, %p)\n", hCryptProv,
2908 dwCertEncodingType, dwSubjectType, pvSubject, dwIssuerType, pvIssuer,
2909 dwFlags, pvReserved);
2911 switch (dwSubjectType)
2913 case CRYPT_VERIFY_CERT_SIGN_SUBJECT_BLOB:
2915 PCRYPT_DATA_BLOB blob = pvSubject;
2917 subjectBlob.pbData = blob->pbData;
2918 subjectBlob.cbData = blob->cbData;
2919 break;
2921 case CRYPT_VERIFY_CERT_SIGN_SUBJECT_CERT:
2923 PCERT_CONTEXT context = pvSubject;
2925 subjectBlob.pbData = context->pbCertEncoded;
2926 subjectBlob.cbData = context->cbCertEncoded;
2927 break;
2929 case CRYPT_VERIFY_CERT_SIGN_SUBJECT_CRL:
2931 PCRL_CONTEXT context = pvSubject;
2933 subjectBlob.pbData = context->pbCrlEncoded;
2934 subjectBlob.cbData = context->cbCrlEncoded;
2935 break;
2937 default:
2938 SetLastError(E_INVALIDARG);
2939 ret = FALSE;
2942 if (ret)
2944 PCERT_SIGNED_CONTENT_INFO signedCert = NULL;
2945 DWORD size = 0;
2947 ret = CryptDecodeObjectEx(dwCertEncodingType, X509_CERT,
2948 subjectBlob.pbData, subjectBlob.cbData,
2949 CRYPT_DECODE_ALLOC_FLAG | CRYPT_DECODE_NOCOPY_FLAG, NULL,
2950 &signedCert, &size);
2951 if (ret)
2953 switch (dwIssuerType)
2955 case CRYPT_VERIFY_CERT_SIGN_ISSUER_PUBKEY:
2956 ret = CRYPT_VerifyCertSignatureFromPublicKeyInfo(hCryptProv,
2957 dwCertEncodingType, pvIssuer,
2958 signedCert);
2959 break;
2960 case CRYPT_VERIFY_CERT_SIGN_ISSUER_CERT:
2961 ret = CRYPT_VerifyCertSignatureFromPublicKeyInfo(hCryptProv,
2962 dwCertEncodingType,
2963 &((PCCERT_CONTEXT)pvIssuer)->pCertInfo->SubjectPublicKeyInfo,
2964 signedCert);
2965 break;
2966 case CRYPT_VERIFY_CERT_SIGN_ISSUER_CHAIN:
2967 FIXME("CRYPT_VERIFY_CERT_SIGN_ISSUER_CHAIN: stub\n");
2968 ret = FALSE;
2969 break;
2970 case CRYPT_VERIFY_CERT_SIGN_ISSUER_NULL:
2971 if (pvIssuer)
2973 SetLastError(E_INVALIDARG);
2974 ret = FALSE;
2976 else
2978 FIXME("unimplemented for NULL signer\n");
2979 SetLastError(E_INVALIDARG);
2980 ret = FALSE;
2982 break;
2983 default:
2984 SetLastError(E_INVALIDARG);
2985 ret = FALSE;
2987 LocalFree(signedCert);
2990 return ret;
2993 BOOL WINAPI CertGetIntendedKeyUsage(DWORD dwCertEncodingType,
2994 PCERT_INFO pCertInfo, BYTE *pbKeyUsage, DWORD cbKeyUsage)
2996 PCERT_EXTENSION ext;
2997 BOOL ret = FALSE;
2999 TRACE("(%08lx, %p, %p, %ld)\n", dwCertEncodingType, pCertInfo, pbKeyUsage,
3000 cbKeyUsage);
3002 ext = CertFindExtension(szOID_KEY_USAGE, pCertInfo->cExtension,
3003 pCertInfo->rgExtension);
3004 if (ext)
3006 CRYPT_BIT_BLOB usage;
3007 DWORD size = sizeof(usage);
3009 ret = CryptDecodeObjectEx(dwCertEncodingType, X509_BITS,
3010 ext->Value.pbData, ext->Value.cbData, CRYPT_DECODE_NOCOPY_FLAG, NULL,
3011 &usage, &size);
3012 if (ret)
3014 if (cbKeyUsage < usage.cbData)
3015 ret = FALSE;
3016 else
3018 memcpy(pbKeyUsage, usage.pbData, usage.cbData);
3019 if (cbKeyUsage > usage.cbData)
3020 memset(pbKeyUsage + usage.cbData, 0,
3021 cbKeyUsage - usage.cbData);
3025 else
3026 SetLastError(0);
3027 return ret;
3030 BOOL WINAPI CertGetEnhancedKeyUsage(PCCERT_CONTEXT pCertContext, DWORD dwFlags,
3031 PCERT_ENHKEY_USAGE pUsage, DWORD *pcbUsage)
3033 PCERT_ENHKEY_USAGE usage = NULL;
3034 DWORD bytesNeeded;
3035 BOOL ret = TRUE;
3037 if (!pCertContext || !pcbUsage)
3039 SetLastError(ERROR_INVALID_PARAMETER);
3040 return FALSE;
3043 TRACE("(%p, %08lx, %p, %ld)\n", pCertContext, dwFlags, pUsage, *pcbUsage);
3045 if (!(dwFlags & CERT_FIND_EXT_ONLY_ENHKEY_USAGE_FLAG))
3047 DWORD propSize = 0;
3049 if (CertGetCertificateContextProperty(pCertContext,
3050 CERT_ENHKEY_USAGE_PROP_ID, NULL, &propSize))
3052 LPBYTE buf = CryptMemAlloc(propSize);
3054 if (buf)
3056 if (CertGetCertificateContextProperty(pCertContext,
3057 CERT_ENHKEY_USAGE_PROP_ID, buf, &propSize))
3059 ret = CryptDecodeObjectEx(pCertContext->dwCertEncodingType,
3060 X509_ENHANCED_KEY_USAGE, buf, propSize,
3061 CRYPT_ENCODE_ALLOC_FLAG, NULL, &usage, &bytesNeeded);
3063 CryptMemFree(buf);
3067 if (!usage && !(dwFlags & CERT_FIND_PROP_ONLY_ENHKEY_USAGE_FLAG))
3069 PCERT_EXTENSION ext = CertFindExtension(szOID_ENHANCED_KEY_USAGE,
3070 pCertContext->pCertInfo->cExtension,
3071 pCertContext->pCertInfo->rgExtension);
3073 if (ext)
3075 ret = CryptDecodeObjectEx(pCertContext->dwCertEncodingType,
3076 X509_ENHANCED_KEY_USAGE, ext->Value.pbData, ext->Value.cbData,
3077 CRYPT_ENCODE_ALLOC_FLAG, NULL, &usage, &bytesNeeded);
3080 if (!usage)
3082 /* If a particular location is specified, this should fail. Otherwise
3083 * it should succeed with an empty usage. (This is true on Win2k and
3084 * later, which we emulate.)
3086 if (dwFlags)
3088 SetLastError(CRYPT_E_NOT_FOUND);
3089 ret = FALSE;
3091 else
3092 bytesNeeded = sizeof(CERT_ENHKEY_USAGE);
3095 if (ret)
3097 if (!pUsage)
3098 *pcbUsage = bytesNeeded;
3099 else if (*pcbUsage < bytesNeeded)
3101 SetLastError(ERROR_MORE_DATA);
3102 *pcbUsage = bytesNeeded;
3103 ret = FALSE;
3105 else
3107 *pcbUsage = bytesNeeded;
3108 if (usage)
3110 DWORD i;
3111 LPSTR nextOID = (LPSTR)((LPBYTE)pUsage +
3112 sizeof(CERT_ENHKEY_USAGE) +
3113 usage->cUsageIdentifier * sizeof(LPSTR));
3115 pUsage->cUsageIdentifier = usage->cUsageIdentifier;
3116 pUsage->rgpszUsageIdentifier = (LPSTR *)((LPBYTE)pUsage +
3117 sizeof(CERT_ENHKEY_USAGE));
3118 for (i = 0; i < usage->cUsageIdentifier; i++)
3120 pUsage->rgpszUsageIdentifier[i] = nextOID;
3121 strcpy(nextOID, usage->rgpszUsageIdentifier[i]);
3122 nextOID += strlen(nextOID) + 1;
3125 else
3126 pUsage->cUsageIdentifier = 0;
3129 if (usage)
3130 LocalFree(usage);
3131 TRACE("returning %d\n", ret);
3132 return ret;
3135 BOOL WINAPI CertSetEnhancedKeyUsage(PCCERT_CONTEXT pCertContext,
3136 PCERT_ENHKEY_USAGE pUsage)
3138 BOOL ret;
3140 TRACE("(%p, %p)\n", pCertContext, pUsage);
3142 if (pUsage)
3144 CRYPT_DATA_BLOB blob = { 0, NULL };
3146 ret = CryptEncodeObjectEx(X509_ASN_ENCODING, X509_ENHANCED_KEY_USAGE,
3147 pUsage, CRYPT_ENCODE_ALLOC_FLAG, NULL, &blob.pbData, &blob.cbData);
3148 if (ret)
3150 ret = CertSetCertificateContextProperty(pCertContext,
3151 CERT_ENHKEY_USAGE_PROP_ID, 0, &blob);
3152 LocalFree(blob.pbData);
3155 else
3156 ret = CertSetCertificateContextProperty(pCertContext,
3157 CERT_ENHKEY_USAGE_PROP_ID, 0, NULL);
3158 return ret;
3161 BOOL WINAPI CertAddEnhancedKeyUsageIdentifier(PCCERT_CONTEXT pCertContext,
3162 LPCSTR pszUsageIdentifier)
3164 BOOL ret;
3165 DWORD size;
3167 TRACE("(%p, %s)\n", pCertContext, debugstr_a(pszUsageIdentifier));
3169 if (CertGetEnhancedKeyUsage(pCertContext,
3170 CERT_FIND_PROP_ONLY_ENHKEY_USAGE_FLAG, NULL, &size))
3172 PCERT_ENHKEY_USAGE usage = CryptMemAlloc(size);
3174 if (usage)
3176 ret = CertGetEnhancedKeyUsage(pCertContext,
3177 CERT_FIND_PROP_ONLY_ENHKEY_USAGE_FLAG, usage, &size);
3178 if (ret)
3180 DWORD i;
3181 BOOL exists = FALSE;
3183 /* Make sure usage doesn't already exist */
3184 for (i = 0; !exists && i < usage->cUsageIdentifier; i++)
3186 if (!strcmp(usage->rgpszUsageIdentifier[i],
3187 pszUsageIdentifier))
3188 exists = TRUE;
3190 if (!exists)
3192 PCERT_ENHKEY_USAGE newUsage = CryptMemAlloc(size +
3193 sizeof(LPSTR) + strlen(pszUsageIdentifier) + 1);
3195 if (newUsage)
3197 LPSTR nextOID;
3199 newUsage->rgpszUsageIdentifier = (LPSTR *)
3200 ((LPBYTE)newUsage + sizeof(CERT_ENHKEY_USAGE));
3201 nextOID = (LPSTR)((LPBYTE)newUsage->rgpszUsageIdentifier
3202 + (usage->cUsageIdentifier + 1) * sizeof(LPSTR));
3203 for (i = 0; i < usage->cUsageIdentifier; i++)
3205 newUsage->rgpszUsageIdentifier[i] = nextOID;
3206 strcpy(nextOID, usage->rgpszUsageIdentifier[i]);
3207 nextOID += strlen(nextOID) + 1;
3209 newUsage->rgpszUsageIdentifier[i] = nextOID;
3210 strcpy(nextOID, pszUsageIdentifier);
3211 newUsage->cUsageIdentifier = i + 1;
3212 ret = CertSetEnhancedKeyUsage(pCertContext, newUsage);
3213 CryptMemFree(newUsage);
3215 else
3216 ret = FALSE;
3219 CryptMemFree(usage);
3221 else
3222 ret = FALSE;
3224 else
3226 PCERT_ENHKEY_USAGE usage = CryptMemAlloc(sizeof(CERT_ENHKEY_USAGE) +
3227 sizeof(LPSTR) + strlen(pszUsageIdentifier) + 1);
3229 if (usage)
3231 usage->rgpszUsageIdentifier =
3232 (LPSTR *)((LPBYTE)usage + sizeof(CERT_ENHKEY_USAGE));
3233 usage->rgpszUsageIdentifier[0] = (LPSTR)((LPBYTE)usage +
3234 sizeof(CERT_ENHKEY_USAGE) + sizeof(LPSTR));
3235 strcpy(usage->rgpszUsageIdentifier[0], pszUsageIdentifier);
3236 usage->cUsageIdentifier = 1;
3237 ret = CertSetEnhancedKeyUsage(pCertContext, usage);
3238 CryptMemFree(usage);
3240 else
3241 ret = FALSE;
3243 return ret;
3246 BOOL WINAPI CertRemoveEnhancedKeyUsageIdentifier(PCCERT_CONTEXT pCertContext,
3247 LPCSTR pszUsageIdentifier)
3249 BOOL ret;
3250 DWORD size;
3251 CERT_ENHKEY_USAGE usage;
3253 TRACE("(%p, %s)\n", pCertContext, debugstr_a(pszUsageIdentifier));
3255 size = sizeof(usage);
3256 ret = CertGetEnhancedKeyUsage(pCertContext,
3257 CERT_FIND_PROP_ONLY_ENHKEY_USAGE_FLAG, &usage, &size);
3258 if (!ret && GetLastError() == ERROR_MORE_DATA)
3260 PCERT_ENHKEY_USAGE pUsage = CryptMemAlloc(size);
3262 if (pUsage)
3264 ret = CertGetEnhancedKeyUsage(pCertContext,
3265 CERT_FIND_PROP_ONLY_ENHKEY_USAGE_FLAG, pUsage, &size);
3266 if (ret)
3268 if (pUsage->cUsageIdentifier)
3270 DWORD i;
3271 BOOL found = FALSE;
3273 for (i = 0; i < pUsage->cUsageIdentifier; i++)
3275 if (!strcmp(pUsage->rgpszUsageIdentifier[i],
3276 pszUsageIdentifier))
3277 found = TRUE;
3278 if (found && i < pUsage->cUsageIdentifier - 1)
3279 pUsage->rgpszUsageIdentifier[i] =
3280 pUsage->rgpszUsageIdentifier[i + 1];
3282 pUsage->cUsageIdentifier--;
3283 /* Remove the usage if it's empty */
3284 if (pUsage->cUsageIdentifier)
3285 ret = CertSetEnhancedKeyUsage(pCertContext, pUsage);
3286 else
3287 ret = CertSetEnhancedKeyUsage(pCertContext, NULL);
3290 CryptMemFree(pUsage);
3292 else
3293 ret = FALSE;
3295 else
3297 /* it fit in an empty usage, therefore there's nothing to remove */
3298 ret = TRUE;
3300 return ret;
3303 struct BitField
3305 DWORD cIndexes;
3306 DWORD *indexes;
3309 #define BITS_PER_DWORD (sizeof(DWORD) * 8)
3311 static void CRYPT_SetBitInField(struct BitField *field, DWORD bit)
3313 DWORD indexIndex = bit / BITS_PER_DWORD;
3315 if (indexIndex + 1 > field->cIndexes)
3317 if (field->cIndexes)
3318 field->indexes = CryptMemRealloc(field->indexes,
3319 (indexIndex + 1) * sizeof(DWORD));
3320 else
3321 field->indexes = CryptMemAlloc(sizeof(DWORD));
3322 if (field->indexes)
3324 field->indexes[indexIndex] = 0;
3325 field->cIndexes = indexIndex + 1;
3328 if (field->indexes)
3329 field->indexes[indexIndex] |= 1 << (bit % BITS_PER_DWORD);
3332 static BOOL CRYPT_IsBitInFieldSet(const struct BitField *field, DWORD bit)
3334 BOOL set;
3335 DWORD indexIndex = bit / BITS_PER_DWORD;
3337 assert(field->cIndexes);
3338 set = field->indexes[indexIndex] & (1 << (bit % BITS_PER_DWORD));
3339 return set;
3342 BOOL WINAPI CertGetValidUsages(DWORD cCerts, PCCERT_CONTEXT *rghCerts,
3343 int *cNumOIDs, LPSTR *rghOIDs, DWORD *pcbOIDs)
3345 BOOL ret = TRUE;
3346 DWORD i, cbOIDs = 0;
3347 BOOL allUsagesValid = TRUE;
3348 CERT_ENHKEY_USAGE validUsages = { 0, NULL };
3350 TRACE("(%ld, %p, %d, %p, %ld)\n", cCerts, rghCerts, *cNumOIDs,
3351 rghOIDs, *pcbOIDs);
3353 for (i = 0; i < cCerts; i++)
3355 CERT_ENHKEY_USAGE usage;
3356 DWORD size = sizeof(usage);
3358 ret = CertGetEnhancedKeyUsage(rghCerts[i], 0, &usage, &size);
3359 /* Success is deliberately ignored: it implies all usages are valid */
3360 if (!ret && GetLastError() == ERROR_MORE_DATA)
3362 PCERT_ENHKEY_USAGE pUsage = CryptMemAlloc(size);
3364 allUsagesValid = FALSE;
3365 if (pUsage)
3367 ret = CertGetEnhancedKeyUsage(rghCerts[i], 0, pUsage, &size);
3368 if (ret)
3370 if (!validUsages.cUsageIdentifier)
3372 DWORD j;
3374 cbOIDs = pUsage->cUsageIdentifier * sizeof(LPSTR);
3375 validUsages.cUsageIdentifier = pUsage->cUsageIdentifier;
3376 for (j = 0; j < validUsages.cUsageIdentifier; j++)
3377 cbOIDs += lstrlenA(pUsage->rgpszUsageIdentifier[j])
3378 + 1;
3379 validUsages.rgpszUsageIdentifier =
3380 CryptMemAlloc(cbOIDs);
3381 if (validUsages.rgpszUsageIdentifier)
3383 LPSTR nextOID = (LPSTR)
3384 ((LPBYTE)validUsages.rgpszUsageIdentifier +
3385 validUsages.cUsageIdentifier * sizeof(LPSTR));
3387 for (j = 0; j < validUsages.cUsageIdentifier; j++)
3389 validUsages.rgpszUsageIdentifier[j] = nextOID;
3390 lstrcpyA(validUsages.rgpszUsageIdentifier[j],
3391 pUsage->rgpszUsageIdentifier[j]);
3392 nextOID += lstrlenA(nextOID) + 1;
3396 else
3398 struct BitField validIndexes = { 0, NULL };
3399 DWORD j, k, numRemoved = 0;
3401 /* Merge: build a bitmap of all the indexes of
3402 * validUsages.rgpszUsageIdentifier that are in pUsage.
3404 for (j = 0; j < pUsage->cUsageIdentifier; j++)
3406 for (k = 0; k < validUsages.cUsageIdentifier; k++)
3408 if (!strcmp(pUsage->rgpszUsageIdentifier[j],
3409 validUsages.rgpszUsageIdentifier[k]))
3411 CRYPT_SetBitInField(&validIndexes, k);
3412 break;
3416 /* Merge by removing from validUsages those that are
3417 * not in the bitmap.
3419 for (j = 0; j < validUsages.cUsageIdentifier; j++)
3421 if (!CRYPT_IsBitInFieldSet(&validIndexes, j))
3423 if (j < validUsages.cUsageIdentifier - 1)
3425 memmove(&validUsages.rgpszUsageIdentifier[j],
3426 &validUsages.rgpszUsageIdentifier[j +
3427 numRemoved + 1],
3428 (validUsages.cUsageIdentifier - numRemoved
3429 - j - 1) * sizeof(LPSTR));
3430 cbOIDs -= lstrlenA(
3431 validUsages.rgpszUsageIdentifier[j]) + 1 +
3432 sizeof(LPSTR);
3433 validUsages.cUsageIdentifier--;
3434 numRemoved++;
3436 else
3437 validUsages.cUsageIdentifier--;
3440 CryptMemFree(validIndexes.indexes);
3443 CryptMemFree(pUsage);
3447 ret = TRUE;
3448 if (allUsagesValid)
3450 *cNumOIDs = -1;
3451 *pcbOIDs = 0;
3453 else
3455 *cNumOIDs = validUsages.cUsageIdentifier;
3456 if (!rghOIDs)
3457 *pcbOIDs = cbOIDs;
3458 else if (*pcbOIDs < cbOIDs)
3460 *pcbOIDs = cbOIDs;
3461 SetLastError(ERROR_MORE_DATA);
3462 ret = FALSE;
3464 else
3466 LPSTR nextOID = (LPSTR)((LPBYTE)rghOIDs +
3467 validUsages.cUsageIdentifier * sizeof(LPSTR));
3469 *pcbOIDs = cbOIDs;
3470 for (i = 0; i < validUsages.cUsageIdentifier; i++)
3472 rghOIDs[i] = nextOID;
3473 lstrcpyA(nextOID, validUsages.rgpszUsageIdentifier[i]);
3474 nextOID += lstrlenA(nextOID) + 1;
3478 CryptMemFree(validUsages.rgpszUsageIdentifier);
3479 TRACE("cNumOIDs: %d\n", *cNumOIDs);
3480 TRACE("returning %d\n", ret);
3481 return ret;
3484 /* Sets the CERT_KEY_PROV_INFO_PROP_ID property of context from pInfo, or, if
3485 * pInfo is NULL, from the attributes of hProv.
3487 static void CertContext_SetKeyProvInfo(PCCERT_CONTEXT context,
3488 const CRYPT_KEY_PROV_INFO *pInfo, HCRYPTPROV hProv)
3490 CRYPT_KEY_PROV_INFO info = { 0 };
3491 BOOL ret;
3493 if (!pInfo)
3495 DWORD size;
3496 int len;
3498 ret = CryptGetProvParam(hProv, PP_CONTAINER, NULL, &size, 0);
3499 if (ret)
3501 LPSTR szContainer = CryptMemAlloc(size);
3503 if (szContainer)
3505 ret = CryptGetProvParam(hProv, PP_CONTAINER,
3506 (BYTE *)szContainer, &size, 0);
3507 if (ret)
3509 len = MultiByteToWideChar(CP_ACP, 0, szContainer, -1,
3510 NULL, 0);
3511 if (len)
3513 info.pwszContainerName = CryptMemAlloc(len *
3514 sizeof(WCHAR));
3515 MultiByteToWideChar(CP_ACP, 0, szContainer, -1,
3516 info.pwszContainerName, len);
3519 CryptMemFree(szContainer);
3522 ret = CryptGetProvParam(hProv, PP_NAME, NULL, &size, 0);
3523 if (ret)
3525 LPSTR szProvider = CryptMemAlloc(size);
3527 if (szProvider)
3529 ret = CryptGetProvParam(hProv, PP_NAME, (BYTE *)szProvider,
3530 &size, 0);
3531 if (ret)
3533 len = MultiByteToWideChar(CP_ACP, 0, szProvider, -1,
3534 NULL, 0);
3535 if (len)
3537 info.pwszProvName = CryptMemAlloc(len *
3538 sizeof(WCHAR));
3539 MultiByteToWideChar(CP_ACP, 0, szProvider, -1,
3540 info.pwszProvName, len);
3543 CryptMemFree(szProvider);
3546 /* in case no CRYPT_KEY_PROV_INFO given,
3547 * we always use AT_SIGNATURE key spec
3549 info.dwKeySpec = AT_SIGNATURE;
3550 size = sizeof(info.dwProvType);
3551 ret = CryptGetProvParam(hProv, PP_PROVTYPE, (LPBYTE)&info.dwProvType,
3552 &size, 0);
3553 if (!ret)
3554 info.dwProvType = PROV_RSA_FULL;
3555 pInfo = &info;
3558 CertSetCertificateContextProperty(context, CERT_KEY_PROV_INFO_PROP_ID,
3559 0, pInfo);
3561 if (pInfo == &info)
3563 CryptMemFree(info.pwszContainerName);
3564 CryptMemFree(info.pwszProvName);
3568 /* Creates a signed certificate context from the unsigned, encoded certificate
3569 * in blob, using the crypto provider hProv and the signature algorithm sigAlgo.
3571 static PCCERT_CONTEXT CRYPT_CreateSignedCert(const CRYPT_DER_BLOB *blob,
3572 HCRYPTPROV hProv, DWORD dwKeySpec, PCRYPT_ALGORITHM_IDENTIFIER sigAlgo)
3574 PCCERT_CONTEXT context = NULL;
3575 BOOL ret;
3576 DWORD sigSize = 0;
3578 ret = CryptSignCertificate(hProv, dwKeySpec, X509_ASN_ENCODING,
3579 blob->pbData, blob->cbData, sigAlgo, NULL, NULL, &sigSize);
3580 if (ret)
3582 LPBYTE sig = CryptMemAlloc(sigSize);
3584 ret = CryptSignCertificate(hProv, dwKeySpec, X509_ASN_ENCODING,
3585 blob->pbData, blob->cbData, sigAlgo, NULL, sig, &sigSize);
3586 if (ret)
3588 CERT_SIGNED_CONTENT_INFO signedInfo;
3589 BYTE *encodedSignedCert = NULL;
3590 DWORD encodedSignedCertSize = 0;
3592 signedInfo.ToBeSigned.cbData = blob->cbData;
3593 signedInfo.ToBeSigned.pbData = blob->pbData;
3594 signedInfo.SignatureAlgorithm = *sigAlgo;
3595 signedInfo.Signature.cbData = sigSize;
3596 signedInfo.Signature.pbData = sig;
3597 signedInfo.Signature.cUnusedBits = 0;
3598 ret = CryptEncodeObjectEx(X509_ASN_ENCODING, X509_CERT,
3599 &signedInfo, CRYPT_ENCODE_ALLOC_FLAG, NULL,
3600 &encodedSignedCert, &encodedSignedCertSize);
3601 if (ret)
3603 context = CertCreateCertificateContext(X509_ASN_ENCODING,
3604 encodedSignedCert, encodedSignedCertSize);
3605 LocalFree(encodedSignedCert);
3608 CryptMemFree(sig);
3610 return context;
3613 /* Copies data from the parameters into info, where:
3614 * pSerialNumber: The serial number. Must not be NULL.
3615 * pSubjectIssuerBlob: Specifies both the subject and issuer for info.
3616 * Must not be NULL
3617 * pSignatureAlgorithm: Optional.
3618 * pStartTime: The starting time of the certificate. If NULL, the current
3619 * system time is used.
3620 * pEndTime: The ending time of the certificate. If NULL, one year past the
3621 * starting time is used.
3622 * pubKey: The public key of the certificate. Must not be NULL.
3623 * pExtensions: Extensions to be included with the certificate. Optional.
3625 static void CRYPT_MakeCertInfo(PCERT_INFO info, const CRYPT_DATA_BLOB *pSerialNumber,
3626 const CERT_NAME_BLOB *pSubjectIssuerBlob,
3627 const CRYPT_ALGORITHM_IDENTIFIER *pSignatureAlgorithm, const SYSTEMTIME *pStartTime,
3628 const SYSTEMTIME *pEndTime, const CERT_PUBLIC_KEY_INFO *pubKey,
3629 const CERT_EXTENSIONS *pExtensions)
3631 static CHAR oid[] = szOID_RSA_SHA1RSA;
3633 assert(info);
3634 assert(pSerialNumber);
3635 assert(pSubjectIssuerBlob);
3636 assert(pubKey);
3638 if (pExtensions && pExtensions->cExtension)
3639 info->dwVersion = CERT_V3;
3640 else
3641 info->dwVersion = CERT_V1;
3642 info->SerialNumber.cbData = pSerialNumber->cbData;
3643 info->SerialNumber.pbData = pSerialNumber->pbData;
3644 if (pSignatureAlgorithm)
3645 info->SignatureAlgorithm = *pSignatureAlgorithm;
3646 else
3648 info->SignatureAlgorithm.pszObjId = oid;
3649 info->SignatureAlgorithm.Parameters.cbData = 0;
3650 info->SignatureAlgorithm.Parameters.pbData = NULL;
3652 info->Issuer.cbData = pSubjectIssuerBlob->cbData;
3653 info->Issuer.pbData = pSubjectIssuerBlob->pbData;
3654 if (pStartTime)
3655 SystemTimeToFileTime(pStartTime, &info->NotBefore);
3656 else
3657 GetSystemTimeAsFileTime(&info->NotBefore);
3658 if (pEndTime)
3659 SystemTimeToFileTime(pEndTime, &info->NotAfter);
3660 else
3662 SYSTEMTIME endTime;
3664 if (FileTimeToSystemTime(&info->NotBefore, &endTime))
3666 endTime.wYear++;
3667 SystemTimeToFileTime(&endTime, &info->NotAfter);
3670 info->Subject.cbData = pSubjectIssuerBlob->cbData;
3671 info->Subject.pbData = pSubjectIssuerBlob->pbData;
3672 info->SubjectPublicKeyInfo = *pubKey;
3673 if (pExtensions)
3675 info->cExtension = pExtensions->cExtension;
3676 info->rgExtension = pExtensions->rgExtension;
3678 else
3680 info->cExtension = 0;
3681 info->rgExtension = NULL;
3685 typedef RPC_STATUS (RPC_ENTRY *UuidCreateFunc)(UUID *);
3686 typedef RPC_STATUS (RPC_ENTRY *UuidToStringFunc)(UUID *, unsigned char **);
3687 typedef RPC_STATUS (RPC_ENTRY *RpcStringFreeFunc)(unsigned char **);
3689 static HCRYPTPROV CRYPT_CreateKeyProv(void)
3691 HCRYPTPROV hProv = 0;
3692 HMODULE rpcrt = LoadLibraryW(L"rpcrt4");
3694 if (rpcrt)
3696 UuidCreateFunc uuidCreate = (UuidCreateFunc)GetProcAddress(rpcrt,
3697 "UuidCreate");
3698 UuidToStringFunc uuidToString = (UuidToStringFunc)GetProcAddress(rpcrt,
3699 "UuidToStringA");
3700 RpcStringFreeFunc rpcStringFree = (RpcStringFreeFunc)GetProcAddress(
3701 rpcrt, "RpcStringFreeA");
3703 if (uuidCreate && uuidToString && rpcStringFree)
3705 UUID uuid;
3706 RPC_STATUS status = uuidCreate(&uuid);
3708 if (status == RPC_S_OK || status == RPC_S_UUID_LOCAL_ONLY)
3710 unsigned char *uuidStr;
3712 status = uuidToString(&uuid, &uuidStr);
3713 if (status == RPC_S_OK)
3715 BOOL ret = CryptAcquireContextA(&hProv, (LPCSTR)uuidStr,
3716 MS_DEF_PROV_A, PROV_RSA_FULL, CRYPT_NEWKEYSET);
3718 if (ret)
3720 HCRYPTKEY key;
3722 ret = CryptGenKey(hProv, AT_SIGNATURE, 0, &key);
3723 if (ret)
3724 CryptDestroyKey(key);
3726 rpcStringFree(&uuidStr);
3730 FreeLibrary(rpcrt);
3732 return hProv;
3735 PCCERT_CONTEXT WINAPI CertCreateSelfSignCertificate(HCRYPTPROV_OR_NCRYPT_KEY_HANDLE hProv,
3736 PCERT_NAME_BLOB pSubjectIssuerBlob, DWORD dwFlags,
3737 PCRYPT_KEY_PROV_INFO pKeyProvInfo,
3738 PCRYPT_ALGORITHM_IDENTIFIER pSignatureAlgorithm, PSYSTEMTIME pStartTime,
3739 PSYSTEMTIME pEndTime, PCERT_EXTENSIONS pExtensions)
3741 PCCERT_CONTEXT context = NULL;
3742 BOOL ret, releaseContext = FALSE;
3743 PCERT_PUBLIC_KEY_INFO pubKey = NULL;
3744 DWORD pubKeySize = 0, dwKeySpec;
3746 TRACE("(%08Ix, %p, %08lx, %p, %p, %p, %p, %p)\n", hProv,
3747 pSubjectIssuerBlob, dwFlags, pKeyProvInfo, pSignatureAlgorithm, pStartTime,
3748 pExtensions, pExtensions);
3750 if(!pSubjectIssuerBlob)
3752 SetLastError(ERROR_INVALID_PARAMETER);
3753 return NULL;
3756 dwKeySpec = pKeyProvInfo ? pKeyProvInfo->dwKeySpec : AT_SIGNATURE;
3757 if (!hProv)
3759 if (!pKeyProvInfo)
3761 hProv = CRYPT_CreateKeyProv();
3762 releaseContext = TRUE;
3764 else if (pKeyProvInfo->dwFlags & CERT_SET_KEY_PROV_HANDLE_PROP_ID)
3766 SetLastError(NTE_BAD_FLAGS);
3767 return NULL;
3769 else
3771 HCRYPTKEY hKey = 0;
3772 /* acquire the context using the given information*/
3773 ret = CryptAcquireContextW(&hProv,pKeyProvInfo->pwszContainerName,
3774 pKeyProvInfo->pwszProvName,pKeyProvInfo->dwProvType,
3775 pKeyProvInfo->dwFlags);
3776 if (!ret)
3778 if(GetLastError() != NTE_BAD_KEYSET)
3779 return NULL;
3780 /* create the key set */
3781 ret = CryptAcquireContextW(&hProv,pKeyProvInfo->pwszContainerName,
3782 pKeyProvInfo->pwszProvName,pKeyProvInfo->dwProvType,
3783 pKeyProvInfo->dwFlags|CRYPT_NEWKEYSET);
3784 if (!ret)
3785 return NULL;
3787 /* check if the key is here */
3788 ret = CryptGetUserKey(hProv,dwKeySpec,&hKey);
3789 if(!ret)
3791 if (NTE_NO_KEY == GetLastError())
3792 { /* generate the key */
3793 ret = CryptGenKey(hProv,dwKeySpec,0,&hKey);
3795 if (!ret)
3797 CryptReleaseContext(hProv,0);
3798 SetLastError(NTE_BAD_KEYSET);
3799 return NULL;
3802 CryptDestroyKey(hKey);
3803 releaseContext = TRUE;
3807 ret = CryptExportPublicKeyInfo(hProv, dwKeySpec, X509_ASN_ENCODING, NULL,
3808 &pubKeySize);
3809 if (!ret)
3810 goto end;
3811 pubKey = CryptMemAlloc(pubKeySize);
3812 if (pubKey)
3814 ret = CryptExportPublicKeyInfo(hProv, dwKeySpec, X509_ASN_ENCODING,
3815 pubKey, &pubKeySize);
3816 if (ret)
3818 CERT_INFO info = { 0 };
3819 CRYPT_DER_BLOB blob = { 0, NULL };
3820 BYTE serial[16];
3821 CRYPT_DATA_BLOB serialBlob = { sizeof(serial), serial };
3823 CryptGenRandom(hProv, sizeof(serial), serial);
3824 CRYPT_MakeCertInfo(&info, &serialBlob, pSubjectIssuerBlob,
3825 pSignatureAlgorithm, pStartTime, pEndTime, pubKey, pExtensions);
3826 ret = CryptEncodeObjectEx(X509_ASN_ENCODING, X509_CERT_TO_BE_SIGNED,
3827 &info, CRYPT_ENCODE_ALLOC_FLAG, NULL, &blob.pbData,
3828 &blob.cbData);
3829 if (ret)
3831 if (!(dwFlags & CERT_CREATE_SELFSIGN_NO_SIGN))
3832 context = CRYPT_CreateSignedCert(&blob, hProv,dwKeySpec,
3833 &info.SignatureAlgorithm);
3834 else
3835 context = CertCreateCertificateContext(X509_ASN_ENCODING,
3836 blob.pbData, blob.cbData);
3837 if (context && !(dwFlags & CERT_CREATE_SELFSIGN_NO_KEY_INFO))
3838 CertContext_SetKeyProvInfo(context, pKeyProvInfo, hProv);
3839 LocalFree(blob.pbData);
3842 CryptMemFree(pubKey);
3844 end:
3845 if (releaseContext)
3846 CryptReleaseContext(hProv, 0);
3847 return context;
3850 BOOL WINAPI CertVerifyCTLUsage(DWORD dwEncodingType, DWORD dwSubjectType,
3851 void *pvSubject, PCTL_USAGE pSubjectUsage, DWORD dwFlags,
3852 PCTL_VERIFY_USAGE_PARA pVerifyUsagePara,
3853 PCTL_VERIFY_USAGE_STATUS pVerifyUsageStatus)
3855 FIXME("(0x%lx, %ld, %p, %p, 0x%lx, %p, %p): stub\n", dwEncodingType,
3856 dwSubjectType, pvSubject, pSubjectUsage, dwFlags, pVerifyUsagePara,
3857 pVerifyUsageStatus);
3858 SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
3859 return FALSE;
3862 const void * WINAPI CertCreateContext(DWORD dwContextType, DWORD dwEncodingType,
3863 const BYTE *pbEncoded, DWORD cbEncoded,
3864 DWORD dwFlags, PCERT_CREATE_CONTEXT_PARA pCreatePara)
3866 TRACE("(0x%lx, 0x%lx, %p, %ld, 0x%08lx, %p)\n", dwContextType, dwEncodingType,
3867 pbEncoded, cbEncoded, dwFlags, pCreatePara);
3869 if (dwFlags)
3871 FIXME("dwFlags 0x%08lx not handled\n", dwFlags);
3872 return NULL;
3874 if (pCreatePara)
3876 FIXME("pCreatePara not handled\n");
3877 return NULL;
3880 switch (dwContextType)
3882 case CERT_STORE_CERTIFICATE_CONTEXT:
3883 return CertCreateCertificateContext(dwEncodingType, pbEncoded, cbEncoded);
3884 case CERT_STORE_CRL_CONTEXT:
3885 return CertCreateCRLContext(dwEncodingType, pbEncoded, cbEncoded);
3886 case CERT_STORE_CTL_CONTEXT:
3887 return CertCreateCTLContext(dwEncodingType, pbEncoded, cbEncoded);
3888 default:
3889 WARN("unknown context type: 0x%lx\n", dwContextType);
3890 return NULL;
3894 BOOL WINAPI CryptSetKeyIdentifierProperty(const CRYPT_HASH_BLOB *pKeyIdentifier, DWORD dwPropId,
3895 DWORD dwFlags, LPCWSTR pwszComputerName, void *pvReserved, const void *pvData)
3897 FIXME("(%p, 0x%lx, 0x%lx, %s, %p, %p): stub\n", pKeyIdentifier, dwPropId, dwFlags,
3898 debugstr_w(pwszComputerName), pvReserved, pvData);
3899 return FALSE;