crypt32: Correctly free memory in CNG_ImportRSAPubKey().
[wine.git] / dlls / crypt32 / cert.c
blobb7789fd6fcd05bfa3b2a89ce6f8056cbd4dcc5c4
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 = HeapAlloc(GetProcessHeap(), 0, 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 HeapFree(GetProcessHeap(), 0, 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
719 switch (dwPropId)
721 case CERT_AUTO_ENROLL_PROP_ID:
722 case CERT_CTL_USAGE_PROP_ID: /* same as CERT_ENHKEY_USAGE_PROP_ID */
723 case CERT_DESCRIPTION_PROP_ID:
724 case CERT_FRIENDLY_NAME_PROP_ID:
725 case CERT_HASH_PROP_ID:
726 case CERT_KEY_IDENTIFIER_PROP_ID:
727 case CERT_MD5_HASH_PROP_ID:
728 case CERT_NEXT_UPDATE_LOCATION_PROP_ID:
729 case CERT_PUBKEY_ALG_PARA_PROP_ID:
730 case CERT_PVK_FILE_PROP_ID:
731 case CERT_SIGNATURE_HASH_PROP_ID:
732 case CERT_ISSUER_PUBLIC_KEY_MD5_HASH_PROP_ID:
733 case CERT_SUBJECT_NAME_MD5_HASH_PROP_ID:
734 case CERT_EXTENDED_ERROR_INFO_PROP_ID:
735 case CERT_SUBJECT_PUBLIC_KEY_MD5_HASH_PROP_ID:
736 case CERT_ENROLLMENT_PROP_ID:
737 case CERT_CROSS_CERT_DIST_POINTS_PROP_ID:
738 case CERT_OCSP_RESPONSE_PROP_ID:
739 case CERT_RENEWAL_PROP_ID:
741 if (pvData)
743 const CRYPT_DATA_BLOB *blob = pvData;
745 ret = ContextPropertyList_SetProperty(cert->base.properties, dwPropId,
746 blob->pbData, blob->cbData);
748 else
750 ContextPropertyList_RemoveProperty(cert->base.properties, dwPropId);
751 ret = TRUE;
753 break;
755 case CERT_DATE_STAMP_PROP_ID:
756 if (pvData)
757 ret = ContextPropertyList_SetProperty(cert->base.properties, dwPropId,
758 pvData, sizeof(FILETIME));
759 else
761 ContextPropertyList_RemoveProperty(cert->base.properties, dwPropId);
762 ret = TRUE;
764 break;
765 case CERT_KEY_CONTEXT_PROP_ID:
766 if (pvData)
768 const CERT_KEY_CONTEXT *keyContext = pvData;
770 if (keyContext->cbSize != sizeof(CERT_KEY_CONTEXT))
772 SetLastError(E_INVALIDARG);
773 ret = FALSE;
775 else
776 ret = CertContext_SetKeyContextProperty(cert->base.properties, pvData);
778 else
780 ContextPropertyList_RemoveProperty(cert->base.properties, dwPropId);
781 ret = TRUE;
783 break;
784 case CERT_KEY_PROV_INFO_PROP_ID:
785 if (pvData)
786 ret = CertContext_SetKeyProvInfoProperty(cert->base.properties, pvData);
787 else
789 ContextPropertyList_RemoveProperty(cert->base.properties, dwPropId);
790 ret = TRUE;
792 break;
793 case CERT_KEY_PROV_HANDLE_PROP_ID:
795 CERT_KEY_CONTEXT keyContext;
796 DWORD size = sizeof(keyContext);
798 ret = CertContext_GetProperty(cert, CERT_KEY_CONTEXT_PROP_ID,
799 &keyContext, &size);
800 if (ret)
802 if (!(dwFlags & CERT_STORE_NO_CRYPT_RELEASE_FLAG))
803 CryptReleaseContext(keyContext.hCryptProv, 0);
805 keyContext.cbSize = sizeof(keyContext);
806 if (pvData)
807 keyContext.hCryptProv = *(const HCRYPTPROV *)pvData;
808 else
810 keyContext.hCryptProv = 0;
811 keyContext.dwKeySpec = AT_SIGNATURE;
813 ret = CertContext_SetProperty(cert, CERT_KEY_CONTEXT_PROP_ID,
814 0, &keyContext);
815 break;
817 default:
818 FIXME("%ld: stub\n", dwPropId);
819 ret = FALSE;
822 TRACE("returning %d\n", ret);
823 return ret;
826 BOOL WINAPI CertSetCertificateContextProperty(PCCERT_CONTEXT pCertContext,
827 DWORD dwPropId, DWORD dwFlags, const void *pvData)
829 BOOL ret;
831 TRACE("(%p, %ld, %08lx, %p)\n", pCertContext, dwPropId, dwFlags, pvData);
833 /* Handle special cases for "read-only"/invalid prop IDs. Windows just
834 * crashes on most of these, I'll be safer.
836 switch (dwPropId)
838 case 0:
839 case CERT_ACCESS_STATE_PROP_ID:
840 case CERT_CERT_PROP_ID:
841 case CERT_CRL_PROP_ID:
842 case CERT_CTL_PROP_ID:
843 SetLastError(E_INVALIDARG);
844 return FALSE;
846 ret = CertContext_SetProperty(cert_from_ptr(pCertContext), dwPropId, dwFlags,
847 pvData);
848 TRACE("returning %d\n", ret);
849 return ret;
852 /* Acquires the private key using the key provider info, retrieving info from
853 * the certificate if info is NULL. The acquired provider is returned in
854 * *phCryptProv, and the key spec for the provider is returned in *pdwKeySpec.
856 static BOOL CRYPT_AcquirePrivateKeyFromProvInfo(PCCERT_CONTEXT pCert, DWORD dwFlags,
857 PCRYPT_KEY_PROV_INFO info, HCRYPTPROV *phCryptProv, DWORD *pdwKeySpec)
859 DWORD size = 0;
860 BOOL allocated = FALSE, ret = TRUE;
862 if (!info)
864 ret = CertGetCertificateContextProperty(pCert,
865 CERT_KEY_PROV_INFO_PROP_ID, 0, &size);
866 if (ret)
868 info = HeapAlloc(GetProcessHeap(), 0, size);
869 if (info)
871 ret = CertGetCertificateContextProperty(pCert,
872 CERT_KEY_PROV_INFO_PROP_ID, info, &size);
873 allocated = TRUE;
875 else
877 SetLastError(ERROR_OUTOFMEMORY);
878 ret = FALSE;
881 else
882 SetLastError(CRYPT_E_NO_KEY_PROPERTY);
884 if (ret)
886 ret = CryptAcquireContextW(phCryptProv, info->pwszContainerName,
887 info->pwszProvName, info->dwProvType, (dwFlags & CRYPT_ACQUIRE_SILENT_FLAG) ? CRYPT_SILENT : 0);
888 if (ret)
890 DWORD i;
892 for (i = 0; i < info->cProvParam; i++)
894 CryptSetProvParam(*phCryptProv,
895 info->rgProvParam[i].dwParam, info->rgProvParam[i].pbData,
896 info->rgProvParam[i].dwFlags);
898 *pdwKeySpec = info->dwKeySpec;
900 else
901 SetLastError(CRYPT_E_NO_KEY_PROPERTY);
903 if (allocated)
904 HeapFree(GetProcessHeap(), 0, info);
905 return ret;
908 BOOL WINAPI CryptAcquireCertificatePrivateKey(PCCERT_CONTEXT pCert,
909 DWORD dwFlags, void *pvReserved, HCRYPTPROV_OR_NCRYPT_KEY_HANDLE *phCryptProv,
910 DWORD *pdwKeySpec, BOOL *pfCallerFreeProv)
912 BOOL ret = FALSE, cache = FALSE;
913 PCRYPT_KEY_PROV_INFO info = NULL;
914 CERT_KEY_CONTEXT keyContext;
915 DWORD size;
916 PCCERT_CONTEXT cert_in_store = NULL;
918 TRACE("(%p, %08lx, %p, %p, %p, %p)\n", pCert, dwFlags, pvReserved,
919 phCryptProv, pdwKeySpec, pfCallerFreeProv);
921 if (dwFlags & CRYPT_ACQUIRE_USE_PROV_INFO_FLAG)
923 DWORD size = 0;
925 ret = CertGetCertificateContextProperty(pCert,
926 CERT_KEY_PROV_INFO_PROP_ID, 0, &size);
928 if (!ret)
930 HCERTSTORE hstore;
932 hstore = CertOpenStore(CERT_STORE_PROV_SYSTEM_W, 0, 0,
933 CERT_SYSTEM_STORE_CURRENT_USER, L"My");
934 if (hstore)
936 cert_in_store = CertFindCertificateInStore(hstore, pCert->dwCertEncodingType, 0,
937 CERT_FIND_EXISTING, pCert, NULL);
938 if (cert_in_store)
940 ret = CertGetCertificateContextProperty(cert_in_store, CERT_KEY_PROV_INFO_PROP_ID, 0, &size);
941 if (ret)
942 pCert = cert_in_store;
943 else
945 CertFreeCertificateContext(cert_in_store);
946 cert_in_store = NULL;
950 CertCloseStore(hstore, 0);
954 if (ret)
956 info = HeapAlloc(GetProcessHeap(), 0, size);
957 ret = CertGetCertificateContextProperty(pCert,
958 CERT_KEY_PROV_INFO_PROP_ID, info, &size);
959 if (ret)
960 cache = info->dwFlags & CERT_SET_KEY_CONTEXT_PROP_ID;
963 else if (dwFlags & CRYPT_ACQUIRE_CACHE_FLAG)
964 cache = TRUE;
965 *phCryptProv = 0;
966 if (cache)
968 size = sizeof(keyContext);
969 ret = CertGetCertificateContextProperty(pCert, CERT_KEY_CONTEXT_PROP_ID,
970 &keyContext, &size);
971 if (ret)
973 *phCryptProv = keyContext.hCryptProv;
974 if (pdwKeySpec)
975 *pdwKeySpec = keyContext.dwKeySpec;
976 if (pfCallerFreeProv)
977 *pfCallerFreeProv = FALSE;
980 if (!*phCryptProv)
982 ret = CRYPT_AcquirePrivateKeyFromProvInfo(pCert, dwFlags, info,
983 &keyContext.hCryptProv, &keyContext.dwKeySpec);
984 if (ret)
986 *phCryptProv = keyContext.hCryptProv;
987 if (pdwKeySpec)
988 *pdwKeySpec = keyContext.dwKeySpec;
989 if (cache)
991 keyContext.cbSize = sizeof(keyContext);
992 if (CertSetCertificateContextProperty(pCert,
993 CERT_KEY_CONTEXT_PROP_ID, 0, &keyContext))
995 if (pfCallerFreeProv)
996 *pfCallerFreeProv = FALSE;
999 else
1001 if (pfCallerFreeProv)
1002 *pfCallerFreeProv = TRUE;
1006 HeapFree(GetProcessHeap(), 0, info);
1007 if (cert_in_store)
1008 CertFreeCertificateContext(cert_in_store);
1009 return ret;
1012 static BOOL key_prov_info_matches_cert(PCCERT_CONTEXT pCert,
1013 const CRYPT_KEY_PROV_INFO *keyProvInfo)
1015 HCRYPTPROV csp;
1016 BOOL matches = FALSE;
1018 if (CryptAcquireContextW(&csp, keyProvInfo->pwszContainerName,
1019 keyProvInfo->pwszProvName, keyProvInfo->dwProvType, keyProvInfo->dwFlags))
1021 DWORD size;
1023 /* Need to sign something to verify the sig. What to sign? Why not
1024 * the certificate itself?
1026 if (CryptSignAndEncodeCertificate(csp, AT_SIGNATURE,
1027 pCert->dwCertEncodingType, X509_CERT_TO_BE_SIGNED, pCert->pCertInfo,
1028 &pCert->pCertInfo->SignatureAlgorithm, NULL, NULL, &size))
1030 BYTE *certEncoded = CryptMemAlloc(size);
1032 if (certEncoded)
1034 if (CryptSignAndEncodeCertificate(csp, AT_SIGNATURE,
1035 pCert->dwCertEncodingType, X509_CERT_TO_BE_SIGNED,
1036 pCert->pCertInfo, &pCert->pCertInfo->SignatureAlgorithm,
1037 NULL, certEncoded, &size))
1039 if (size == pCert->cbCertEncoded &&
1040 !memcmp(certEncoded, pCert->pbCertEncoded, size))
1041 matches = TRUE;
1043 CryptMemFree(certEncoded);
1046 CryptReleaseContext(csp, 0);
1048 return matches;
1051 static BOOL container_matches_cert(PCCERT_CONTEXT pCert, LPCSTR container,
1052 CRYPT_KEY_PROV_INFO *keyProvInfo)
1054 CRYPT_KEY_PROV_INFO copy;
1055 WCHAR containerW[MAX_PATH];
1056 BOOL matches;
1058 MultiByteToWideChar(CP_ACP, 0, container, -1, containerW, ARRAY_SIZE(containerW));
1059 /* We make a copy of the CRYPT_KEY_PROV_INFO because the caller expects
1060 * keyProvInfo->pwszContainerName to be NULL or a heap-allocated container
1061 * name.
1063 copy = *keyProvInfo;
1064 copy.pwszContainerName = containerW;
1065 matches = key_prov_info_matches_cert(pCert, &copy);
1066 if (matches)
1068 keyProvInfo->pwszContainerName =
1069 CryptMemAlloc((lstrlenW(containerW) + 1) * sizeof(WCHAR));
1070 if (keyProvInfo->pwszContainerName)
1072 lstrcpyW(keyProvInfo->pwszContainerName, containerW);
1073 keyProvInfo->dwKeySpec = AT_SIGNATURE;
1075 else
1076 matches = FALSE;
1078 return matches;
1081 /* Searches the provider named keyProvInfo.pwszProvName for a container whose
1082 * private key matches pCert's public key. Upon success, updates keyProvInfo
1083 * with the matching container's info (free keyProvInfo.pwszContainerName upon
1084 * success.)
1085 * Returns TRUE if found, FALSE if not.
1087 static BOOL find_key_prov_info_in_provider(PCCERT_CONTEXT pCert,
1088 CRYPT_KEY_PROV_INFO *keyProvInfo)
1090 HCRYPTPROV defProvider;
1091 BOOL ret, found = FALSE;
1092 char containerA[MAX_PATH];
1094 assert(keyProvInfo->pwszContainerName == NULL);
1095 if ((ret = CryptAcquireContextW(&defProvider, NULL,
1096 keyProvInfo->pwszProvName, keyProvInfo->dwProvType,
1097 keyProvInfo->dwFlags | CRYPT_VERIFYCONTEXT)))
1099 DWORD enumFlags = keyProvInfo->dwFlags | CRYPT_FIRST;
1101 while (ret && !found)
1103 DWORD size = sizeof(containerA);
1105 ret = CryptGetProvParam(defProvider, PP_ENUMCONTAINERS,
1106 (BYTE *)containerA, &size, enumFlags);
1107 if (ret)
1108 found = container_matches_cert(pCert, containerA, keyProvInfo);
1109 if (enumFlags & CRYPT_FIRST)
1111 enumFlags &= ~CRYPT_FIRST;
1112 enumFlags |= CRYPT_NEXT;
1115 CryptReleaseContext(defProvider, 0);
1117 return found;
1120 static BOOL find_matching_provider(PCCERT_CONTEXT pCert, DWORD dwFlags)
1122 BOOL found = FALSE, ret = TRUE;
1123 DWORD index = 0, cbProvName = 0;
1124 CRYPT_KEY_PROV_INFO keyProvInfo;
1126 TRACE("(%p, %08lx)\n", pCert, dwFlags);
1128 memset(&keyProvInfo, 0, sizeof(keyProvInfo));
1129 while (ret && !found)
1131 DWORD size = 0;
1133 ret = CryptEnumProvidersW(index, NULL, 0, &keyProvInfo.dwProvType,
1134 NULL, &size);
1135 if (ret)
1137 if (size <= cbProvName)
1138 ret = CryptEnumProvidersW(index, NULL, 0,
1139 &keyProvInfo.dwProvType, keyProvInfo.pwszProvName, &size);
1140 else
1142 CryptMemFree(keyProvInfo.pwszProvName);
1143 keyProvInfo.pwszProvName = CryptMemAlloc(size);
1144 if (keyProvInfo.pwszProvName)
1146 cbProvName = size;
1147 ret = CryptEnumProvidersW(index, NULL, 0,
1148 &keyProvInfo.dwProvType, keyProvInfo.pwszProvName, &size);
1149 if (ret)
1151 if (dwFlags & CRYPT_FIND_SILENT_KEYSET_FLAG)
1152 keyProvInfo.dwFlags |= CRYPT_SILENT;
1153 if (dwFlags & CRYPT_FIND_USER_KEYSET_FLAG ||
1154 !(dwFlags & (CRYPT_FIND_USER_KEYSET_FLAG |
1155 CRYPT_FIND_MACHINE_KEYSET_FLAG)))
1157 keyProvInfo.dwFlags |= CRYPT_USER_KEYSET;
1158 found = find_key_prov_info_in_provider(pCert,
1159 &keyProvInfo);
1161 if (!found)
1163 if (dwFlags & CRYPT_FIND_MACHINE_KEYSET_FLAG ||
1164 !(dwFlags & (CRYPT_FIND_USER_KEYSET_FLAG |
1165 CRYPT_FIND_MACHINE_KEYSET_FLAG)))
1167 keyProvInfo.dwFlags &= ~CRYPT_USER_KEYSET;
1168 keyProvInfo.dwFlags |= CRYPT_MACHINE_KEYSET;
1169 found = find_key_prov_info_in_provider(pCert,
1170 &keyProvInfo);
1175 else
1176 ret = FALSE;
1178 index++;
1181 if (found)
1182 CertSetCertificateContextProperty(pCert, CERT_KEY_PROV_INFO_PROP_ID,
1183 0, &keyProvInfo);
1184 CryptMemFree(keyProvInfo.pwszProvName);
1185 CryptMemFree(keyProvInfo.pwszContainerName);
1186 return found;
1189 static BOOL cert_prov_info_matches_cert(PCCERT_CONTEXT pCert)
1191 BOOL matches = FALSE;
1192 DWORD size;
1194 if (CertGetCertificateContextProperty(pCert, CERT_KEY_PROV_INFO_PROP_ID,
1195 NULL, &size))
1197 CRYPT_KEY_PROV_INFO *keyProvInfo = CryptMemAlloc(size);
1199 if (keyProvInfo)
1201 if (CertGetCertificateContextProperty(pCert,
1202 CERT_KEY_PROV_INFO_PROP_ID, keyProvInfo, &size))
1203 matches = key_prov_info_matches_cert(pCert, keyProvInfo);
1204 CryptMemFree(keyProvInfo);
1207 return matches;
1210 BOOL WINAPI CryptFindCertificateKeyProvInfo(PCCERT_CONTEXT pCert,
1211 DWORD dwFlags, void *pvReserved)
1213 BOOL matches;
1215 TRACE("(%p, %08lx, %p)\n", pCert, dwFlags, pvReserved);
1217 matches = cert_prov_info_matches_cert(pCert);
1218 if (!matches)
1219 matches = find_matching_provider(pCert, dwFlags);
1220 return matches;
1223 BOOL WINAPI CertCompareCertificate(DWORD dwCertEncodingType,
1224 PCERT_INFO pCertId1, PCERT_INFO pCertId2)
1226 BOOL ret;
1228 TRACE("(%08lx, %p, %p)\n", dwCertEncodingType, pCertId1, pCertId2);
1230 ret = CertCompareCertificateName(dwCertEncodingType, &pCertId1->Issuer,
1231 &pCertId2->Issuer) && CertCompareIntegerBlob(&pCertId1->SerialNumber,
1232 &pCertId2->SerialNumber);
1233 TRACE("returning %d\n", ret);
1234 return ret;
1237 BOOL WINAPI CertCompareCertificateName(DWORD dwCertEncodingType,
1238 PCERT_NAME_BLOB pCertName1, PCERT_NAME_BLOB pCertName2)
1240 BOOL ret;
1242 TRACE("(%08lx, %p, %p)\n", dwCertEncodingType, pCertName1, pCertName2);
1244 if (pCertName1->cbData == pCertName2->cbData)
1246 if (pCertName1->cbData)
1247 ret = !memcmp(pCertName1->pbData, pCertName2->pbData,
1248 pCertName1->cbData);
1249 else
1250 ret = TRUE;
1252 else
1253 ret = FALSE;
1254 TRACE("returning %d\n", ret);
1255 return ret;
1258 /* Returns the number of significant bytes in pInt, where a byte is
1259 * insignificant if it's a leading 0 for positive numbers or a leading 0xff
1260 * for negative numbers. pInt is assumed to be little-endian.
1262 static DWORD CRYPT_significantBytes(const CRYPT_INTEGER_BLOB *pInt)
1264 DWORD ret = pInt->cbData;
1266 while (ret > 1)
1268 if (pInt->pbData[ret - 2] <= 0x7f && pInt->pbData[ret - 1] == 0)
1269 ret--;
1270 else if (pInt->pbData[ret - 2] >= 0x80 && pInt->pbData[ret - 1] == 0xff)
1271 ret--;
1272 else
1273 break;
1275 return ret;
1278 BOOL WINAPI CertCompareIntegerBlob(PCRYPT_INTEGER_BLOB pInt1,
1279 PCRYPT_INTEGER_BLOB pInt2)
1281 BOOL ret;
1282 DWORD cb1, cb2;
1284 TRACE("(%p, %p)\n", pInt1, pInt2);
1286 cb1 = CRYPT_significantBytes(pInt1);
1287 cb2 = CRYPT_significantBytes(pInt2);
1288 if (cb1 == cb2)
1290 if (cb1)
1291 ret = !memcmp(pInt1->pbData, pInt2->pbData, cb1);
1292 else
1293 ret = TRUE;
1295 else
1296 ret = FALSE;
1297 TRACE("returning %d\n", ret);
1298 return ret;
1301 BOOL WINAPI CertComparePublicKeyInfo(DWORD dwCertEncodingType,
1302 PCERT_PUBLIC_KEY_INFO pPublicKey1, PCERT_PUBLIC_KEY_INFO pPublicKey2)
1304 BOOL ret;
1306 TRACE("(%08lx, %p, %p)\n", dwCertEncodingType, pPublicKey1, pPublicKey2);
1308 /* RSA public key data should start with ASN_SEQUENCE,
1309 * otherwise it's not a RSA_CSP_PUBLICKEYBLOB.
1311 if (!pPublicKey1->PublicKey.cbData || pPublicKey1->PublicKey.pbData[0] != ASN_SEQUENCE)
1312 dwCertEncodingType = 0;
1314 switch (GET_CERT_ENCODING_TYPE(dwCertEncodingType))
1316 case 0: /* Seems to mean "raw binary bits" */
1317 if (pPublicKey1->PublicKey.cbData == pPublicKey2->PublicKey.cbData &&
1318 pPublicKey1->PublicKey.cUnusedBits == pPublicKey2->PublicKey.cUnusedBits)
1320 if (pPublicKey2->PublicKey.cbData)
1321 ret = !memcmp(pPublicKey1->PublicKey.pbData,
1322 pPublicKey2->PublicKey.pbData, pPublicKey1->PublicKey.cbData);
1323 else
1324 ret = TRUE;
1326 else
1327 ret = FALSE;
1328 break;
1329 default:
1330 WARN("Unknown encoding type %08lx\n", dwCertEncodingType);
1331 /* FALLTHROUGH */
1332 case X509_ASN_ENCODING:
1334 BLOBHEADER *pblob1, *pblob2;
1335 DWORD length;
1336 ret = FALSE;
1337 if (CryptDecodeObject(dwCertEncodingType, RSA_CSP_PUBLICKEYBLOB,
1338 pPublicKey1->PublicKey.pbData, pPublicKey1->PublicKey.cbData,
1339 CRYPT_DECODE_ALLOC_FLAG, &pblob1, &length))
1341 if (CryptDecodeObject(dwCertEncodingType, RSA_CSP_PUBLICKEYBLOB,
1342 pPublicKey2->PublicKey.pbData, pPublicKey2->PublicKey.cbData,
1343 CRYPT_DECODE_ALLOC_FLAG, &pblob2, &length))
1345 /* The RSAPUBKEY structure directly follows the BLOBHEADER */
1346 RSAPUBKEY *pk1 = (LPVOID)(pblob1 + 1),
1347 *pk2 = (LPVOID)(pblob2 + 1);
1348 ret = (pk1->bitlen == pk2->bitlen) && (pk1->pubexp == pk2->pubexp)
1349 && !memcmp(pk1 + 1, pk2 + 1, pk1->bitlen/8);
1351 LocalFree(pblob2);
1353 LocalFree(pblob1);
1356 break;
1359 return ret;
1362 DWORD WINAPI CertGetPublicKeyLength(DWORD dwCertEncodingType,
1363 PCERT_PUBLIC_KEY_INFO pPublicKey)
1365 DWORD len = 0;
1367 TRACE("(%08lx, %p)\n", dwCertEncodingType, pPublicKey);
1369 if (GET_CERT_ENCODING_TYPE(dwCertEncodingType) != X509_ASN_ENCODING)
1371 SetLastError(ERROR_FILE_NOT_FOUND);
1372 return 0;
1374 if (pPublicKey->Algorithm.pszObjId &&
1375 !strcmp(pPublicKey->Algorithm.pszObjId, szOID_RSA_DH))
1377 FIXME("unimplemented for DH public keys\n");
1378 SetLastError(CRYPT_E_ASN1_BADTAG);
1380 else
1382 PCCRYPT_OID_INFO info;
1383 DWORD size;
1384 PBYTE buf;
1385 BOOL ret;
1387 info = CryptFindOIDInfo(CRYPT_OID_INFO_OID_KEY, pPublicKey->Algorithm.pszObjId, 0);
1388 if (info)
1390 HCRYPTKEY key;
1392 TRACE("public key algid %#x (%s)\n", info->u.Algid, debugstr_a(pPublicKey->Algorithm.pszObjId));
1394 ret = CryptImportPublicKeyInfo(I_CryptGetDefaultCryptProv(info->u.Algid), dwCertEncodingType, pPublicKey, &key);
1395 if (ret)
1397 size = sizeof(len);
1398 ret = CryptGetKeyParam(key, KP_KEYLEN, (BYTE *)&len, &size, 0);
1399 CryptDestroyKey(key);
1400 return len;
1402 /* fallback to RSA */
1405 ret = CryptDecodeObjectEx(dwCertEncodingType,
1406 RSA_CSP_PUBLICKEYBLOB, pPublicKey->PublicKey.pbData,
1407 pPublicKey->PublicKey.cbData, CRYPT_DECODE_ALLOC_FLAG, NULL, &buf,
1408 &size);
1410 if (ret)
1412 RSAPUBKEY *rsaPubKey = (RSAPUBKEY *)(buf + sizeof(BLOBHEADER));
1414 len = rsaPubKey->bitlen;
1415 LocalFree(buf);
1418 return len;
1421 typedef BOOL (*CertCompareFunc)(PCCERT_CONTEXT pCertContext, DWORD dwType,
1422 DWORD dwFlags, const void *pvPara);
1424 static BOOL compare_cert_by_md5_hash(PCCERT_CONTEXT pCertContext, DWORD dwType,
1425 DWORD dwFlags, const void *pvPara)
1427 BOOL ret;
1428 BYTE hash[16];
1429 DWORD size = sizeof(hash);
1431 ret = CertGetCertificateContextProperty(pCertContext,
1432 CERT_MD5_HASH_PROP_ID, hash, &size);
1433 if (ret)
1435 const CRYPT_HASH_BLOB *pHash = pvPara;
1437 if (size == pHash->cbData)
1438 ret = !memcmp(pHash->pbData, hash, size);
1439 else
1440 ret = FALSE;
1442 return ret;
1445 static BOOL compare_cert_by_sha1_hash(PCCERT_CONTEXT pCertContext, DWORD dwType,
1446 DWORD dwFlags, const void *pvPara)
1448 BOOL ret;
1449 BYTE hash[20];
1450 DWORD size = sizeof(hash);
1452 ret = CertGetCertificateContextProperty(pCertContext,
1453 CERT_SHA1_HASH_PROP_ID, hash, &size);
1454 if (ret)
1456 const CRYPT_HASH_BLOB *pHash = pvPara;
1458 if (size == pHash->cbData)
1459 ret = !memcmp(pHash->pbData, hash, size);
1460 else
1461 ret = FALSE;
1463 return ret;
1466 static BOOL compare_cert_by_name(PCCERT_CONTEXT pCertContext, DWORD dwType,
1467 DWORD dwFlags, const void *pvPara)
1469 CERT_NAME_BLOB *blob = (CERT_NAME_BLOB *)pvPara, *toCompare;
1470 BOOL ret;
1472 if (dwType & CERT_INFO_SUBJECT_FLAG)
1473 toCompare = &pCertContext->pCertInfo->Subject;
1474 else
1475 toCompare = &pCertContext->pCertInfo->Issuer;
1476 ret = CertCompareCertificateName(pCertContext->dwCertEncodingType,
1477 toCompare, blob);
1478 return ret;
1481 static BOOL compare_cert_by_public_key(PCCERT_CONTEXT pCertContext,
1482 DWORD dwType, DWORD dwFlags, const void *pvPara)
1484 CERT_PUBLIC_KEY_INFO *publicKey = (CERT_PUBLIC_KEY_INFO *)pvPara;
1485 BOOL ret;
1487 ret = CertComparePublicKeyInfo(pCertContext->dwCertEncodingType,
1488 &pCertContext->pCertInfo->SubjectPublicKeyInfo, publicKey);
1489 return ret;
1492 static BOOL compare_cert_by_subject_cert(PCCERT_CONTEXT pCertContext,
1493 DWORD dwType, DWORD dwFlags, const void *pvPara)
1495 CERT_INFO *pCertInfo = (CERT_INFO *)pvPara;
1496 BOOL ret;
1498 /* Matching serial number and subject match.. */
1499 ret = CertCompareCertificateName(pCertContext->dwCertEncodingType,
1500 &pCertContext->pCertInfo->Subject, &pCertInfo->Issuer);
1501 if (ret)
1502 ret = CertCompareIntegerBlob(&pCertContext->pCertInfo->SerialNumber,
1503 &pCertInfo->SerialNumber);
1504 else
1506 /* failing that, if the serial number and issuer match, we match */
1507 ret = CertCompareIntegerBlob(&pCertContext->pCertInfo->SerialNumber,
1508 &pCertInfo->SerialNumber);
1509 if (ret)
1510 ret = CertCompareCertificateName(pCertContext->dwCertEncodingType,
1511 &pCertContext->pCertInfo->Issuer, &pCertInfo->Issuer);
1513 TRACE("returning %d\n", ret);
1514 return ret;
1517 static BOOL compare_cert_by_cert_id(PCCERT_CONTEXT pCertContext, DWORD dwType,
1518 DWORD dwFlags, const void *pvPara)
1520 CERT_ID *id = (CERT_ID *)pvPara;
1521 BOOL ret;
1523 switch (id->dwIdChoice)
1525 case CERT_ID_ISSUER_SERIAL_NUMBER:
1526 ret = CertCompareCertificateName(pCertContext->dwCertEncodingType,
1527 &pCertContext->pCertInfo->Issuer, &id->u.IssuerSerialNumber.Issuer);
1528 if (ret)
1529 ret = CertCompareIntegerBlob(&pCertContext->pCertInfo->SerialNumber,
1530 &id->u.IssuerSerialNumber.SerialNumber);
1531 break;
1532 case CERT_ID_SHA1_HASH:
1533 ret = compare_cert_by_sha1_hash(pCertContext, dwType, dwFlags,
1534 &id->u.HashId);
1535 break;
1536 case CERT_ID_KEY_IDENTIFIER:
1538 DWORD size = 0;
1540 ret = CertGetCertificateContextProperty(pCertContext,
1541 CERT_KEY_IDENTIFIER_PROP_ID, NULL, &size);
1542 if (ret && size == id->u.KeyId.cbData)
1544 LPBYTE buf = CryptMemAlloc(size);
1546 if (buf)
1548 CertGetCertificateContextProperty(pCertContext,
1549 CERT_KEY_IDENTIFIER_PROP_ID, buf, &size);
1550 ret = !memcmp(buf, id->u.KeyId.pbData, size);
1551 CryptMemFree(buf);
1553 else
1554 ret = FALSE;
1556 else
1557 ret = FALSE;
1558 break;
1560 default:
1561 ret = FALSE;
1562 break;
1564 return ret;
1567 static BOOL compare_existing_cert(PCCERT_CONTEXT pCertContext, DWORD dwType,
1568 DWORD dwFlags, const void *pvPara)
1570 PCCERT_CONTEXT toCompare = pvPara;
1571 return CertCompareCertificate(pCertContext->dwCertEncodingType,
1572 pCertContext->pCertInfo, toCompare->pCertInfo);
1575 static BOOL compare_cert_by_signature_hash(PCCERT_CONTEXT pCertContext, DWORD dwType,
1576 DWORD dwFlags, const void *pvPara)
1578 const CRYPT_HASH_BLOB *hash = pvPara;
1579 DWORD size = 0;
1580 BOOL ret;
1582 ret = CertGetCertificateContextProperty(pCertContext,
1583 CERT_SIGNATURE_HASH_PROP_ID, NULL, &size);
1584 if (ret && size == hash->cbData)
1586 LPBYTE buf = CryptMemAlloc(size);
1588 if (buf)
1590 CertGetCertificateContextProperty(pCertContext,
1591 CERT_SIGNATURE_HASH_PROP_ID, buf, &size);
1592 ret = !memcmp(buf, hash->pbData, size);
1593 CryptMemFree(buf);
1595 else
1596 ret = FALSE;
1598 else
1599 ret = FALSE;
1600 return ret;
1603 static inline PCCERT_CONTEXT cert_compare_certs_in_store(HCERTSTORE store,
1604 PCCERT_CONTEXT prev, CertCompareFunc compare, DWORD dwType, DWORD dwFlags,
1605 const void *pvPara)
1607 BOOL matches = FALSE;
1608 PCCERT_CONTEXT ret;
1610 ret = prev;
1611 do {
1612 ret = CertEnumCertificatesInStore(store, ret);
1613 if (ret)
1614 matches = compare(ret, dwType, dwFlags, pvPara);
1615 } while (ret != NULL && !matches);
1616 return ret;
1619 typedef PCCERT_CONTEXT (*CertFindFunc)(HCERTSTORE store, DWORD dwType,
1620 DWORD dwFlags, const void *pvPara, PCCERT_CONTEXT prev);
1622 static PCCERT_CONTEXT find_cert_any(HCERTSTORE store, DWORD dwType,
1623 DWORD dwFlags, const void *pvPara, PCCERT_CONTEXT prev)
1625 return CertEnumCertificatesInStore(store, prev);
1628 static PCCERT_CONTEXT find_cert_by_issuer(HCERTSTORE store, DWORD dwType,
1629 DWORD dwFlags, const void *pvPara, PCCERT_CONTEXT prev)
1631 BOOL ret;
1632 PCCERT_CONTEXT found = NULL, subject = pvPara;
1633 PCERT_EXTENSION ext;
1634 DWORD size;
1636 if ((ext = CertFindExtension(szOID_AUTHORITY_KEY_IDENTIFIER,
1637 subject->pCertInfo->cExtension, subject->pCertInfo->rgExtension)))
1639 CERT_AUTHORITY_KEY_ID_INFO *info;
1641 ret = CryptDecodeObjectEx(subject->dwCertEncodingType,
1642 X509_AUTHORITY_KEY_ID, ext->Value.pbData, ext->Value.cbData,
1643 CRYPT_DECODE_ALLOC_FLAG | CRYPT_DECODE_NOCOPY_FLAG, NULL,
1644 &info, &size);
1645 if (ret)
1647 CERT_ID id;
1649 if (info->CertIssuer.cbData && info->CertSerialNumber.cbData)
1651 id.dwIdChoice = CERT_ID_ISSUER_SERIAL_NUMBER;
1652 memcpy(&id.u.IssuerSerialNumber.Issuer, &info->CertIssuer,
1653 sizeof(CERT_NAME_BLOB));
1654 memcpy(&id.u.IssuerSerialNumber.SerialNumber,
1655 &info->CertSerialNumber, sizeof(CRYPT_INTEGER_BLOB));
1657 else if (info->KeyId.cbData)
1659 id.dwIdChoice = CERT_ID_KEY_IDENTIFIER;
1660 memcpy(&id.u.KeyId, &info->KeyId, sizeof(CRYPT_HASH_BLOB));
1662 else
1663 ret = FALSE;
1664 if (ret)
1665 found = cert_compare_certs_in_store(store, prev,
1666 compare_cert_by_cert_id, dwType, dwFlags, &id);
1667 LocalFree(info);
1670 else if ((ext = CertFindExtension(szOID_AUTHORITY_KEY_IDENTIFIER2,
1671 subject->pCertInfo->cExtension, subject->pCertInfo->rgExtension)))
1673 CERT_AUTHORITY_KEY_ID2_INFO *info;
1675 ret = CryptDecodeObjectEx(subject->dwCertEncodingType,
1676 X509_AUTHORITY_KEY_ID2, ext->Value.pbData, ext->Value.cbData,
1677 CRYPT_DECODE_ALLOC_FLAG | CRYPT_DECODE_NOCOPY_FLAG, NULL,
1678 &info, &size);
1679 if (ret)
1681 CERT_ID id;
1683 if (info->AuthorityCertIssuer.cAltEntry &&
1684 info->AuthorityCertSerialNumber.cbData)
1686 PCERT_ALT_NAME_ENTRY directoryName = NULL;
1687 DWORD i;
1689 for (i = 0; !directoryName &&
1690 i < info->AuthorityCertIssuer.cAltEntry; i++)
1691 if (info->AuthorityCertIssuer.rgAltEntry[i].dwAltNameChoice
1692 == CERT_ALT_NAME_DIRECTORY_NAME)
1693 directoryName =
1694 &info->AuthorityCertIssuer.rgAltEntry[i];
1695 if (directoryName)
1697 id.dwIdChoice = CERT_ID_ISSUER_SERIAL_NUMBER;
1698 memcpy(&id.u.IssuerSerialNumber.Issuer,
1699 &directoryName->u.DirectoryName, sizeof(CERT_NAME_BLOB));
1700 memcpy(&id.u.IssuerSerialNumber.SerialNumber,
1701 &info->AuthorityCertSerialNumber,
1702 sizeof(CRYPT_INTEGER_BLOB));
1704 else
1706 FIXME("no supported name type in authority key id2\n");
1707 ret = FALSE;
1710 else if (info->KeyId.cbData)
1712 id.dwIdChoice = CERT_ID_KEY_IDENTIFIER;
1713 memcpy(&id.u.KeyId, &info->KeyId, sizeof(CRYPT_HASH_BLOB));
1715 else
1716 ret = FALSE;
1717 if (ret)
1718 found = cert_compare_certs_in_store(store, prev,
1719 compare_cert_by_cert_id, dwType, dwFlags, &id);
1720 LocalFree(info);
1723 else
1724 found = cert_compare_certs_in_store(store, prev,
1725 compare_cert_by_name, CERT_COMPARE_NAME | CERT_COMPARE_SUBJECT_CERT,
1726 dwFlags, &subject->pCertInfo->Issuer);
1727 return found;
1730 static BOOL compare_cert_by_name_str(PCCERT_CONTEXT pCertContext,
1731 DWORD dwType, DWORD dwFlags, const void *pvPara)
1733 PCERT_NAME_BLOB name;
1734 DWORD len;
1735 BOOL ret = FALSE;
1737 if (dwType & CERT_INFO_SUBJECT_FLAG)
1738 name = &pCertContext->pCertInfo->Subject;
1739 else
1740 name = &pCertContext->pCertInfo->Issuer;
1741 len = CertNameToStrW(pCertContext->dwCertEncodingType, name,
1742 CERT_SIMPLE_NAME_STR, NULL, 0);
1743 if (len)
1745 LPWSTR str = CryptMemAlloc(len * sizeof(WCHAR));
1747 if (str)
1749 CertNameToStrW(pCertContext->dwCertEncodingType, name,
1750 CERT_SIMPLE_NAME_STR, str, len);
1751 wcslwr(str);
1752 if (wcsstr(str, pvPara))
1753 ret = TRUE;
1754 CryptMemFree(str);
1757 return ret;
1760 static PCCERT_CONTEXT find_cert_by_name_str_a(HCERTSTORE store, DWORD dwType,
1761 DWORD dwFlags, const void *pvPara, PCCERT_CONTEXT prev)
1763 PCCERT_CONTEXT found = NULL;
1765 TRACE("%s\n", debugstr_a(pvPara));
1767 if (pvPara)
1769 int len = MultiByteToWideChar(CP_ACP, 0, pvPara, -1, NULL, 0);
1770 LPWSTR str = CryptMemAlloc(len * sizeof(WCHAR));
1772 if (str)
1774 MultiByteToWideChar(CP_ACP, 0, pvPara, -1, str, len);
1775 wcslwr(str);
1776 found = cert_compare_certs_in_store(store, prev,
1777 compare_cert_by_name_str, dwType, dwFlags, str);
1778 CryptMemFree(str);
1781 else
1782 found = find_cert_any(store, dwType, dwFlags, NULL, prev);
1783 return found;
1786 static PCCERT_CONTEXT find_cert_by_name_str_w(HCERTSTORE store, DWORD dwType,
1787 DWORD dwFlags, const void *pvPara, PCCERT_CONTEXT prev)
1789 PCCERT_CONTEXT found = NULL;
1791 TRACE("%s\n", debugstr_w(pvPara));
1793 if (pvPara)
1795 DWORD len = lstrlenW(pvPara);
1796 LPWSTR str = CryptMemAlloc((len + 1) * sizeof(WCHAR));
1798 if (str)
1800 wcscpy( str, pvPara );
1801 wcslwr( str );
1802 found = cert_compare_certs_in_store(store, prev,
1803 compare_cert_by_name_str, dwType, dwFlags, str);
1804 CryptMemFree(str);
1807 else
1808 found = find_cert_any(store, dwType, dwFlags, NULL, prev);
1809 return found;
1812 PCCERT_CONTEXT WINAPI CertFindCertificateInStore(HCERTSTORE hCertStore,
1813 DWORD dwCertEncodingType, DWORD dwFlags, DWORD dwType, const void *pvPara,
1814 PCCERT_CONTEXT pPrevCertContext)
1816 PCCERT_CONTEXT ret;
1817 CertFindFunc find = NULL;
1818 CertCompareFunc compare = NULL;
1819 CERT_ID cert_id;
1821 TRACE("(%p, %08lx, %08lx, %08lx, %p, %p)\n", hCertStore, dwCertEncodingType,
1822 dwFlags, dwType, pvPara, pPrevCertContext);
1824 switch (dwType >> CERT_COMPARE_SHIFT)
1826 case CERT_COMPARE_ANY:
1827 find = find_cert_any;
1828 break;
1829 case CERT_COMPARE_MD5_HASH:
1830 compare = compare_cert_by_md5_hash;
1831 break;
1832 case CERT_COMPARE_SHA1_HASH:
1833 compare = compare_cert_by_sha1_hash;
1834 break;
1835 case CERT_COMPARE_NAME:
1836 compare = compare_cert_by_name;
1837 break;
1838 case CERT_COMPARE_PUBLIC_KEY:
1839 compare = compare_cert_by_public_key;
1840 break;
1841 case CERT_COMPARE_NAME_STR_A:
1842 find = find_cert_by_name_str_a;
1843 break;
1844 case CERT_COMPARE_NAME_STR_W:
1845 find = find_cert_by_name_str_w;
1846 break;
1847 case CERT_COMPARE_SUBJECT_CERT:
1848 compare = compare_cert_by_subject_cert;
1849 break;
1850 case CERT_COMPARE_KEY_IDENTIFIER:
1851 cert_id.dwIdChoice = CERT_ID_KEY_IDENTIFIER;
1852 cert_id.u.KeyId = *(const CRYPT_HASH_BLOB *)pvPara;
1853 pvPara = &cert_id;
1854 /* fall through */
1855 case CERT_COMPARE_CERT_ID:
1856 compare = compare_cert_by_cert_id;
1857 break;
1858 case CERT_COMPARE_ISSUER_OF:
1859 find = find_cert_by_issuer;
1860 break;
1861 case CERT_COMPARE_EXISTING:
1862 compare = compare_existing_cert;
1863 break;
1864 case CERT_COMPARE_SIGNATURE_HASH:
1865 compare = compare_cert_by_signature_hash;
1866 break;
1867 default:
1868 FIXME("find type %08lx unimplemented\n", dwType);
1871 if (find)
1872 ret = find(hCertStore, dwType, dwFlags, pvPara, pPrevCertContext);
1873 else if (compare)
1874 ret = cert_compare_certs_in_store(hCertStore, pPrevCertContext,
1875 compare, dwType, dwFlags, pvPara);
1876 else
1877 ret = NULL;
1878 if (!ret)
1879 SetLastError(CRYPT_E_NOT_FOUND);
1880 TRACE("returning %p\n", ret);
1881 return ret;
1884 PCCERT_CONTEXT WINAPI CertGetSubjectCertificateFromStore(HCERTSTORE hCertStore,
1885 DWORD dwCertEncodingType, PCERT_INFO pCertId)
1887 TRACE("(%p, %08lx, %p)\n", hCertStore, dwCertEncodingType, pCertId);
1889 if (!pCertId)
1891 SetLastError(E_INVALIDARG);
1892 return NULL;
1894 return CertFindCertificateInStore(hCertStore, dwCertEncodingType, 0,
1895 CERT_FIND_SUBJECT_CERT, pCertId, NULL);
1898 BOOL WINAPI CertVerifySubjectCertificateContext(PCCERT_CONTEXT pSubject,
1899 PCCERT_CONTEXT pIssuer, DWORD *pdwFlags)
1901 static const DWORD supportedFlags = CERT_STORE_REVOCATION_FLAG |
1902 CERT_STORE_SIGNATURE_FLAG | CERT_STORE_TIME_VALIDITY_FLAG;
1904 if (*pdwFlags & ~supportedFlags)
1906 SetLastError(E_INVALIDARG);
1907 return FALSE;
1909 if (*pdwFlags & CERT_STORE_REVOCATION_FLAG)
1911 DWORD flags = 0;
1912 PCCRL_CONTEXT crl = CertGetCRLFromStore(pSubject->hCertStore, pSubject,
1913 NULL, &flags);
1915 /* FIXME: what if the CRL has expired? */
1916 if (crl)
1918 if (CertVerifyCRLRevocation(pSubject->dwCertEncodingType,
1919 pSubject->pCertInfo, 1, (PCRL_INFO *)&crl->pCrlInfo))
1920 *pdwFlags &= CERT_STORE_REVOCATION_FLAG;
1922 else
1923 *pdwFlags |= CERT_STORE_NO_CRL_FLAG;
1925 if (*pdwFlags & CERT_STORE_TIME_VALIDITY_FLAG)
1927 if (0 == CertVerifyTimeValidity(NULL, pSubject->pCertInfo))
1928 *pdwFlags &= ~CERT_STORE_TIME_VALIDITY_FLAG;
1930 if (*pdwFlags & CERT_STORE_SIGNATURE_FLAG)
1932 if (CryptVerifyCertificateSignatureEx(0, pSubject->dwCertEncodingType,
1933 CRYPT_VERIFY_CERT_SIGN_SUBJECT_CERT, (void *)pSubject,
1934 CRYPT_VERIFY_CERT_SIGN_ISSUER_CERT, (void *)pIssuer, 0, NULL))
1935 *pdwFlags &= ~CERT_STORE_SIGNATURE_FLAG;
1937 return TRUE;
1940 PCCERT_CONTEXT WINAPI CertGetIssuerCertificateFromStore(HCERTSTORE hCertStore,
1941 PCCERT_CONTEXT pSubjectContext, PCCERT_CONTEXT pPrevIssuerContext,
1942 DWORD *pdwFlags)
1944 PCCERT_CONTEXT ret;
1946 TRACE("(%p, %p, %p, %08lx)\n", hCertStore, pSubjectContext,
1947 pPrevIssuerContext, *pdwFlags);
1949 if (!pSubjectContext)
1951 SetLastError(E_INVALIDARG);
1952 return NULL;
1955 ret = CertFindCertificateInStore(hCertStore,
1956 pSubjectContext->dwCertEncodingType, 0, CERT_FIND_ISSUER_OF,
1957 pSubjectContext, pPrevIssuerContext);
1958 if (ret)
1960 if (!CertVerifySubjectCertificateContext(pSubjectContext, ret,
1961 pdwFlags))
1963 CertFreeCertificateContext(ret);
1964 ret = NULL;
1966 if (CRYPT_IsCertificateSelfSigned(pSubjectContext))
1968 CertFreeCertificateContext(ret);
1969 ret = NULL;
1970 SetLastError(CRYPT_E_SELF_SIGNED);
1973 TRACE("returning %p\n", ret);
1974 return ret;
1977 typedef struct _OLD_CERT_REVOCATION_STATUS {
1978 DWORD cbSize;
1979 DWORD dwIndex;
1980 DWORD dwError;
1981 DWORD dwReason;
1982 } OLD_CERT_REVOCATION_STATUS;
1984 typedef BOOL (WINAPI *CertVerifyRevocationFunc)(DWORD, DWORD, DWORD,
1985 void **, DWORD, PCERT_REVOCATION_PARA, PCERT_REVOCATION_STATUS);
1987 BOOL WINAPI CertVerifyRevocation(DWORD dwEncodingType, DWORD dwRevType,
1988 DWORD cContext, PVOID rgpvContext[], DWORD dwFlags,
1989 PCERT_REVOCATION_PARA pRevPara, PCERT_REVOCATION_STATUS pRevStatus)
1991 BOOL ret;
1993 TRACE("(%08lx, %ld, %ld, %p, %08lx, %p, %p)\n", dwEncodingType, dwRevType,
1994 cContext, rgpvContext, dwFlags, pRevPara, pRevStatus);
1996 if (pRevStatus->cbSize != sizeof(OLD_CERT_REVOCATION_STATUS) &&
1997 pRevStatus->cbSize != sizeof(CERT_REVOCATION_STATUS))
1999 SetLastError(E_INVALIDARG);
2000 return FALSE;
2002 if (cContext)
2004 static HCRYPTOIDFUNCSET set = NULL;
2005 DWORD size;
2007 if (!set)
2008 set = CryptInitOIDFunctionSet(CRYPT_OID_VERIFY_REVOCATION_FUNC, 0);
2009 ret = CryptGetDefaultOIDDllList(set, dwEncodingType, NULL, &size);
2010 if (ret)
2012 if (size == 1)
2014 /* empty list */
2015 SetLastError(CRYPT_E_NO_REVOCATION_DLL);
2016 ret = FALSE;
2018 else
2020 LPWSTR dllList = CryptMemAlloc(size * sizeof(WCHAR)), ptr;
2022 if (dllList)
2024 ret = CryptGetDefaultOIDDllList(set, dwEncodingType,
2025 dllList, &size);
2026 if (ret)
2028 for (ptr = dllList; ret && *ptr;
2029 ptr += lstrlenW(ptr) + 1)
2031 CertVerifyRevocationFunc func;
2032 HCRYPTOIDFUNCADDR hFunc;
2034 ret = CryptGetDefaultOIDFunctionAddress(set,
2035 dwEncodingType, ptr, 0, (void **)&func, &hFunc);
2036 if (ret)
2038 ret = func(dwEncodingType, dwRevType, cContext,
2039 rgpvContext, dwFlags, pRevPara, pRevStatus);
2040 CryptFreeOIDFunctionAddress(hFunc, 0);
2044 CryptMemFree(dllList);
2046 else
2048 SetLastError(ERROR_OUTOFMEMORY);
2049 ret = FALSE;
2054 else
2055 ret = TRUE;
2056 return ret;
2059 PCRYPT_ATTRIBUTE WINAPI CertFindAttribute(LPCSTR pszObjId, DWORD cAttr,
2060 CRYPT_ATTRIBUTE rgAttr[])
2062 PCRYPT_ATTRIBUTE ret = NULL;
2063 DWORD i;
2065 TRACE("%s %ld %p\n", debugstr_a(pszObjId), cAttr, rgAttr);
2067 if (!cAttr)
2068 return NULL;
2069 if (!pszObjId)
2071 SetLastError(ERROR_INVALID_PARAMETER);
2072 return NULL;
2075 for (i = 0; !ret && i < cAttr; i++)
2076 if (rgAttr[i].pszObjId && !strcmp(pszObjId, rgAttr[i].pszObjId))
2077 ret = &rgAttr[i];
2078 return ret;
2081 PCERT_EXTENSION WINAPI CertFindExtension(LPCSTR pszObjId, DWORD cExtensions,
2082 CERT_EXTENSION rgExtensions[])
2084 PCERT_EXTENSION ret = NULL;
2085 DWORD i;
2087 TRACE("%s %ld %p\n", debugstr_a(pszObjId), cExtensions, rgExtensions);
2089 if (!cExtensions)
2090 return NULL;
2091 if (!pszObjId)
2093 SetLastError(ERROR_INVALID_PARAMETER);
2094 return NULL;
2097 for (i = 0; !ret && i < cExtensions; i++)
2098 if (rgExtensions[i].pszObjId && !strcmp(pszObjId,
2099 rgExtensions[i].pszObjId))
2100 ret = &rgExtensions[i];
2101 return ret;
2104 PCERT_RDN_ATTR WINAPI CertFindRDNAttr(LPCSTR pszObjId, PCERT_NAME_INFO pName)
2106 PCERT_RDN_ATTR ret = NULL;
2107 DWORD i, j;
2109 TRACE("%s %p\n", debugstr_a(pszObjId), pName);
2111 if (!pszObjId)
2113 SetLastError(ERROR_INVALID_PARAMETER);
2114 return NULL;
2117 for (i = 0; !ret && i < pName->cRDN; i++)
2118 for (j = 0; !ret && j < pName->rgRDN[i].cRDNAttr; j++)
2119 if (pName->rgRDN[i].rgRDNAttr[j].pszObjId && !strcmp(pszObjId,
2120 pName->rgRDN[i].rgRDNAttr[j].pszObjId))
2121 ret = &pName->rgRDN[i].rgRDNAttr[j];
2122 return ret;
2125 static BOOL find_matching_rdn_attr(DWORD dwFlags, const CERT_NAME_INFO *name,
2126 const CERT_RDN_ATTR *attr)
2128 DWORD i, j;
2129 BOOL match = FALSE;
2131 for (i = 0; !match && i < name->cRDN; i++)
2133 for (j = 0; j < name->rgRDN[i].cRDNAttr; j++)
2135 if (!strcmp(name->rgRDN[i].rgRDNAttr[j].pszObjId,
2136 attr->pszObjId) &&
2137 name->rgRDN[i].rgRDNAttr[j].dwValueType ==
2138 attr->dwValueType)
2140 if (dwFlags & CERT_UNICODE_IS_RDN_ATTRS_FLAG)
2142 LPCWSTR nameStr =
2143 (LPCWSTR)name->rgRDN[i].rgRDNAttr[j].Value.pbData;
2144 LPCWSTR attrStr = (LPCWSTR)attr->Value.pbData;
2146 if (attr->Value.cbData !=
2147 name->rgRDN[i].rgRDNAttr[j].Value.cbData)
2148 match = FALSE;
2149 else if (dwFlags & CERT_CASE_INSENSITIVE_IS_RDN_ATTRS_FLAG)
2150 match = !wcsnicmp(nameStr, attrStr,
2151 attr->Value.cbData / sizeof(WCHAR));
2152 else
2153 match = !wcsncmp(nameStr, attrStr,
2154 attr->Value.cbData / sizeof(WCHAR));
2155 TRACE("%s : %s => %d\n",
2156 debugstr_wn(nameStr, attr->Value.cbData / sizeof(WCHAR)),
2157 debugstr_wn(attrStr, attr->Value.cbData / sizeof(WCHAR)),
2158 match);
2160 else
2162 LPCSTR nameStr =
2163 (LPCSTR)name->rgRDN[i].rgRDNAttr[j].Value.pbData;
2164 LPCSTR attrStr = (LPCSTR)attr->Value.pbData;
2166 if (attr->Value.cbData !=
2167 name->rgRDN[i].rgRDNAttr[j].Value.cbData)
2168 match = FALSE;
2169 else if (dwFlags & CERT_CASE_INSENSITIVE_IS_RDN_ATTRS_FLAG)
2170 match = !_strnicmp(nameStr, attrStr,
2171 attr->Value.cbData);
2172 else
2173 match = !strncmp(nameStr, attrStr, attr->Value.cbData);
2174 TRACE("%s : %s => %d\n",
2175 debugstr_an(nameStr, attr->Value.cbData),
2176 debugstr_an(attrStr, attr->Value.cbData), match);
2181 return match;
2184 BOOL WINAPI CertIsRDNAttrsInCertificateName(DWORD dwCertEncodingType,
2185 DWORD dwFlags, PCERT_NAME_BLOB pCertName, PCERT_RDN pRDN)
2187 CERT_NAME_INFO *name;
2188 LPCSTR type;
2189 DWORD size;
2190 BOOL ret;
2192 TRACE("(%08lx, %08lx, %p, %p)\n", dwCertEncodingType, dwFlags, pCertName,
2193 pRDN);
2195 type = dwFlags & CERT_UNICODE_IS_RDN_ATTRS_FLAG ? X509_UNICODE_NAME :
2196 X509_NAME;
2197 if ((ret = CryptDecodeObjectEx(dwCertEncodingType, type, pCertName->pbData,
2198 pCertName->cbData, CRYPT_DECODE_ALLOC_FLAG, NULL, &name, &size)))
2200 DWORD i;
2202 for (i = 0; ret && i < pRDN->cRDNAttr; i++)
2203 ret = find_matching_rdn_attr(dwFlags, name, &pRDN->rgRDNAttr[i]);
2204 if (!ret)
2205 SetLastError(CRYPT_E_NO_MATCH);
2206 LocalFree(name);
2208 return ret;
2211 LONG WINAPI CertVerifyTimeValidity(LPFILETIME pTimeToVerify,
2212 PCERT_INFO pCertInfo)
2214 FILETIME fileTime;
2215 LONG ret;
2217 if (!pTimeToVerify)
2219 GetSystemTimeAsFileTime(&fileTime);
2220 pTimeToVerify = &fileTime;
2222 if ((ret = CompareFileTime(pTimeToVerify, &pCertInfo->NotBefore)) >= 0)
2224 ret = CompareFileTime(pTimeToVerify, &pCertInfo->NotAfter);
2225 if (ret < 0)
2226 ret = 0;
2228 return ret;
2231 BOOL WINAPI CertVerifyValidityNesting(PCERT_INFO pSubjectInfo,
2232 PCERT_INFO pIssuerInfo)
2234 TRACE("(%p, %p)\n", pSubjectInfo, pIssuerInfo);
2236 return CertVerifyTimeValidity(&pSubjectInfo->NotBefore, pIssuerInfo) == 0
2237 && CertVerifyTimeValidity(&pSubjectInfo->NotAfter, pIssuerInfo) == 0;
2240 BOOL WINAPI CryptHashCertificate(HCRYPTPROV_LEGACY hCryptProv, ALG_ID Algid,
2241 DWORD dwFlags, const BYTE *pbEncoded, DWORD cbEncoded, BYTE *pbComputedHash,
2242 DWORD *pcbComputedHash)
2244 BOOL ret = TRUE;
2245 HCRYPTHASH hHash = 0;
2247 TRACE("(%08Ix, %d, %08lx, %p, %ld, %p, %p)\n", hCryptProv, Algid, dwFlags,
2248 pbEncoded, cbEncoded, pbComputedHash, pcbComputedHash);
2250 if (!hCryptProv)
2251 hCryptProv = I_CryptGetDefaultCryptProv(Algid);
2252 if (!Algid)
2253 Algid = CALG_SHA1;
2254 if (ret)
2256 ret = CryptCreateHash(hCryptProv, Algid, 0, 0, &hHash);
2257 if (ret)
2259 ret = CryptHashData(hHash, pbEncoded, cbEncoded, 0);
2260 if (ret)
2261 ret = CryptGetHashParam(hHash, HP_HASHVAL, pbComputedHash,
2262 pcbComputedHash, 0);
2263 CryptDestroyHash(hHash);
2266 return ret;
2269 BOOL WINAPI CryptHashCertificate2(LPCWSTR pwszCNGHashAlgid, DWORD dwFlags,
2270 void *pvReserved, const BYTE *pbEncoded, DWORD cbEncoded, BYTE *pbComputedHash,
2271 DWORD *pcbComputedHash)
2273 BCRYPT_HASH_HANDLE hash = NULL;
2274 BCRYPT_ALG_HANDLE alg = NULL;
2275 NTSTATUS status;
2276 DWORD hash_len;
2277 DWORD hash_len_size;
2279 TRACE("(%s, %08lx, %p, %p, %ld, %p, %p)\n", debugstr_w(pwszCNGHashAlgid),
2280 dwFlags, pvReserved, pbEncoded, cbEncoded, pbComputedHash, pcbComputedHash);
2282 if ((status = BCryptOpenAlgorithmProvider(&alg, pwszCNGHashAlgid, NULL, 0)))
2284 if (status == STATUS_NOT_IMPLEMENTED)
2285 status = STATUS_NOT_FOUND;
2286 goto done;
2289 if ((status = BCryptCreateHash(alg, &hash, NULL, 0, NULL, 0, 0)))
2290 goto done;
2292 if ((status = BCryptGetProperty(hash, BCRYPT_HASH_LENGTH, (BYTE *)&hash_len, sizeof(hash_len), &hash_len_size, 0)))
2293 goto done;
2295 if (!pbComputedHash)
2297 *pcbComputedHash = hash_len;
2298 goto done;
2301 if (*pcbComputedHash < hash_len)
2303 status = ERROR_MORE_DATA;
2304 goto done;
2307 *pcbComputedHash = hash_len;
2309 if ((status = BCryptHashData(hash, (BYTE *)pbEncoded, cbEncoded, 0)))
2310 goto done;
2312 if ((status = BCryptFinishHash(hash, pbComputedHash, hash_len, 0)))
2313 goto done;
2315 done:
2316 if (hash) BCryptDestroyHash(hash);
2317 if (alg) BCryptCloseAlgorithmProvider(alg, 0);
2318 if (status) SetLastError(status);
2319 return !status;
2322 BOOL WINAPI CryptHashPublicKeyInfo(HCRYPTPROV_LEGACY hCryptProv, ALG_ID Algid,
2323 DWORD dwFlags, DWORD dwCertEncodingType, PCERT_PUBLIC_KEY_INFO pInfo,
2324 BYTE *pbComputedHash, DWORD *pcbComputedHash)
2326 BOOL ret = TRUE;
2327 HCRYPTHASH hHash = 0;
2329 TRACE("(%08Ix, %d, %08lx, %ld, %p, %p, %p)\n", hCryptProv, Algid, dwFlags,
2330 dwCertEncodingType, pInfo, pbComputedHash, pcbComputedHash);
2332 if (!hCryptProv)
2333 hCryptProv = I_CryptGetDefaultCryptProv(0);
2334 if (!Algid)
2335 Algid = CALG_MD5;
2336 if ((dwCertEncodingType & CERT_ENCODING_TYPE_MASK) != X509_ASN_ENCODING)
2338 SetLastError(ERROR_FILE_NOT_FOUND);
2339 return FALSE;
2341 if (ret)
2343 BYTE *buf;
2344 DWORD size = 0;
2346 ret = CRYPT_AsnEncodePubKeyInfoNoNull(dwCertEncodingType,
2347 X509_PUBLIC_KEY_INFO, pInfo, CRYPT_ENCODE_ALLOC_FLAG, NULL,
2348 (LPBYTE)&buf, &size);
2349 if (ret)
2351 ret = CryptCreateHash(hCryptProv, Algid, 0, 0, &hHash);
2352 if (ret)
2354 ret = CryptHashData(hHash, buf, size, 0);
2355 if (ret)
2356 ret = CryptGetHashParam(hHash, HP_HASHVAL, pbComputedHash,
2357 pcbComputedHash, 0);
2358 CryptDestroyHash(hHash);
2360 LocalFree(buf);
2363 return ret;
2366 BOOL WINAPI CryptHashToBeSigned(HCRYPTPROV_LEGACY hCryptProv,
2367 DWORD dwCertEncodingType, const BYTE *pbEncoded, DWORD cbEncoded,
2368 BYTE *pbComputedHash, DWORD *pcbComputedHash)
2370 BOOL ret;
2371 CERT_SIGNED_CONTENT_INFO *info;
2372 DWORD size;
2374 TRACE("(%08Ix, %08lx, %p, %ld, %p, %ld)\n", hCryptProv, dwCertEncodingType,
2375 pbEncoded, cbEncoded, pbComputedHash, *pcbComputedHash);
2377 ret = CryptDecodeObjectEx(dwCertEncodingType, X509_CERT,
2378 pbEncoded, cbEncoded, CRYPT_DECODE_ALLOC_FLAG, NULL, &info, &size);
2379 if (ret)
2381 PCCRYPT_OID_INFO oidInfo;
2382 HCRYPTHASH hHash;
2384 if (!hCryptProv)
2385 hCryptProv = I_CryptGetDefaultCryptProv(0);
2386 oidInfo = CryptFindOIDInfo(CRYPT_OID_INFO_OID_KEY,
2387 info->SignatureAlgorithm.pszObjId, 0);
2388 if (!oidInfo)
2390 SetLastError(NTE_BAD_ALGID);
2391 ret = FALSE;
2393 else
2395 ret = CryptCreateHash(hCryptProv, oidInfo->u.Algid, 0, 0, &hHash);
2396 if (ret)
2398 ret = CryptHashData(hHash, info->ToBeSigned.pbData,
2399 info->ToBeSigned.cbData, 0);
2400 if (ret)
2401 ret = CryptGetHashParam(hHash, HP_HASHVAL, pbComputedHash,
2402 pcbComputedHash, 0);
2403 CryptDestroyHash(hHash);
2406 LocalFree(info);
2408 return ret;
2411 BOOL WINAPI CryptSignCertificate(HCRYPTPROV_OR_NCRYPT_KEY_HANDLE hCryptProv,
2412 DWORD dwKeySpec, DWORD dwCertEncodingType, const BYTE *pbEncodedToBeSigned,
2413 DWORD cbEncodedToBeSigned, PCRYPT_ALGORITHM_IDENTIFIER pSignatureAlgorithm,
2414 const void *pvHashAuxInfo, BYTE *pbSignature, DWORD *pcbSignature)
2416 BOOL ret;
2417 PCCRYPT_OID_INFO info;
2418 HCRYPTHASH hHash;
2420 TRACE("(%08Ix, %ld, %ld, %p, %ld, %p, %p, %p, %p)\n", hCryptProv,
2421 dwKeySpec, dwCertEncodingType, pbEncodedToBeSigned, cbEncodedToBeSigned,
2422 pSignatureAlgorithm, pvHashAuxInfo, pbSignature, pcbSignature);
2424 info = CryptFindOIDInfo(CRYPT_OID_INFO_OID_KEY,
2425 pSignatureAlgorithm->pszObjId, 0);
2426 if (!info)
2428 SetLastError(NTE_BAD_ALGID);
2429 return FALSE;
2431 if (info->dwGroupId == CRYPT_HASH_ALG_OID_GROUP_ID)
2433 if (!hCryptProv)
2434 hCryptProv = I_CryptGetDefaultCryptProv(0);
2435 ret = CryptCreateHash(hCryptProv, info->u.Algid, 0, 0, &hHash);
2436 if (ret)
2438 ret = CryptHashData(hHash, pbEncodedToBeSigned,
2439 cbEncodedToBeSigned, 0);
2440 if (ret)
2441 ret = CryptGetHashParam(hHash, HP_HASHVAL, pbSignature,
2442 pcbSignature, 0);
2443 CryptDestroyHash(hHash);
2446 else
2448 if (!hCryptProv)
2450 SetLastError(ERROR_INVALID_PARAMETER);
2451 ret = FALSE;
2453 else
2455 ret = CryptCreateHash(hCryptProv, info->u.Algid, 0, 0, &hHash);
2456 if (ret)
2458 ret = CryptHashData(hHash, pbEncodedToBeSigned,
2459 cbEncodedToBeSigned, 0);
2460 if (ret)
2461 ret = CryptSignHashW(hHash, dwKeySpec, NULL, 0, pbSignature,
2462 pcbSignature);
2463 CryptDestroyHash(hHash);
2467 return ret;
2470 BOOL WINAPI CryptSignAndEncodeCertificate(HCRYPTPROV_OR_NCRYPT_KEY_HANDLE hCryptProv,
2471 DWORD dwKeySpec, DWORD dwCertEncodingType, LPCSTR lpszStructType,
2472 const void *pvStructInfo, PCRYPT_ALGORITHM_IDENTIFIER pSignatureAlgorithm,
2473 const void *pvHashAuxInfo, BYTE *pbEncoded, DWORD *pcbEncoded)
2475 BOOL ret;
2476 DWORD encodedSize, hashSize;
2478 TRACE("(%08Ix, %ld, %ld, %s, %p, %p, %p, %p, %p)\n", hCryptProv, dwKeySpec,
2479 dwCertEncodingType, debugstr_a(lpszStructType), pvStructInfo,
2480 pSignatureAlgorithm, pvHashAuxInfo, pbEncoded, pcbEncoded);
2482 ret = CryptEncodeObject(dwCertEncodingType, lpszStructType, pvStructInfo,
2483 NULL, &encodedSize);
2484 if (ret)
2486 PBYTE encoded = CryptMemAlloc(encodedSize);
2488 if (encoded)
2490 ret = CryptEncodeObject(dwCertEncodingType, lpszStructType,
2491 pvStructInfo, encoded, &encodedSize);
2492 if (ret)
2494 ret = CryptSignCertificate(hCryptProv, dwKeySpec,
2495 dwCertEncodingType, encoded, encodedSize, pSignatureAlgorithm,
2496 pvHashAuxInfo, NULL, &hashSize);
2497 if (ret)
2499 PBYTE hash = CryptMemAlloc(hashSize);
2501 if (hash)
2503 ret = CryptSignCertificate(hCryptProv, dwKeySpec,
2504 dwCertEncodingType, encoded, encodedSize,
2505 pSignatureAlgorithm, pvHashAuxInfo, hash, &hashSize);
2506 if (ret)
2508 CERT_SIGNED_CONTENT_INFO info = { { 0 } };
2510 info.ToBeSigned.cbData = encodedSize;
2511 info.ToBeSigned.pbData = encoded;
2512 info.SignatureAlgorithm = *pSignatureAlgorithm;
2513 info.Signature.cbData = hashSize;
2514 info.Signature.pbData = hash;
2515 info.Signature.cUnusedBits = 0;
2516 ret = CryptEncodeObject(dwCertEncodingType,
2517 X509_CERT, &info, pbEncoded, pcbEncoded);
2519 CryptMemFree(hash);
2521 else
2522 ret = FALSE;
2525 CryptMemFree(encoded);
2527 else
2528 ret = FALSE;
2530 return ret;
2533 BOOL WINAPI CryptVerifyCertificateSignature(HCRYPTPROV_LEGACY hCryptProv,
2534 DWORD dwCertEncodingType, const BYTE *pbEncoded, DWORD cbEncoded,
2535 PCERT_PUBLIC_KEY_INFO pPublicKey)
2537 CRYPT_DATA_BLOB blob = { cbEncoded, (BYTE *)pbEncoded };
2539 return CryptVerifyCertificateSignatureEx(hCryptProv, dwCertEncodingType,
2540 CRYPT_VERIFY_CERT_SIGN_SUBJECT_BLOB, &blob,
2541 CRYPT_VERIFY_CERT_SIGN_ISSUER_PUBKEY, pPublicKey, 0, NULL);
2544 static BOOL CRYPT_VerifySignature(HCRYPTPROV_LEGACY hCryptProv, DWORD dwCertEncodingType,
2545 CERT_PUBLIC_KEY_INFO *pubKeyInfo, const CERT_SIGNED_CONTENT_INFO *signedCert, const CRYPT_OID_INFO *info)
2547 BOOL ret;
2548 HCRYPTKEY key;
2549 ALG_ID pubKeyID, hashID;
2551 hashID = info->u.Algid;
2552 if (info->ExtraInfo.cbData >= sizeof(ALG_ID))
2553 pubKeyID = *(ALG_ID *)info->ExtraInfo.pbData;
2554 else
2555 pubKeyID = hashID;
2556 /* Load the default provider if necessary */
2557 if (!hCryptProv)
2558 hCryptProv = I_CryptGetDefaultCryptProv(hashID);
2559 ret = CryptImportPublicKeyInfoEx(hCryptProv, dwCertEncodingType,
2560 pubKeyInfo, pubKeyID, 0, NULL, &key);
2561 if (ret)
2563 HCRYPTHASH hash;
2565 ret = CryptCreateHash(hCryptProv, hashID, 0, 0, &hash);
2566 if (ret)
2568 ret = CryptHashData(hash, signedCert->ToBeSigned.pbData,
2569 signedCert->ToBeSigned.cbData, 0);
2570 if (ret)
2571 ret = CryptVerifySignatureW(hash, signedCert->Signature.pbData,
2572 signedCert->Signature.cbData, key, NULL, 0);
2573 CryptDestroyHash(hash);
2575 CryptDestroyKey(key);
2577 return ret;
2580 static BOOL CNG_CalcHash(const WCHAR *algorithm, const CERT_SIGNED_CONTENT_INFO *signedCert,
2581 BYTE **hash_value, DWORD *hash_len)
2583 BCRYPT_HASH_HANDLE hash = NULL;
2584 BCRYPT_ALG_HANDLE alg = NULL;
2585 NTSTATUS status;
2586 DWORD size;
2588 if ((status = BCryptOpenAlgorithmProvider(&alg, algorithm, NULL, 0)))
2589 goto done;
2591 if ((status = BCryptCreateHash(alg, &hash, NULL, 0, NULL, 0, 0)))
2592 goto done;
2594 if ((status = BCryptHashData(hash, signedCert->ToBeSigned.pbData, signedCert->ToBeSigned.cbData, 0)))
2595 goto done;
2597 if ((status = BCryptGetProperty(hash, BCRYPT_HASH_LENGTH, (BYTE *)hash_len, sizeof(*hash_len), &size, 0)))
2598 goto done;
2600 if (!(*hash_value = CryptMemAlloc(*hash_len)))
2602 status = STATUS_NO_MEMORY;
2603 goto done;
2606 if ((status = BCryptFinishHash(hash, *hash_value, *hash_len, 0)))
2608 CryptMemFree(*hash_value);
2609 goto done;
2612 done:
2613 if (hash) BCryptDestroyHash(hash);
2614 if (alg) BCryptCloseAlgorithmProvider(alg, 0);
2615 if (status) SetLastError(RtlNtStatusToDosError(status));
2616 return status == 0;
2619 static BOOL CNG_ImportECCPubKey(CERT_PUBLIC_KEY_INFO *pubKeyInfo, BCRYPT_KEY_HANDLE *key)
2621 DWORD blob_magic, ecckey_len, size;
2622 BCRYPT_ALG_HANDLE alg = NULL;
2623 BCRYPT_ECCKEY_BLOB *ecckey;
2624 const WCHAR *sign_algo;
2625 char **ecc_curve;
2626 NTSTATUS status;
2628 if (!pubKeyInfo->PublicKey.cbData)
2630 SetLastError(NTE_BAD_ALGID);
2631 return FALSE;
2634 if (pubKeyInfo->PublicKey.pbData[0] != 0x4)
2636 FIXME("Compressed ECC curves (%02x) not yet supported\n", pubKeyInfo->PublicKey.pbData[0]);
2637 SetLastError(NTE_BAD_ALGID);
2638 return FALSE;
2641 if (!CryptDecodeObjectEx(X509_ASN_ENCODING, X509_OBJECT_IDENTIFIER, pubKeyInfo->Algorithm.Parameters.pbData,
2642 pubKeyInfo->Algorithm.Parameters.cbData, CRYPT_DECODE_ALLOC_FLAG, NULL, &ecc_curve, &size))
2643 return FALSE;
2645 if (!strcmp(*ecc_curve, szOID_ECC_CURVE_P256))
2647 sign_algo = BCRYPT_ECDSA_P256_ALGORITHM;
2648 blob_magic = BCRYPT_ECDSA_PUBLIC_P256_MAGIC;
2650 else if (!strcmp(*ecc_curve, szOID_ECC_CURVE_P384))
2652 sign_algo = BCRYPT_ECDSA_P384_ALGORITHM;
2653 blob_magic = BCRYPT_ECDSA_PUBLIC_P384_MAGIC;
2655 else
2657 FIXME("Unsupported ecc curve type: %s\n", *ecc_curve);
2658 sign_algo = NULL;
2659 blob_magic = 0;
2661 LocalFree(ecc_curve);
2663 if (!sign_algo)
2665 SetLastError(NTE_BAD_ALGID);
2666 return FALSE;
2669 if ((status = BCryptOpenAlgorithmProvider(&alg, sign_algo, NULL, 0)))
2670 goto done;
2672 ecckey_len = sizeof(BCRYPT_ECCKEY_BLOB) + pubKeyInfo->PublicKey.cbData - 1;
2673 if (!(ecckey = CryptMemAlloc(ecckey_len)))
2675 status = STATUS_NO_MEMORY;
2676 goto done;
2679 ecckey->dwMagic = blob_magic;
2680 ecckey->cbKey = (pubKeyInfo->PublicKey.cbData - 1) / 2;
2681 memcpy(ecckey + 1, pubKeyInfo->PublicKey.pbData + 1, pubKeyInfo->PublicKey.cbData - 1);
2683 status = BCryptImportKeyPair(alg, NULL, BCRYPT_ECCPUBLIC_BLOB, key, (BYTE*)ecckey, ecckey_len, 0);
2684 CryptMemFree(ecckey);
2686 done:
2687 if (alg) BCryptCloseAlgorithmProvider(alg, 0);
2688 if (status) SetLastError(RtlNtStatusToDosError(status));
2689 return !status;
2692 static BOOL CNG_ImportRSAPubKey(CERT_PUBLIC_KEY_INFO *info, BCRYPT_KEY_HANDLE *key)
2694 DWORD size, modulus_len, i;
2695 BLOBHEADER *hdr;
2696 RSAPUBKEY *rsapubkey;
2697 const WCHAR *rsa_algo;
2698 BCRYPT_ALG_HANDLE alg = NULL;
2699 BCRYPT_RSAKEY_BLOB *rsakey;
2700 BYTE *s, *d;
2701 NTSTATUS status;
2703 if (!info->PublicKey.cbData)
2705 SetLastError(NTE_BAD_ALGID);
2706 return FALSE;
2709 if (!CryptDecodeObjectEx(X509_ASN_ENCODING, RSA_CSP_PUBLICKEYBLOB, info->PublicKey.pbData,
2710 info->PublicKey.cbData, CRYPT_DECODE_ALLOC_FLAG, NULL, &hdr, &size))
2712 WARN("CryptDecodeObjectEx failed\n");
2713 return FALSE;
2716 if (hdr->aiKeyAlg == CALG_RSA_KEYX)
2717 rsa_algo = BCRYPT_RSA_ALGORITHM;
2718 else if (hdr->aiKeyAlg == CALG_RSA_SIGN)
2719 rsa_algo = BCRYPT_RSA_SIGN_ALGORITHM;
2720 else
2722 FIXME("Unsupported RSA algorithm: %#x\n", hdr->aiKeyAlg);
2723 LocalFree(hdr);
2724 SetLastError(NTE_BAD_ALGID);
2725 return FALSE;
2728 if ((status = BCryptOpenAlgorithmProvider(&alg, rsa_algo, NULL, 0)))
2729 goto done;
2731 rsapubkey = (RSAPUBKEY *)(hdr + 1);
2733 modulus_len = size - sizeof(*hdr) - sizeof(*rsapubkey);
2734 if (modulus_len != rsapubkey->bitlen / 8)
2735 FIXME("RSA pubkey has wrong modulus_len %lu\n", modulus_len);
2737 size = sizeof(*rsakey) + sizeof(ULONG) + modulus_len;
2739 if (!(rsakey = CryptMemAlloc(size)))
2741 status = STATUS_NO_MEMORY;
2742 goto done;
2745 rsakey->Magic = BCRYPT_RSAPUBLIC_MAGIC;
2746 rsakey->BitLength = rsapubkey->bitlen;
2747 rsakey->cbPublicExp = sizeof(ULONG);
2748 rsakey->cbModulus = modulus_len;
2749 rsakey->cbPrime1 = 0;
2750 rsakey->cbPrime2 = 0;
2752 d = (BYTE *)(rsakey + 1);
2753 /* According to MSDN modulus and pubexp are in LE while
2754 * BCRYPT_RSAKEY_BLOB is supposed to have them in BE format */
2755 *(ULONG *)d = RtlUlongByteSwap(rsapubkey->pubexp);
2756 d += sizeof(ULONG);
2757 s = (BYTE *)(rsapubkey + 1);
2758 for (i = 0; i < modulus_len; i++)
2759 d[i] = s[modulus_len - i - 1];
2761 status = BCryptImportKeyPair(alg, NULL, BCRYPT_RSAPUBLIC_BLOB, key, (BYTE *)rsakey, size, 0);
2762 CryptMemFree(rsakey);
2764 done:
2765 LocalFree(hdr);
2766 if (alg) BCryptCloseAlgorithmProvider(alg, 0);
2767 if (status) SetLastError(RtlNtStatusToDosError(status));
2768 return !status;
2771 BOOL CNG_ImportPubKey(CERT_PUBLIC_KEY_INFO *pubKeyInfo, BCRYPT_KEY_HANDLE *key)
2773 if (!strcmp(pubKeyInfo->Algorithm.pszObjId, szOID_ECC_PUBLIC_KEY))
2774 return CNG_ImportECCPubKey(pubKeyInfo, key);
2776 if (!strcmp(pubKeyInfo->Algorithm.pszObjId, szOID_RSA_RSA))
2777 return CNG_ImportRSAPubKey(pubKeyInfo, key);
2779 FIXME("Unsupported public key type: %s\n", debugstr_a(pubKeyInfo->Algorithm.pszObjId));
2780 SetLastError(NTE_BAD_ALGID);
2781 return FALSE;
2784 static BOOL CNG_PrepareSignatureECC(BYTE *encoded_sig, DWORD encoded_size, BYTE **sig_value, DWORD *sig_len)
2786 CERT_ECC_SIGNATURE *ecc_sig;
2787 DWORD size;
2788 int i;
2790 if (!CryptDecodeObjectEx(X509_ASN_ENCODING, X509_ECC_SIGNATURE, encoded_sig, encoded_size,
2791 CRYPT_DECODE_ALLOC_FLAG, NULL, &ecc_sig, &size))
2792 return FALSE;
2794 if (!ecc_sig->r.cbData || !ecc_sig->s.cbData)
2796 LocalFree(ecc_sig);
2797 SetLastError(ERROR_INVALID_DATA);
2798 return FALSE;
2801 *sig_len = ecc_sig->r.cbData + ecc_sig->s.cbData;
2802 if (!(*sig_value = CryptMemAlloc(*sig_len)))
2804 LocalFree(ecc_sig);
2805 SetLastError(ERROR_OUTOFMEMORY);
2806 return FALSE;
2809 for (i = 0; i < ecc_sig->r.cbData; i++)
2810 (*sig_value)[i] = ecc_sig->r.pbData[ecc_sig->r.cbData - i - 1];
2811 for (i = 0; i < ecc_sig->s.cbData; i++)
2812 (*sig_value)[ecc_sig->r.cbData + i] = ecc_sig->s.pbData[ecc_sig->s.cbData - i - 1];
2814 LocalFree(ecc_sig);
2815 return TRUE;
2818 static BOOL CNG_PrepareSignature(CERT_PUBLIC_KEY_INFO *pubKeyInfo, const CERT_SIGNED_CONTENT_INFO *signedCert,
2819 BYTE **sig_value, DWORD *sig_len)
2821 BYTE *encoded_sig;
2822 BOOL ret = FALSE;
2823 int i;
2825 if (!signedCert->Signature.cbData)
2827 SetLastError(ERROR_INVALID_DATA);
2828 return FALSE;
2831 if (!(encoded_sig = CryptMemAlloc(signedCert->Signature.cbData)))
2833 SetLastError(ERROR_OUTOFMEMORY);
2834 return FALSE;
2837 for (i = 0; i < signedCert->Signature.cbData; i++)
2838 encoded_sig[i] = signedCert->Signature.pbData[signedCert->Signature.cbData - i - 1];
2840 if (!strcmp(pubKeyInfo->Algorithm.pszObjId, szOID_ECC_PUBLIC_KEY))
2841 ret = CNG_PrepareSignatureECC(encoded_sig, signedCert->Signature.cbData, sig_value, sig_len);
2842 else
2844 FIXME("Unsupported public key type: %s\n", debugstr_a(pubKeyInfo->Algorithm.pszObjId));
2845 SetLastError(NTE_BAD_ALGID);
2848 CryptMemFree(encoded_sig);
2849 return ret;
2852 static BOOL CNG_VerifySignature(HCRYPTPROV_LEGACY hCryptProv, DWORD dwCertEncodingType,
2853 CERT_PUBLIC_KEY_INFO *pubKeyInfo, const CERT_SIGNED_CONTENT_INFO *signedCert, const CRYPT_OID_INFO *info)
2855 BCRYPT_KEY_HANDLE key = NULL;
2856 BYTE *hash_value = NULL, *sig_value;
2857 DWORD hash_len, sig_len;
2858 NTSTATUS status;
2859 BOOL ret;
2861 ret = CNG_ImportPubKey(pubKeyInfo, &key);
2862 if (ret)
2864 ret = CNG_CalcHash(info->pwszCNGAlgid, signedCert, &hash_value, &hash_len);
2865 if (ret)
2867 ret = CNG_PrepareSignature(pubKeyInfo, signedCert, &sig_value, &sig_len);
2868 if (ret)
2870 status = BCryptVerifySignature(key, NULL, hash_value, hash_len, sig_value, sig_len, 0);
2871 if (status)
2873 FIXME("Failed to verify signature: %08lx\n", status);
2874 SetLastError(RtlNtStatusToDosError(status));
2875 ret = FALSE;
2877 CryptMemFree(sig_value);
2879 CryptMemFree(hash_value);
2881 BCryptDestroyKey(key);
2884 return ret;
2887 static BOOL CRYPT_VerifyCertSignatureFromPublicKeyInfo(HCRYPTPROV_LEGACY hCryptProv, DWORD dwCertEncodingType,
2888 CERT_PUBLIC_KEY_INFO *pubKeyInfo, const CERT_SIGNED_CONTENT_INFO *signedCert)
2890 CCRYPT_OID_INFO *info;
2892 info = CryptFindOIDInfo(CRYPT_OID_INFO_OID_KEY, signedCert->SignatureAlgorithm.pszObjId, 0);
2893 if (!info || info->dwGroupId != CRYPT_SIGN_ALG_OID_GROUP_ID)
2895 SetLastError(NTE_BAD_ALGID);
2896 return FALSE;
2899 if (info->u.Algid == CALG_OID_INFO_CNG_ONLY)
2900 return CNG_VerifySignature(hCryptProv, dwCertEncodingType, pubKeyInfo, signedCert, info);
2901 else
2902 return CRYPT_VerifySignature(hCryptProv, dwCertEncodingType, pubKeyInfo, signedCert, info);
2905 BOOL WINAPI CryptVerifyCertificateSignatureEx(HCRYPTPROV_LEGACY hCryptProv,
2906 DWORD dwCertEncodingType, DWORD dwSubjectType, void *pvSubject,
2907 DWORD dwIssuerType, void *pvIssuer, DWORD dwFlags, void *pvReserved)
2909 BOOL ret = TRUE;
2910 CRYPT_DATA_BLOB subjectBlob;
2912 TRACE("(%08Ix, %ld, %ld, %p, %ld, %p, %08lx, %p)\n", hCryptProv,
2913 dwCertEncodingType, dwSubjectType, pvSubject, dwIssuerType, pvIssuer,
2914 dwFlags, pvReserved);
2916 switch (dwSubjectType)
2918 case CRYPT_VERIFY_CERT_SIGN_SUBJECT_BLOB:
2920 PCRYPT_DATA_BLOB blob = pvSubject;
2922 subjectBlob.pbData = blob->pbData;
2923 subjectBlob.cbData = blob->cbData;
2924 break;
2926 case CRYPT_VERIFY_CERT_SIGN_SUBJECT_CERT:
2928 PCERT_CONTEXT context = pvSubject;
2930 subjectBlob.pbData = context->pbCertEncoded;
2931 subjectBlob.cbData = context->cbCertEncoded;
2932 break;
2934 case CRYPT_VERIFY_CERT_SIGN_SUBJECT_CRL:
2936 PCRL_CONTEXT context = pvSubject;
2938 subjectBlob.pbData = context->pbCrlEncoded;
2939 subjectBlob.cbData = context->cbCrlEncoded;
2940 break;
2942 default:
2943 SetLastError(E_INVALIDARG);
2944 ret = FALSE;
2947 if (ret)
2949 PCERT_SIGNED_CONTENT_INFO signedCert = NULL;
2950 DWORD size = 0;
2952 ret = CryptDecodeObjectEx(dwCertEncodingType, X509_CERT,
2953 subjectBlob.pbData, subjectBlob.cbData,
2954 CRYPT_DECODE_ALLOC_FLAG | CRYPT_DECODE_NOCOPY_FLAG, NULL,
2955 &signedCert, &size);
2956 if (ret)
2958 switch (dwIssuerType)
2960 case CRYPT_VERIFY_CERT_SIGN_ISSUER_PUBKEY:
2961 ret = CRYPT_VerifyCertSignatureFromPublicKeyInfo(hCryptProv,
2962 dwCertEncodingType, pvIssuer,
2963 signedCert);
2964 break;
2965 case CRYPT_VERIFY_CERT_SIGN_ISSUER_CERT:
2966 ret = CRYPT_VerifyCertSignatureFromPublicKeyInfo(hCryptProv,
2967 dwCertEncodingType,
2968 &((PCCERT_CONTEXT)pvIssuer)->pCertInfo->SubjectPublicKeyInfo,
2969 signedCert);
2970 break;
2971 case CRYPT_VERIFY_CERT_SIGN_ISSUER_CHAIN:
2972 FIXME("CRYPT_VERIFY_CERT_SIGN_ISSUER_CHAIN: stub\n");
2973 ret = FALSE;
2974 break;
2975 case CRYPT_VERIFY_CERT_SIGN_ISSUER_NULL:
2976 if (pvIssuer)
2978 SetLastError(E_INVALIDARG);
2979 ret = FALSE;
2981 else
2983 FIXME("unimplemented for NULL signer\n");
2984 SetLastError(E_INVALIDARG);
2985 ret = FALSE;
2987 break;
2988 default:
2989 SetLastError(E_INVALIDARG);
2990 ret = FALSE;
2992 LocalFree(signedCert);
2995 return ret;
2998 BOOL WINAPI CertGetIntendedKeyUsage(DWORD dwCertEncodingType,
2999 PCERT_INFO pCertInfo, BYTE *pbKeyUsage, DWORD cbKeyUsage)
3001 PCERT_EXTENSION ext;
3002 BOOL ret = FALSE;
3004 TRACE("(%08lx, %p, %p, %ld)\n", dwCertEncodingType, pCertInfo, pbKeyUsage,
3005 cbKeyUsage);
3007 ext = CertFindExtension(szOID_KEY_USAGE, pCertInfo->cExtension,
3008 pCertInfo->rgExtension);
3009 if (ext)
3011 CRYPT_BIT_BLOB usage;
3012 DWORD size = sizeof(usage);
3014 ret = CryptDecodeObjectEx(dwCertEncodingType, X509_BITS,
3015 ext->Value.pbData, ext->Value.cbData, CRYPT_DECODE_NOCOPY_FLAG, NULL,
3016 &usage, &size);
3017 if (ret)
3019 if (cbKeyUsage < usage.cbData)
3020 ret = FALSE;
3021 else
3023 memcpy(pbKeyUsage, usage.pbData, usage.cbData);
3024 if (cbKeyUsage > usage.cbData)
3025 memset(pbKeyUsage + usage.cbData, 0,
3026 cbKeyUsage - usage.cbData);
3030 else
3031 SetLastError(0);
3032 return ret;
3035 BOOL WINAPI CertGetEnhancedKeyUsage(PCCERT_CONTEXT pCertContext, DWORD dwFlags,
3036 PCERT_ENHKEY_USAGE pUsage, DWORD *pcbUsage)
3038 PCERT_ENHKEY_USAGE usage = NULL;
3039 DWORD bytesNeeded;
3040 BOOL ret = TRUE;
3042 if (!pCertContext || !pcbUsage)
3044 SetLastError(ERROR_INVALID_PARAMETER);
3045 return FALSE;
3048 TRACE("(%p, %08lx, %p, %ld)\n", pCertContext, dwFlags, pUsage, *pcbUsage);
3050 if (!(dwFlags & CERT_FIND_EXT_ONLY_ENHKEY_USAGE_FLAG))
3052 DWORD propSize = 0;
3054 if (CertGetCertificateContextProperty(pCertContext,
3055 CERT_ENHKEY_USAGE_PROP_ID, NULL, &propSize))
3057 LPBYTE buf = CryptMemAlloc(propSize);
3059 if (buf)
3061 if (CertGetCertificateContextProperty(pCertContext,
3062 CERT_ENHKEY_USAGE_PROP_ID, buf, &propSize))
3064 ret = CryptDecodeObjectEx(pCertContext->dwCertEncodingType,
3065 X509_ENHANCED_KEY_USAGE, buf, propSize,
3066 CRYPT_ENCODE_ALLOC_FLAG, NULL, &usage, &bytesNeeded);
3068 CryptMemFree(buf);
3072 if (!usage && !(dwFlags & CERT_FIND_PROP_ONLY_ENHKEY_USAGE_FLAG))
3074 PCERT_EXTENSION ext = CertFindExtension(szOID_ENHANCED_KEY_USAGE,
3075 pCertContext->pCertInfo->cExtension,
3076 pCertContext->pCertInfo->rgExtension);
3078 if (ext)
3080 ret = CryptDecodeObjectEx(pCertContext->dwCertEncodingType,
3081 X509_ENHANCED_KEY_USAGE, ext->Value.pbData, ext->Value.cbData,
3082 CRYPT_ENCODE_ALLOC_FLAG, NULL, &usage, &bytesNeeded);
3085 if (!usage)
3087 /* If a particular location is specified, this should fail. Otherwise
3088 * it should succeed with an empty usage. (This is true on Win2k and
3089 * later, which we emulate.)
3091 if (dwFlags)
3093 SetLastError(CRYPT_E_NOT_FOUND);
3094 ret = FALSE;
3096 else
3097 bytesNeeded = sizeof(CERT_ENHKEY_USAGE);
3100 if (ret)
3102 if (!pUsage)
3103 *pcbUsage = bytesNeeded;
3104 else if (*pcbUsage < bytesNeeded)
3106 SetLastError(ERROR_MORE_DATA);
3107 *pcbUsage = bytesNeeded;
3108 ret = FALSE;
3110 else
3112 *pcbUsage = bytesNeeded;
3113 if (usage)
3115 DWORD i;
3116 LPSTR nextOID = (LPSTR)((LPBYTE)pUsage +
3117 sizeof(CERT_ENHKEY_USAGE) +
3118 usage->cUsageIdentifier * sizeof(LPSTR));
3120 pUsage->cUsageIdentifier = usage->cUsageIdentifier;
3121 pUsage->rgpszUsageIdentifier = (LPSTR *)((LPBYTE)pUsage +
3122 sizeof(CERT_ENHKEY_USAGE));
3123 for (i = 0; i < usage->cUsageIdentifier; i++)
3125 pUsage->rgpszUsageIdentifier[i] = nextOID;
3126 strcpy(nextOID, usage->rgpszUsageIdentifier[i]);
3127 nextOID += strlen(nextOID) + 1;
3130 else
3131 pUsage->cUsageIdentifier = 0;
3134 if (usage)
3135 LocalFree(usage);
3136 TRACE("returning %d\n", ret);
3137 return ret;
3140 BOOL WINAPI CertSetEnhancedKeyUsage(PCCERT_CONTEXT pCertContext,
3141 PCERT_ENHKEY_USAGE pUsage)
3143 BOOL ret;
3145 TRACE("(%p, %p)\n", pCertContext, pUsage);
3147 if (pUsage)
3149 CRYPT_DATA_BLOB blob = { 0, NULL };
3151 ret = CryptEncodeObjectEx(X509_ASN_ENCODING, X509_ENHANCED_KEY_USAGE,
3152 pUsage, CRYPT_ENCODE_ALLOC_FLAG, NULL, &blob.pbData, &blob.cbData);
3153 if (ret)
3155 ret = CertSetCertificateContextProperty(pCertContext,
3156 CERT_ENHKEY_USAGE_PROP_ID, 0, &blob);
3157 LocalFree(blob.pbData);
3160 else
3161 ret = CertSetCertificateContextProperty(pCertContext,
3162 CERT_ENHKEY_USAGE_PROP_ID, 0, NULL);
3163 return ret;
3166 BOOL WINAPI CertAddEnhancedKeyUsageIdentifier(PCCERT_CONTEXT pCertContext,
3167 LPCSTR pszUsageIdentifier)
3169 BOOL ret;
3170 DWORD size;
3172 TRACE("(%p, %s)\n", pCertContext, debugstr_a(pszUsageIdentifier));
3174 if (CertGetEnhancedKeyUsage(pCertContext,
3175 CERT_FIND_PROP_ONLY_ENHKEY_USAGE_FLAG, NULL, &size))
3177 PCERT_ENHKEY_USAGE usage = CryptMemAlloc(size);
3179 if (usage)
3181 ret = CertGetEnhancedKeyUsage(pCertContext,
3182 CERT_FIND_PROP_ONLY_ENHKEY_USAGE_FLAG, usage, &size);
3183 if (ret)
3185 DWORD i;
3186 BOOL exists = FALSE;
3188 /* Make sure usage doesn't already exist */
3189 for (i = 0; !exists && i < usage->cUsageIdentifier; i++)
3191 if (!strcmp(usage->rgpszUsageIdentifier[i],
3192 pszUsageIdentifier))
3193 exists = TRUE;
3195 if (!exists)
3197 PCERT_ENHKEY_USAGE newUsage = CryptMemAlloc(size +
3198 sizeof(LPSTR) + strlen(pszUsageIdentifier) + 1);
3200 if (newUsage)
3202 LPSTR nextOID;
3204 newUsage->rgpszUsageIdentifier = (LPSTR *)
3205 ((LPBYTE)newUsage + sizeof(CERT_ENHKEY_USAGE));
3206 nextOID = (LPSTR)((LPBYTE)newUsage->rgpszUsageIdentifier
3207 + (usage->cUsageIdentifier + 1) * sizeof(LPSTR));
3208 for (i = 0; i < usage->cUsageIdentifier; i++)
3210 newUsage->rgpszUsageIdentifier[i] = nextOID;
3211 strcpy(nextOID, usage->rgpszUsageIdentifier[i]);
3212 nextOID += strlen(nextOID) + 1;
3214 newUsage->rgpszUsageIdentifier[i] = nextOID;
3215 strcpy(nextOID, pszUsageIdentifier);
3216 newUsage->cUsageIdentifier = i + 1;
3217 ret = CertSetEnhancedKeyUsage(pCertContext, newUsage);
3218 CryptMemFree(newUsage);
3220 else
3221 ret = FALSE;
3224 CryptMemFree(usage);
3226 else
3227 ret = FALSE;
3229 else
3231 PCERT_ENHKEY_USAGE usage = CryptMemAlloc(sizeof(CERT_ENHKEY_USAGE) +
3232 sizeof(LPSTR) + strlen(pszUsageIdentifier) + 1);
3234 if (usage)
3236 usage->rgpszUsageIdentifier =
3237 (LPSTR *)((LPBYTE)usage + sizeof(CERT_ENHKEY_USAGE));
3238 usage->rgpszUsageIdentifier[0] = (LPSTR)((LPBYTE)usage +
3239 sizeof(CERT_ENHKEY_USAGE) + sizeof(LPSTR));
3240 strcpy(usage->rgpszUsageIdentifier[0], pszUsageIdentifier);
3241 usage->cUsageIdentifier = 1;
3242 ret = CertSetEnhancedKeyUsage(pCertContext, usage);
3243 CryptMemFree(usage);
3245 else
3246 ret = FALSE;
3248 return ret;
3251 BOOL WINAPI CertRemoveEnhancedKeyUsageIdentifier(PCCERT_CONTEXT pCertContext,
3252 LPCSTR pszUsageIdentifier)
3254 BOOL ret;
3255 DWORD size;
3256 CERT_ENHKEY_USAGE usage;
3258 TRACE("(%p, %s)\n", pCertContext, debugstr_a(pszUsageIdentifier));
3260 size = sizeof(usage);
3261 ret = CertGetEnhancedKeyUsage(pCertContext,
3262 CERT_FIND_PROP_ONLY_ENHKEY_USAGE_FLAG, &usage, &size);
3263 if (!ret && GetLastError() == ERROR_MORE_DATA)
3265 PCERT_ENHKEY_USAGE pUsage = CryptMemAlloc(size);
3267 if (pUsage)
3269 ret = CertGetEnhancedKeyUsage(pCertContext,
3270 CERT_FIND_PROP_ONLY_ENHKEY_USAGE_FLAG, pUsage, &size);
3271 if (ret)
3273 if (pUsage->cUsageIdentifier)
3275 DWORD i;
3276 BOOL found = FALSE;
3278 for (i = 0; i < pUsage->cUsageIdentifier; i++)
3280 if (!strcmp(pUsage->rgpszUsageIdentifier[i],
3281 pszUsageIdentifier))
3282 found = TRUE;
3283 if (found && i < pUsage->cUsageIdentifier - 1)
3284 pUsage->rgpszUsageIdentifier[i] =
3285 pUsage->rgpszUsageIdentifier[i + 1];
3287 pUsage->cUsageIdentifier--;
3288 /* Remove the usage if it's empty */
3289 if (pUsage->cUsageIdentifier)
3290 ret = CertSetEnhancedKeyUsage(pCertContext, pUsage);
3291 else
3292 ret = CertSetEnhancedKeyUsage(pCertContext, NULL);
3295 CryptMemFree(pUsage);
3297 else
3298 ret = FALSE;
3300 else
3302 /* it fit in an empty usage, therefore there's nothing to remove */
3303 ret = TRUE;
3305 return ret;
3308 struct BitField
3310 DWORD cIndexes;
3311 DWORD *indexes;
3314 #define BITS_PER_DWORD (sizeof(DWORD) * 8)
3316 static void CRYPT_SetBitInField(struct BitField *field, DWORD bit)
3318 DWORD indexIndex = bit / BITS_PER_DWORD;
3320 if (indexIndex + 1 > field->cIndexes)
3322 if (field->cIndexes)
3323 field->indexes = CryptMemRealloc(field->indexes,
3324 (indexIndex + 1) * sizeof(DWORD));
3325 else
3326 field->indexes = CryptMemAlloc(sizeof(DWORD));
3327 if (field->indexes)
3329 field->indexes[indexIndex] = 0;
3330 field->cIndexes = indexIndex + 1;
3333 if (field->indexes)
3334 field->indexes[indexIndex] |= 1 << (bit % BITS_PER_DWORD);
3337 static BOOL CRYPT_IsBitInFieldSet(const struct BitField *field, DWORD bit)
3339 BOOL set;
3340 DWORD indexIndex = bit / BITS_PER_DWORD;
3342 assert(field->cIndexes);
3343 set = field->indexes[indexIndex] & (1 << (bit % BITS_PER_DWORD));
3344 return set;
3347 BOOL WINAPI CertGetValidUsages(DWORD cCerts, PCCERT_CONTEXT *rghCerts,
3348 int *cNumOIDs, LPSTR *rghOIDs, DWORD *pcbOIDs)
3350 BOOL ret = TRUE;
3351 DWORD i, cbOIDs = 0;
3352 BOOL allUsagesValid = TRUE;
3353 CERT_ENHKEY_USAGE validUsages = { 0, NULL };
3355 TRACE("(%ld, %p, %d, %p, %ld)\n", cCerts, rghCerts, *cNumOIDs,
3356 rghOIDs, *pcbOIDs);
3358 for (i = 0; i < cCerts; i++)
3360 CERT_ENHKEY_USAGE usage;
3361 DWORD size = sizeof(usage);
3363 ret = CertGetEnhancedKeyUsage(rghCerts[i], 0, &usage, &size);
3364 /* Success is deliberately ignored: it implies all usages are valid */
3365 if (!ret && GetLastError() == ERROR_MORE_DATA)
3367 PCERT_ENHKEY_USAGE pUsage = CryptMemAlloc(size);
3369 allUsagesValid = FALSE;
3370 if (pUsage)
3372 ret = CertGetEnhancedKeyUsage(rghCerts[i], 0, pUsage, &size);
3373 if (ret)
3375 if (!validUsages.cUsageIdentifier)
3377 DWORD j;
3379 cbOIDs = pUsage->cUsageIdentifier * sizeof(LPSTR);
3380 validUsages.cUsageIdentifier = pUsage->cUsageIdentifier;
3381 for (j = 0; j < validUsages.cUsageIdentifier; j++)
3382 cbOIDs += lstrlenA(pUsage->rgpszUsageIdentifier[j])
3383 + 1;
3384 validUsages.rgpszUsageIdentifier =
3385 CryptMemAlloc(cbOIDs);
3386 if (validUsages.rgpszUsageIdentifier)
3388 LPSTR nextOID = (LPSTR)
3389 ((LPBYTE)validUsages.rgpszUsageIdentifier +
3390 validUsages.cUsageIdentifier * sizeof(LPSTR));
3392 for (j = 0; j < validUsages.cUsageIdentifier; j++)
3394 validUsages.rgpszUsageIdentifier[j] = nextOID;
3395 lstrcpyA(validUsages.rgpszUsageIdentifier[j],
3396 pUsage->rgpszUsageIdentifier[j]);
3397 nextOID += lstrlenA(nextOID) + 1;
3401 else
3403 struct BitField validIndexes = { 0, NULL };
3404 DWORD j, k, numRemoved = 0;
3406 /* Merge: build a bitmap of all the indexes of
3407 * validUsages.rgpszUsageIdentifier that are in pUsage.
3409 for (j = 0; j < pUsage->cUsageIdentifier; j++)
3411 for (k = 0; k < validUsages.cUsageIdentifier; k++)
3413 if (!strcmp(pUsage->rgpszUsageIdentifier[j],
3414 validUsages.rgpszUsageIdentifier[k]))
3416 CRYPT_SetBitInField(&validIndexes, k);
3417 break;
3421 /* Merge by removing from validUsages those that are
3422 * not in the bitmap.
3424 for (j = 0; j < validUsages.cUsageIdentifier; j++)
3426 if (!CRYPT_IsBitInFieldSet(&validIndexes, j))
3428 if (j < validUsages.cUsageIdentifier - 1)
3430 memmove(&validUsages.rgpszUsageIdentifier[j],
3431 &validUsages.rgpszUsageIdentifier[j +
3432 numRemoved + 1],
3433 (validUsages.cUsageIdentifier - numRemoved
3434 - j - 1) * sizeof(LPSTR));
3435 cbOIDs -= lstrlenA(
3436 validUsages.rgpszUsageIdentifier[j]) + 1 +
3437 sizeof(LPSTR);
3438 validUsages.cUsageIdentifier--;
3439 numRemoved++;
3441 else
3442 validUsages.cUsageIdentifier--;
3445 CryptMemFree(validIndexes.indexes);
3448 CryptMemFree(pUsage);
3452 ret = TRUE;
3453 if (allUsagesValid)
3455 *cNumOIDs = -1;
3456 *pcbOIDs = 0;
3458 else
3460 *cNumOIDs = validUsages.cUsageIdentifier;
3461 if (!rghOIDs)
3462 *pcbOIDs = cbOIDs;
3463 else if (*pcbOIDs < cbOIDs)
3465 *pcbOIDs = cbOIDs;
3466 SetLastError(ERROR_MORE_DATA);
3467 ret = FALSE;
3469 else
3471 LPSTR nextOID = (LPSTR)((LPBYTE)rghOIDs +
3472 validUsages.cUsageIdentifier * sizeof(LPSTR));
3474 *pcbOIDs = cbOIDs;
3475 for (i = 0; i < validUsages.cUsageIdentifier; i++)
3477 rghOIDs[i] = nextOID;
3478 lstrcpyA(nextOID, validUsages.rgpszUsageIdentifier[i]);
3479 nextOID += lstrlenA(nextOID) + 1;
3483 CryptMemFree(validUsages.rgpszUsageIdentifier);
3484 TRACE("cNumOIDs: %d\n", *cNumOIDs);
3485 TRACE("returning %d\n", ret);
3486 return ret;
3489 /* Sets the CERT_KEY_PROV_INFO_PROP_ID property of context from pInfo, or, if
3490 * pInfo is NULL, from the attributes of hProv.
3492 static void CertContext_SetKeyProvInfo(PCCERT_CONTEXT context,
3493 const CRYPT_KEY_PROV_INFO *pInfo, HCRYPTPROV hProv)
3495 CRYPT_KEY_PROV_INFO info = { 0 };
3496 BOOL ret;
3498 if (!pInfo)
3500 DWORD size;
3501 int len;
3503 ret = CryptGetProvParam(hProv, PP_CONTAINER, NULL, &size, 0);
3504 if (ret)
3506 LPSTR szContainer = CryptMemAlloc(size);
3508 if (szContainer)
3510 ret = CryptGetProvParam(hProv, PP_CONTAINER,
3511 (BYTE *)szContainer, &size, 0);
3512 if (ret)
3514 len = MultiByteToWideChar(CP_ACP, 0, szContainer, -1,
3515 NULL, 0);
3516 if (len)
3518 info.pwszContainerName = CryptMemAlloc(len *
3519 sizeof(WCHAR));
3520 MultiByteToWideChar(CP_ACP, 0, szContainer, -1,
3521 info.pwszContainerName, len);
3524 CryptMemFree(szContainer);
3527 ret = CryptGetProvParam(hProv, PP_NAME, NULL, &size, 0);
3528 if (ret)
3530 LPSTR szProvider = CryptMemAlloc(size);
3532 if (szProvider)
3534 ret = CryptGetProvParam(hProv, PP_NAME, (BYTE *)szProvider,
3535 &size, 0);
3536 if (ret)
3538 len = MultiByteToWideChar(CP_ACP, 0, szProvider, -1,
3539 NULL, 0);
3540 if (len)
3542 info.pwszProvName = CryptMemAlloc(len *
3543 sizeof(WCHAR));
3544 MultiByteToWideChar(CP_ACP, 0, szProvider, -1,
3545 info.pwszProvName, len);
3548 CryptMemFree(szProvider);
3551 /* in case no CRYPT_KEY_PROV_INFO given,
3552 * we always use AT_SIGNATURE key spec
3554 info.dwKeySpec = AT_SIGNATURE;
3555 size = sizeof(info.dwProvType);
3556 ret = CryptGetProvParam(hProv, PP_PROVTYPE, (LPBYTE)&info.dwProvType,
3557 &size, 0);
3558 if (!ret)
3559 info.dwProvType = PROV_RSA_FULL;
3560 pInfo = &info;
3563 CertSetCertificateContextProperty(context, CERT_KEY_PROV_INFO_PROP_ID,
3564 0, pInfo);
3566 if (pInfo == &info)
3568 CryptMemFree(info.pwszContainerName);
3569 CryptMemFree(info.pwszProvName);
3573 /* Creates a signed certificate context from the unsigned, encoded certificate
3574 * in blob, using the crypto provider hProv and the signature algorithm sigAlgo.
3576 static PCCERT_CONTEXT CRYPT_CreateSignedCert(const CRYPT_DER_BLOB *blob,
3577 HCRYPTPROV hProv, DWORD dwKeySpec, PCRYPT_ALGORITHM_IDENTIFIER sigAlgo)
3579 PCCERT_CONTEXT context = NULL;
3580 BOOL ret;
3581 DWORD sigSize = 0;
3583 ret = CryptSignCertificate(hProv, dwKeySpec, X509_ASN_ENCODING,
3584 blob->pbData, blob->cbData, sigAlgo, NULL, NULL, &sigSize);
3585 if (ret)
3587 LPBYTE sig = CryptMemAlloc(sigSize);
3589 ret = CryptSignCertificate(hProv, dwKeySpec, X509_ASN_ENCODING,
3590 blob->pbData, blob->cbData, sigAlgo, NULL, sig, &sigSize);
3591 if (ret)
3593 CERT_SIGNED_CONTENT_INFO signedInfo;
3594 BYTE *encodedSignedCert = NULL;
3595 DWORD encodedSignedCertSize = 0;
3597 signedInfo.ToBeSigned.cbData = blob->cbData;
3598 signedInfo.ToBeSigned.pbData = blob->pbData;
3599 signedInfo.SignatureAlgorithm = *sigAlgo;
3600 signedInfo.Signature.cbData = sigSize;
3601 signedInfo.Signature.pbData = sig;
3602 signedInfo.Signature.cUnusedBits = 0;
3603 ret = CryptEncodeObjectEx(X509_ASN_ENCODING, X509_CERT,
3604 &signedInfo, CRYPT_ENCODE_ALLOC_FLAG, NULL,
3605 &encodedSignedCert, &encodedSignedCertSize);
3606 if (ret)
3608 context = CertCreateCertificateContext(X509_ASN_ENCODING,
3609 encodedSignedCert, encodedSignedCertSize);
3610 LocalFree(encodedSignedCert);
3613 CryptMemFree(sig);
3615 return context;
3618 /* Copies data from the parameters into info, where:
3619 * pSerialNumber: The serial number. Must not be NULL.
3620 * pSubjectIssuerBlob: Specifies both the subject and issuer for info.
3621 * Must not be NULL
3622 * pSignatureAlgorithm: Optional.
3623 * pStartTime: The starting time of the certificate. If NULL, the current
3624 * system time is used.
3625 * pEndTime: The ending time of the certificate. If NULL, one year past the
3626 * starting time is used.
3627 * pubKey: The public key of the certificate. Must not be NULL.
3628 * pExtensions: Extensions to be included with the certificate. Optional.
3630 static void CRYPT_MakeCertInfo(PCERT_INFO info, const CRYPT_DATA_BLOB *pSerialNumber,
3631 const CERT_NAME_BLOB *pSubjectIssuerBlob,
3632 const CRYPT_ALGORITHM_IDENTIFIER *pSignatureAlgorithm, const SYSTEMTIME *pStartTime,
3633 const SYSTEMTIME *pEndTime, const CERT_PUBLIC_KEY_INFO *pubKey,
3634 const CERT_EXTENSIONS *pExtensions)
3636 static CHAR oid[] = szOID_RSA_SHA1RSA;
3638 assert(info);
3639 assert(pSerialNumber);
3640 assert(pSubjectIssuerBlob);
3641 assert(pubKey);
3643 if (pExtensions && pExtensions->cExtension)
3644 info->dwVersion = CERT_V3;
3645 else
3646 info->dwVersion = CERT_V1;
3647 info->SerialNumber.cbData = pSerialNumber->cbData;
3648 info->SerialNumber.pbData = pSerialNumber->pbData;
3649 if (pSignatureAlgorithm)
3650 info->SignatureAlgorithm = *pSignatureAlgorithm;
3651 else
3653 info->SignatureAlgorithm.pszObjId = oid;
3654 info->SignatureAlgorithm.Parameters.cbData = 0;
3655 info->SignatureAlgorithm.Parameters.pbData = NULL;
3657 info->Issuer.cbData = pSubjectIssuerBlob->cbData;
3658 info->Issuer.pbData = pSubjectIssuerBlob->pbData;
3659 if (pStartTime)
3660 SystemTimeToFileTime(pStartTime, &info->NotBefore);
3661 else
3662 GetSystemTimeAsFileTime(&info->NotBefore);
3663 if (pEndTime)
3664 SystemTimeToFileTime(pEndTime, &info->NotAfter);
3665 else
3667 SYSTEMTIME endTime;
3669 if (FileTimeToSystemTime(&info->NotBefore, &endTime))
3671 endTime.wYear++;
3672 SystemTimeToFileTime(&endTime, &info->NotAfter);
3675 info->Subject.cbData = pSubjectIssuerBlob->cbData;
3676 info->Subject.pbData = pSubjectIssuerBlob->pbData;
3677 info->SubjectPublicKeyInfo = *pubKey;
3678 if (pExtensions)
3680 info->cExtension = pExtensions->cExtension;
3681 info->rgExtension = pExtensions->rgExtension;
3683 else
3685 info->cExtension = 0;
3686 info->rgExtension = NULL;
3690 typedef RPC_STATUS (RPC_ENTRY *UuidCreateFunc)(UUID *);
3691 typedef RPC_STATUS (RPC_ENTRY *UuidToStringFunc)(UUID *, unsigned char **);
3692 typedef RPC_STATUS (RPC_ENTRY *RpcStringFreeFunc)(unsigned char **);
3694 static HCRYPTPROV CRYPT_CreateKeyProv(void)
3696 HCRYPTPROV hProv = 0;
3697 HMODULE rpcrt = LoadLibraryW(L"rpcrt4");
3699 if (rpcrt)
3701 UuidCreateFunc uuidCreate = (UuidCreateFunc)GetProcAddress(rpcrt,
3702 "UuidCreate");
3703 UuidToStringFunc uuidToString = (UuidToStringFunc)GetProcAddress(rpcrt,
3704 "UuidToStringA");
3705 RpcStringFreeFunc rpcStringFree = (RpcStringFreeFunc)GetProcAddress(
3706 rpcrt, "RpcStringFreeA");
3708 if (uuidCreate && uuidToString && rpcStringFree)
3710 UUID uuid;
3711 RPC_STATUS status = uuidCreate(&uuid);
3713 if (status == RPC_S_OK || status == RPC_S_UUID_LOCAL_ONLY)
3715 unsigned char *uuidStr;
3717 status = uuidToString(&uuid, &uuidStr);
3718 if (status == RPC_S_OK)
3720 BOOL ret = CryptAcquireContextA(&hProv, (LPCSTR)uuidStr,
3721 MS_DEF_PROV_A, PROV_RSA_FULL, CRYPT_NEWKEYSET);
3723 if (ret)
3725 HCRYPTKEY key;
3727 ret = CryptGenKey(hProv, AT_SIGNATURE, 0, &key);
3728 if (ret)
3729 CryptDestroyKey(key);
3731 rpcStringFree(&uuidStr);
3735 FreeLibrary(rpcrt);
3737 return hProv;
3740 PCCERT_CONTEXT WINAPI CertCreateSelfSignCertificate(HCRYPTPROV_OR_NCRYPT_KEY_HANDLE hProv,
3741 PCERT_NAME_BLOB pSubjectIssuerBlob, DWORD dwFlags,
3742 PCRYPT_KEY_PROV_INFO pKeyProvInfo,
3743 PCRYPT_ALGORITHM_IDENTIFIER pSignatureAlgorithm, PSYSTEMTIME pStartTime,
3744 PSYSTEMTIME pEndTime, PCERT_EXTENSIONS pExtensions)
3746 PCCERT_CONTEXT context = NULL;
3747 BOOL ret, releaseContext = FALSE;
3748 PCERT_PUBLIC_KEY_INFO pubKey = NULL;
3749 DWORD pubKeySize = 0, dwKeySpec;
3751 TRACE("(%08Ix, %p, %08lx, %p, %p, %p, %p, %p)\n", hProv,
3752 pSubjectIssuerBlob, dwFlags, pKeyProvInfo, pSignatureAlgorithm, pStartTime,
3753 pExtensions, pExtensions);
3755 if(!pSubjectIssuerBlob)
3757 SetLastError(ERROR_INVALID_PARAMETER);
3758 return NULL;
3761 dwKeySpec = pKeyProvInfo ? pKeyProvInfo->dwKeySpec : AT_SIGNATURE;
3762 if (!hProv)
3764 if (!pKeyProvInfo)
3766 hProv = CRYPT_CreateKeyProv();
3767 releaseContext = TRUE;
3769 else if (pKeyProvInfo->dwFlags & CERT_SET_KEY_PROV_HANDLE_PROP_ID)
3771 SetLastError(NTE_BAD_FLAGS);
3772 return NULL;
3774 else
3776 HCRYPTKEY hKey = 0;
3777 /* acquire the context using the given information*/
3778 ret = CryptAcquireContextW(&hProv,pKeyProvInfo->pwszContainerName,
3779 pKeyProvInfo->pwszProvName,pKeyProvInfo->dwProvType,
3780 pKeyProvInfo->dwFlags);
3781 if (!ret)
3783 if(GetLastError() != NTE_BAD_KEYSET)
3784 return NULL;
3785 /* create the key set */
3786 ret = CryptAcquireContextW(&hProv,pKeyProvInfo->pwszContainerName,
3787 pKeyProvInfo->pwszProvName,pKeyProvInfo->dwProvType,
3788 pKeyProvInfo->dwFlags|CRYPT_NEWKEYSET);
3789 if (!ret)
3790 return NULL;
3792 /* check if the key is here */
3793 ret = CryptGetUserKey(hProv,dwKeySpec,&hKey);
3794 if(!ret)
3796 if (NTE_NO_KEY == GetLastError())
3797 { /* generate the key */
3798 ret = CryptGenKey(hProv,dwKeySpec,0,&hKey);
3800 if (!ret)
3802 CryptReleaseContext(hProv,0);
3803 SetLastError(NTE_BAD_KEYSET);
3804 return NULL;
3807 CryptDestroyKey(hKey);
3808 releaseContext = TRUE;
3812 ret = CryptExportPublicKeyInfo(hProv, dwKeySpec, X509_ASN_ENCODING, NULL,
3813 &pubKeySize);
3814 if (!ret)
3815 goto end;
3816 pubKey = CryptMemAlloc(pubKeySize);
3817 if (pubKey)
3819 ret = CryptExportPublicKeyInfo(hProv, dwKeySpec, X509_ASN_ENCODING,
3820 pubKey, &pubKeySize);
3821 if (ret)
3823 CERT_INFO info = { 0 };
3824 CRYPT_DER_BLOB blob = { 0, NULL };
3825 BYTE serial[16];
3826 CRYPT_DATA_BLOB serialBlob = { sizeof(serial), serial };
3828 CryptGenRandom(hProv, sizeof(serial), serial);
3829 CRYPT_MakeCertInfo(&info, &serialBlob, pSubjectIssuerBlob,
3830 pSignatureAlgorithm, pStartTime, pEndTime, pubKey, pExtensions);
3831 ret = CryptEncodeObjectEx(X509_ASN_ENCODING, X509_CERT_TO_BE_SIGNED,
3832 &info, CRYPT_ENCODE_ALLOC_FLAG, NULL, &blob.pbData,
3833 &blob.cbData);
3834 if (ret)
3836 if (!(dwFlags & CERT_CREATE_SELFSIGN_NO_SIGN))
3837 context = CRYPT_CreateSignedCert(&blob, hProv,dwKeySpec,
3838 &info.SignatureAlgorithm);
3839 else
3840 context = CertCreateCertificateContext(X509_ASN_ENCODING,
3841 blob.pbData, blob.cbData);
3842 if (context && !(dwFlags & CERT_CREATE_SELFSIGN_NO_KEY_INFO))
3843 CertContext_SetKeyProvInfo(context, pKeyProvInfo, hProv);
3844 LocalFree(blob.pbData);
3847 CryptMemFree(pubKey);
3849 end:
3850 if (releaseContext)
3851 CryptReleaseContext(hProv, 0);
3852 return context;
3855 BOOL WINAPI CertVerifyCTLUsage(DWORD dwEncodingType, DWORD dwSubjectType,
3856 void *pvSubject, PCTL_USAGE pSubjectUsage, DWORD dwFlags,
3857 PCTL_VERIFY_USAGE_PARA pVerifyUsagePara,
3858 PCTL_VERIFY_USAGE_STATUS pVerifyUsageStatus)
3860 FIXME("(0x%lx, %ld, %p, %p, 0x%lx, %p, %p): stub\n", dwEncodingType,
3861 dwSubjectType, pvSubject, pSubjectUsage, dwFlags, pVerifyUsagePara,
3862 pVerifyUsageStatus);
3863 SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
3864 return FALSE;
3867 const void * WINAPI CertCreateContext(DWORD dwContextType, DWORD dwEncodingType,
3868 const BYTE *pbEncoded, DWORD cbEncoded,
3869 DWORD dwFlags, PCERT_CREATE_CONTEXT_PARA pCreatePara)
3871 TRACE("(0x%lx, 0x%lx, %p, %ld, 0x%08lx, %p)\n", dwContextType, dwEncodingType,
3872 pbEncoded, cbEncoded, dwFlags, pCreatePara);
3874 if (dwFlags)
3876 FIXME("dwFlags 0x%08lx not handled\n", dwFlags);
3877 return NULL;
3879 if (pCreatePara)
3881 FIXME("pCreatePara not handled\n");
3882 return NULL;
3885 switch (dwContextType)
3887 case CERT_STORE_CERTIFICATE_CONTEXT:
3888 return CertCreateCertificateContext(dwEncodingType, pbEncoded, cbEncoded);
3889 case CERT_STORE_CRL_CONTEXT:
3890 return CertCreateCRLContext(dwEncodingType, pbEncoded, cbEncoded);
3891 case CERT_STORE_CTL_CONTEXT:
3892 return CertCreateCTLContext(dwEncodingType, pbEncoded, cbEncoded);
3893 default:
3894 WARN("unknown context type: 0x%lx\n", dwContextType);
3895 return NULL;
3899 BOOL WINAPI CryptSetKeyIdentifierProperty(const CRYPT_HASH_BLOB *pKeyIdentifier, DWORD dwPropId,
3900 DWORD dwFlags, LPCWSTR pwszComputerName, void *pvReserved, const void *pvData)
3902 FIXME("(%p, 0x%lx, 0x%lx, %s, %p, %p): stub\n", pKeyIdentifier, dwPropId, dwFlags,
3903 debugstr_w(pwszComputerName), pvReserved, pvData);
3904 return FALSE;