msvcrt/tests: Remove a space before a '\n'.
[wine/gsoc-2012-control.git] / dlls / crypt32 / cert.c
blob2780cba6343d595a651ef8c56a827ff5623b74cb
1 /*
2 * Copyright 2004-2006 Juan Lang
4 * This library is free software; you can redistribute it and/or
5 * modify it under the terms of the GNU Lesser General Public
6 * License as published by the Free Software Foundation; either
7 * version 2.1 of the License, or (at your option) any later version.
9 * This library is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
12 * Lesser General Public License for more details.
14 * You should have received a copy of the GNU Lesser General Public
15 * License along with this library; if not, write to the Free Software
16 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
20 #include <assert.h>
21 #include <stdarg.h>
23 #define NONAMELESSUNION
24 #include "windef.h"
25 #include "winbase.h"
26 #include "wincrypt.h"
27 #include "winnls.h"
28 #include "rpc.h"
29 #include "wine/debug.h"
30 #include "wine/unicode.h"
31 #include "crypt32_private.h"
33 WINE_DEFAULT_DEBUG_CHANNEL(crypt);
35 /* Internal version of CertGetCertificateContextProperty that gets properties
36 * directly from the context (or the context it's linked to, depending on its
37 * type.) Doesn't handle special-case properties, since they are handled by
38 * CertGetCertificateContextProperty, and are particular to the store in which
39 * the property exists (which is separate from the context.)
41 static BOOL CertContext_GetProperty(void *context, DWORD dwPropId,
42 void *pvData, DWORD *pcbData);
44 /* Internal version of CertSetCertificateContextProperty that sets properties
45 * directly on the context (or the context it's linked to, depending on its
46 * type.) Doesn't handle special cases, since they're handled by
47 * CertSetCertificateContextProperty anyway.
49 static BOOL CertContext_SetProperty(void *context, DWORD dwPropId,
50 DWORD dwFlags, const void *pvData);
52 BOOL WINAPI CertAddEncodedCertificateToStore(HCERTSTORE hCertStore,
53 DWORD dwCertEncodingType, const BYTE *pbCertEncoded, DWORD cbCertEncoded,
54 DWORD dwAddDisposition, PCCERT_CONTEXT *ppCertContext)
56 PCCERT_CONTEXT cert = CertCreateCertificateContext(dwCertEncodingType,
57 pbCertEncoded, cbCertEncoded);
58 BOOL ret;
60 TRACE("(%p, %08x, %p, %d, %08x, %p)\n", hCertStore, dwCertEncodingType,
61 pbCertEncoded, cbCertEncoded, dwAddDisposition, ppCertContext);
63 if (cert)
65 ret = CertAddCertificateContextToStore(hCertStore, cert,
66 dwAddDisposition, ppCertContext);
67 CertFreeCertificateContext(cert);
69 else
70 ret = FALSE;
71 return ret;
74 PCCERT_CONTEXT WINAPI CertCreateCertificateContext(DWORD dwCertEncodingType,
75 const BYTE *pbCertEncoded, DWORD cbCertEncoded)
77 PCERT_CONTEXT cert = NULL;
78 BOOL ret;
79 PCERT_INFO certInfo = NULL;
80 DWORD size = 0;
82 TRACE("(%08x, %p, %d)\n", dwCertEncodingType, pbCertEncoded,
83 cbCertEncoded);
85 ret = CryptDecodeObjectEx(dwCertEncodingType, X509_CERT_TO_BE_SIGNED,
86 pbCertEncoded, cbCertEncoded, CRYPT_DECODE_ALLOC_FLAG, NULL,
87 &certInfo, &size);
88 if (ret)
90 BYTE *data = NULL;
92 cert = Context_CreateDataContext(sizeof(CERT_CONTEXT));
93 if (!cert)
94 goto end;
95 data = CryptMemAlloc(cbCertEncoded);
96 if (!data)
98 CryptMemFree(cert);
99 cert = NULL;
100 goto end;
102 memcpy(data, pbCertEncoded, cbCertEncoded);
103 cert->dwCertEncodingType = dwCertEncodingType;
104 cert->pbCertEncoded = data;
105 cert->cbCertEncoded = cbCertEncoded;
106 cert->pCertInfo = certInfo;
107 cert->hCertStore = 0;
110 end:
111 return cert;
114 PCCERT_CONTEXT WINAPI CertDuplicateCertificateContext(
115 PCCERT_CONTEXT pCertContext)
117 TRACE("(%p)\n", pCertContext);
119 if (!pCertContext)
120 return NULL;
122 Context_AddRef((void *)pCertContext, sizeof(CERT_CONTEXT));
123 return pCertContext;
126 static void CertDataContext_Free(void *context)
128 PCERT_CONTEXT certContext = context;
130 CryptMemFree(certContext->pbCertEncoded);
131 LocalFree(certContext->pCertInfo);
134 BOOL WINAPI CertFreeCertificateContext(PCCERT_CONTEXT pCertContext)
136 TRACE("(%p)\n", pCertContext);
138 if (pCertContext)
139 Context_Release((void *)pCertContext, sizeof(CERT_CONTEXT),
140 CertDataContext_Free);
141 return TRUE;
144 DWORD WINAPI CertEnumCertificateContextProperties(PCCERT_CONTEXT pCertContext,
145 DWORD dwPropId)
147 PCONTEXT_PROPERTY_LIST properties = Context_GetProperties(
148 pCertContext, sizeof(CERT_CONTEXT));
149 DWORD ret;
151 TRACE("(%p, %d)\n", pCertContext, dwPropId);
153 if (properties)
154 ret = ContextPropertyList_EnumPropIDs(properties, dwPropId);
155 else
156 ret = 0;
157 return ret;
160 static BOOL CertContext_GetHashProp(void *context, DWORD dwPropId,
161 ALG_ID algID, const BYTE *toHash, DWORD toHashLen, void *pvData,
162 DWORD *pcbData)
164 BOOL ret = CryptHashCertificate(0, algID, 0, toHash, toHashLen, pvData,
165 pcbData);
166 if (ret && pvData)
168 CRYPT_DATA_BLOB blob = { *pcbData, pvData };
170 ret = CertContext_SetProperty(context, dwPropId, 0, &blob);
172 return ret;
175 static BOOL CertContext_CopyParam(void *pvData, DWORD *pcbData, const void *pb,
176 DWORD cb)
178 BOOL ret = TRUE;
180 if (!pvData)
181 *pcbData = cb;
182 else if (*pcbData < cb)
184 SetLastError(ERROR_MORE_DATA);
185 *pcbData = cb;
186 ret = FALSE;
188 else
190 memcpy(pvData, pb, cb);
191 *pcbData = cb;
193 return ret;
196 static BOOL CertContext_GetProperty(void *context, DWORD dwPropId,
197 void *pvData, DWORD *pcbData)
199 PCCERT_CONTEXT pCertContext = context;
200 PCONTEXT_PROPERTY_LIST properties =
201 Context_GetProperties(context, sizeof(CERT_CONTEXT));
202 BOOL ret;
203 CRYPT_DATA_BLOB blob;
205 TRACE("(%p, %d, %p, %p)\n", context, dwPropId, pvData, pcbData);
207 if (properties)
208 ret = ContextPropertyList_FindProperty(properties, dwPropId, &blob);
209 else
210 ret = FALSE;
211 if (ret)
212 ret = CertContext_CopyParam(pvData, pcbData, blob.pbData, blob.cbData);
213 else
215 /* Implicit properties */
216 switch (dwPropId)
218 case CERT_SHA1_HASH_PROP_ID:
219 ret = CertContext_GetHashProp(context, dwPropId, CALG_SHA1,
220 pCertContext->pbCertEncoded, pCertContext->cbCertEncoded, pvData,
221 pcbData);
222 break;
223 case CERT_MD5_HASH_PROP_ID:
224 ret = CertContext_GetHashProp(context, dwPropId, CALG_MD5,
225 pCertContext->pbCertEncoded, pCertContext->cbCertEncoded, pvData,
226 pcbData);
227 break;
228 case CERT_SUBJECT_NAME_MD5_HASH_PROP_ID:
229 ret = CertContext_GetHashProp(context, dwPropId, CALG_MD5,
230 pCertContext->pCertInfo->Subject.pbData,
231 pCertContext->pCertInfo->Subject.cbData,
232 pvData, pcbData);
233 break;
234 case CERT_SUBJECT_PUBLIC_KEY_MD5_HASH_PROP_ID:
235 ret = CertContext_GetHashProp(context, dwPropId, CALG_MD5,
236 pCertContext->pCertInfo->SubjectPublicKeyInfo.PublicKey.pbData,
237 pCertContext->pCertInfo->SubjectPublicKeyInfo.PublicKey.cbData,
238 pvData, pcbData);
239 break;
240 case CERT_ISSUER_SERIAL_NUMBER_MD5_HASH_PROP_ID:
241 ret = CertContext_GetHashProp(context, dwPropId, CALG_MD5,
242 pCertContext->pCertInfo->SerialNumber.pbData,
243 pCertContext->pCertInfo->SerialNumber.cbData,
244 pvData, pcbData);
245 break;
246 case CERT_SIGNATURE_HASH_PROP_ID:
247 ret = CryptHashToBeSigned(0, pCertContext->dwCertEncodingType,
248 pCertContext->pbCertEncoded, pCertContext->cbCertEncoded, pvData,
249 pcbData);
250 if (ret && pvData)
252 CRYPT_DATA_BLOB blob = { *pcbData, pvData };
254 ret = CertContext_SetProperty(context, dwPropId, 0, &blob);
256 break;
257 case CERT_KEY_IDENTIFIER_PROP_ID:
259 PCERT_EXTENSION ext = CertFindExtension(
260 szOID_SUBJECT_KEY_IDENTIFIER, pCertContext->pCertInfo->cExtension,
261 pCertContext->pCertInfo->rgExtension);
263 if (ext)
265 CRYPT_DATA_BLOB value;
266 DWORD size = sizeof(value);
268 ret = CryptDecodeObjectEx(X509_ASN_ENCODING,
269 szOID_SUBJECT_KEY_IDENTIFIER, ext->Value.pbData,
270 ext->Value.cbData, CRYPT_DECODE_NOCOPY_FLAG, NULL, &value,
271 &size);
272 if (ret)
274 ret = CertContext_CopyParam(pvData, pcbData, value.pbData,
275 value.cbData);
276 CertContext_SetProperty(context, dwPropId, 0, &value);
279 else
280 SetLastError(ERROR_INVALID_DATA);
281 break;
283 default:
284 SetLastError(CRYPT_E_NOT_FOUND);
287 TRACE("returning %d\n", ret);
288 return ret;
291 void CRYPT_FixKeyProvInfoPointers(PCRYPT_KEY_PROV_INFO info)
293 DWORD i, containerLen, provNameLen;
294 LPBYTE data = (LPBYTE)info + sizeof(CRYPT_KEY_PROV_INFO);
296 info->pwszContainerName = (LPWSTR)data;
297 containerLen = (lstrlenW(info->pwszContainerName) + 1) * sizeof(WCHAR);
298 data += containerLen;
300 info->pwszProvName = (LPWSTR)data;
301 provNameLen = (lstrlenW(info->pwszProvName) + 1) * sizeof(WCHAR);
302 data += provNameLen;
304 info->rgProvParam = (PCRYPT_KEY_PROV_PARAM)data;
305 data += info->cProvParam * sizeof(CRYPT_KEY_PROV_PARAM);
307 for (i = 0; i < info->cProvParam; i++)
309 info->rgProvParam[i].pbData = data;
310 data += info->rgProvParam[i].cbData;
314 BOOL WINAPI CertGetCertificateContextProperty(PCCERT_CONTEXT pCertContext,
315 DWORD dwPropId, void *pvData, DWORD *pcbData)
317 BOOL ret;
319 TRACE("(%p, %d, %p, %p)\n", pCertContext, dwPropId, pvData, pcbData);
321 switch (dwPropId)
323 case 0:
324 case CERT_CERT_PROP_ID:
325 case CERT_CRL_PROP_ID:
326 case CERT_CTL_PROP_ID:
327 SetLastError(E_INVALIDARG);
328 ret = FALSE;
329 break;
330 case CERT_ACCESS_STATE_PROP_ID:
331 if (pCertContext->hCertStore)
332 ret = CertGetStoreProperty(pCertContext->hCertStore, dwPropId,
333 pvData, pcbData);
334 else
336 DWORD state = 0;
338 ret = CertContext_CopyParam(pvData, pcbData, &state, sizeof(state));
340 break;
341 case CERT_KEY_PROV_HANDLE_PROP_ID:
343 CERT_KEY_CONTEXT keyContext;
344 DWORD size = sizeof(keyContext);
346 ret = CertContext_GetProperty((void *)pCertContext,
347 CERT_KEY_CONTEXT_PROP_ID, &keyContext, &size);
348 if (ret)
349 ret = CertContext_CopyParam(pvData, pcbData, &keyContext.hCryptProv,
350 sizeof(keyContext.hCryptProv));
351 break;
353 case CERT_KEY_PROV_INFO_PROP_ID:
354 ret = CertContext_GetProperty((void *)pCertContext, dwPropId, pvData,
355 pcbData);
356 if (ret && pvData)
357 CRYPT_FixKeyProvInfoPointers(pvData);
358 break;
359 default:
360 ret = CertContext_GetProperty((void *)pCertContext, dwPropId, pvData,
361 pcbData);
364 TRACE("returning %d\n", ret);
365 return ret;
368 /* Copies key provider info from from into to, where to is assumed to be a
369 * contiguous buffer of memory large enough for from and all its associated
370 * data, but whose pointers are uninitialized.
371 * Upon return, to contains a contiguous copy of from, packed in the following
372 * order:
373 * - CRYPT_KEY_PROV_INFO
374 * - pwszContainerName
375 * - pwszProvName
376 * - rgProvParam[0]...
378 static void CRYPT_CopyKeyProvInfo(PCRYPT_KEY_PROV_INFO to,
379 const CRYPT_KEY_PROV_INFO *from)
381 DWORD i;
382 LPBYTE nextData = (LPBYTE)to + sizeof(CRYPT_KEY_PROV_INFO);
384 if (from->pwszContainerName)
386 to->pwszContainerName = (LPWSTR)nextData;
387 lstrcpyW(to->pwszContainerName, from->pwszContainerName);
388 nextData += (lstrlenW(from->pwszContainerName) + 1) * sizeof(WCHAR);
390 else
391 to->pwszContainerName = NULL;
392 if (from->pwszProvName)
394 to->pwszProvName = (LPWSTR)nextData;
395 lstrcpyW(to->pwszProvName, from->pwszProvName);
396 nextData += (lstrlenW(from->pwszProvName) + 1) * sizeof(WCHAR);
398 else
399 to->pwszProvName = NULL;
400 to->dwProvType = from->dwProvType;
401 to->dwFlags = from->dwFlags;
402 to->cProvParam = from->cProvParam;
403 to->rgProvParam = (PCRYPT_KEY_PROV_PARAM)nextData;
404 nextData += to->cProvParam * sizeof(CRYPT_KEY_PROV_PARAM);
405 to->dwKeySpec = from->dwKeySpec;
406 for (i = 0; i < to->cProvParam; i++)
408 memcpy(&to->rgProvParam[i], &from->rgProvParam[i],
409 sizeof(CRYPT_KEY_PROV_PARAM));
410 to->rgProvParam[i].pbData = nextData;
411 memcpy(to->rgProvParam[i].pbData, from->rgProvParam[i].pbData,
412 from->rgProvParam[i].cbData);
413 nextData += from->rgProvParam[i].cbData;
417 static BOOL CertContext_SetKeyProvInfoProperty(PCONTEXT_PROPERTY_LIST properties,
418 const CRYPT_KEY_PROV_INFO *info)
420 BOOL ret;
421 LPBYTE buf = NULL;
422 DWORD size = sizeof(CRYPT_KEY_PROV_INFO), i, containerSize, provNameSize;
424 if (info->pwszContainerName)
425 containerSize = (lstrlenW(info->pwszContainerName) + 1) * sizeof(WCHAR);
426 else
427 containerSize = 0;
428 if (info->pwszProvName)
429 provNameSize = (lstrlenW(info->pwszProvName) + 1) * sizeof(WCHAR);
430 else
431 provNameSize = 0;
432 size += containerSize + provNameSize;
433 for (i = 0; i < info->cProvParam; i++)
434 size += sizeof(CRYPT_KEY_PROV_PARAM) + info->rgProvParam[i].cbData;
435 buf = CryptMemAlloc(size);
436 if (buf)
438 CRYPT_CopyKeyProvInfo((PCRYPT_KEY_PROV_INFO)buf, info);
439 ret = ContextPropertyList_SetProperty(properties,
440 CERT_KEY_PROV_INFO_PROP_ID, buf, size);
441 CryptMemFree(buf);
443 else
444 ret = FALSE;
445 return ret;
448 static BOOL CertContext_SetProperty(void *context, DWORD dwPropId,
449 DWORD dwFlags, const void *pvData)
451 PCONTEXT_PROPERTY_LIST properties =
452 Context_GetProperties(context, sizeof(CERT_CONTEXT));
453 BOOL ret;
455 TRACE("(%p, %d, %08x, %p)\n", context, dwPropId, dwFlags, pvData);
457 if (!properties)
458 ret = FALSE;
459 else
461 switch (dwPropId)
463 case CERT_AUTO_ENROLL_PROP_ID:
464 case CERT_CTL_USAGE_PROP_ID: /* same as CERT_ENHKEY_USAGE_PROP_ID */
465 case CERT_DESCRIPTION_PROP_ID:
466 case CERT_FRIENDLY_NAME_PROP_ID:
467 case CERT_HASH_PROP_ID:
468 case CERT_KEY_IDENTIFIER_PROP_ID:
469 case CERT_MD5_HASH_PROP_ID:
470 case CERT_NEXT_UPDATE_LOCATION_PROP_ID:
471 case CERT_PUBKEY_ALG_PARA_PROP_ID:
472 case CERT_PVK_FILE_PROP_ID:
473 case CERT_SIGNATURE_HASH_PROP_ID:
474 case CERT_ISSUER_PUBLIC_KEY_MD5_HASH_PROP_ID:
475 case CERT_SUBJECT_NAME_MD5_HASH_PROP_ID:
476 case CERT_EXTENDED_ERROR_INFO_PROP_ID:
477 case CERT_SUBJECT_PUBLIC_KEY_MD5_HASH_PROP_ID:
478 case CERT_ENROLLMENT_PROP_ID:
479 case CERT_CROSS_CERT_DIST_POINTS_PROP_ID:
480 case CERT_RENEWAL_PROP_ID:
482 if (pvData)
484 const CRYPT_DATA_BLOB *blob = pvData;
486 ret = ContextPropertyList_SetProperty(properties, dwPropId,
487 blob->pbData, blob->cbData);
489 else
491 ContextPropertyList_RemoveProperty(properties, dwPropId);
492 ret = TRUE;
494 break;
496 case CERT_DATE_STAMP_PROP_ID:
497 if (pvData)
498 ret = ContextPropertyList_SetProperty(properties, dwPropId,
499 pvData, sizeof(FILETIME));
500 else
502 ContextPropertyList_RemoveProperty(properties, dwPropId);
503 ret = TRUE;
505 break;
506 case CERT_KEY_CONTEXT_PROP_ID:
508 if (pvData)
510 const CERT_KEY_CONTEXT *keyContext = pvData;
512 if (keyContext->cbSize != sizeof(CERT_KEY_CONTEXT))
514 SetLastError(E_INVALIDARG);
515 ret = FALSE;
517 else
518 ret = ContextPropertyList_SetProperty(properties, dwPropId,
519 (const BYTE *)keyContext, keyContext->cbSize);
521 else
523 ContextPropertyList_RemoveProperty(properties, dwPropId);
524 ret = TRUE;
526 break;
528 case CERT_KEY_PROV_INFO_PROP_ID:
529 if (pvData)
530 ret = CertContext_SetKeyProvInfoProperty(properties, pvData);
531 else
533 ContextPropertyList_RemoveProperty(properties, dwPropId);
534 ret = TRUE;
536 break;
537 case CERT_KEY_PROV_HANDLE_PROP_ID:
539 CERT_KEY_CONTEXT keyContext;
540 DWORD size = sizeof(keyContext);
542 ret = CertContext_GetProperty(context, CERT_KEY_CONTEXT_PROP_ID,
543 &keyContext, &size);
544 if (ret)
546 if (!(dwFlags & CERT_STORE_NO_CRYPT_RELEASE_FLAG))
547 CryptReleaseContext(keyContext.hCryptProv, 0);
549 keyContext.cbSize = sizeof(keyContext);
550 if (pvData)
551 keyContext.hCryptProv = *(const HCRYPTPROV *)pvData;
552 else
554 keyContext.hCryptProv = 0;
555 keyContext.dwKeySpec = AT_SIGNATURE;
557 ret = CertContext_SetProperty(context, CERT_KEY_CONTEXT_PROP_ID,
558 0, &keyContext);
559 break;
561 default:
562 FIXME("%d: stub\n", dwPropId);
563 ret = FALSE;
566 TRACE("returning %d\n", ret);
567 return ret;
570 BOOL WINAPI CertSetCertificateContextProperty(PCCERT_CONTEXT pCertContext,
571 DWORD dwPropId, DWORD dwFlags, const void *pvData)
573 BOOL ret;
575 TRACE("(%p, %d, %08x, %p)\n", pCertContext, dwPropId, dwFlags, pvData);
577 /* Handle special cases for "read-only"/invalid prop IDs. Windows just
578 * crashes on most of these, I'll be safer.
580 switch (dwPropId)
582 case 0:
583 case CERT_ACCESS_STATE_PROP_ID:
584 case CERT_CERT_PROP_ID:
585 case CERT_CRL_PROP_ID:
586 case CERT_CTL_PROP_ID:
587 SetLastError(E_INVALIDARG);
588 return FALSE;
590 ret = CertContext_SetProperty((void *)pCertContext, dwPropId, dwFlags,
591 pvData);
592 TRACE("returning %d\n", ret);
593 return ret;
596 /* Acquires the private key using the key provider info, retrieving info from
597 * the certificate if info is NULL. The acquired provider is returned in
598 * *phCryptProv, and the key spec for the provider is returned in *pdwKeySpec.
600 static BOOL CRYPT_AcquirePrivateKeyFromProvInfo(PCCERT_CONTEXT pCert,
601 PCRYPT_KEY_PROV_INFO info, HCRYPTPROV *phCryptProv, DWORD *pdwKeySpec)
603 DWORD size = 0;
604 BOOL allocated = FALSE, ret = TRUE;
606 if (!info)
608 ret = CertGetCertificateContextProperty(pCert,
609 CERT_KEY_PROV_INFO_PROP_ID, 0, &size);
610 if (ret)
612 info = HeapAlloc(GetProcessHeap(), 0, size);
613 if (info)
615 ret = CertGetCertificateContextProperty(pCert,
616 CERT_KEY_PROV_INFO_PROP_ID, info, &size);
617 allocated = TRUE;
619 else
621 SetLastError(ERROR_OUTOFMEMORY);
622 ret = FALSE;
625 else
626 SetLastError(CRYPT_E_NO_KEY_PROPERTY);
628 if (ret)
630 ret = CryptAcquireContextW(phCryptProv, info->pwszContainerName,
631 info->pwszProvName, info->dwProvType, 0);
632 if (ret)
634 DWORD i;
636 for (i = 0; i < info->cProvParam; i++)
638 CryptSetProvParam(*phCryptProv,
639 info->rgProvParam[i].dwParam, info->rgProvParam[i].pbData,
640 info->rgProvParam[i].dwFlags);
642 *pdwKeySpec = info->dwKeySpec;
644 else
645 SetLastError(CRYPT_E_NO_KEY_PROPERTY);
647 if (allocated)
648 HeapFree(GetProcessHeap(), 0, info);
649 return ret;
652 BOOL WINAPI CryptAcquireCertificatePrivateKey(PCCERT_CONTEXT pCert,
653 DWORD dwFlags, void *pvReserved, HCRYPTPROV_OR_NCRYPT_KEY_HANDLE *phCryptProv,
654 DWORD *pdwKeySpec, BOOL *pfCallerFreeProv)
656 BOOL ret = FALSE, cache = FALSE;
657 PCRYPT_KEY_PROV_INFO info = NULL;
658 CERT_KEY_CONTEXT keyContext;
659 DWORD size;
661 TRACE("(%p, %08x, %p, %p, %p, %p)\n", pCert, dwFlags, pvReserved,
662 phCryptProv, pdwKeySpec, pfCallerFreeProv);
664 if (dwFlags & CRYPT_ACQUIRE_USE_PROV_INFO_FLAG)
666 DWORD size = 0;
668 ret = CertGetCertificateContextProperty(pCert,
669 CERT_KEY_PROV_INFO_PROP_ID, 0, &size);
670 if (ret)
672 info = HeapAlloc(GetProcessHeap(), 0, size);
673 ret = CertGetCertificateContextProperty(pCert,
674 CERT_KEY_PROV_INFO_PROP_ID, info, &size);
675 if (ret)
676 cache = info->dwFlags & CERT_SET_KEY_CONTEXT_PROP_ID;
679 else if (dwFlags & CRYPT_ACQUIRE_CACHE_FLAG)
680 cache = TRUE;
681 *phCryptProv = 0;
682 if (cache)
684 size = sizeof(keyContext);
685 ret = CertGetCertificateContextProperty(pCert, CERT_KEY_CONTEXT_PROP_ID,
686 &keyContext, &size);
687 if (ret)
689 *phCryptProv = keyContext.hCryptProv;
690 if (pdwKeySpec)
691 *pdwKeySpec = keyContext.dwKeySpec;
692 if (pfCallerFreeProv)
693 *pfCallerFreeProv = !cache;
696 if (!*phCryptProv)
698 ret = CRYPT_AcquirePrivateKeyFromProvInfo(pCert, info,
699 &keyContext.hCryptProv, &keyContext.dwKeySpec);
700 if (ret)
702 *phCryptProv = keyContext.hCryptProv;
703 if (pdwKeySpec)
704 *pdwKeySpec = keyContext.dwKeySpec;
705 if (cache)
707 keyContext.cbSize = sizeof(keyContext);
708 if (CertSetCertificateContextProperty(pCert,
709 CERT_KEY_CONTEXT_PROP_ID, 0, &keyContext))
711 if (pfCallerFreeProv)
712 *pfCallerFreeProv = FALSE;
715 else
717 if (pfCallerFreeProv)
718 *pfCallerFreeProv = TRUE;
722 HeapFree(GetProcessHeap(), 0, info);
723 return ret;
726 static BOOL key_prov_info_matches_cert(PCCERT_CONTEXT pCert,
727 const CRYPT_KEY_PROV_INFO *keyProvInfo)
729 HCRYPTPROV csp;
730 BOOL matches = FALSE;
732 if (CryptAcquireContextW(&csp, keyProvInfo->pwszContainerName,
733 keyProvInfo->pwszProvName, keyProvInfo->dwProvType, keyProvInfo->dwFlags))
735 DWORD size;
737 /* Need to sign something to verify the sig. What to sign? Why not
738 * the certificate itself?
740 if (CryptSignAndEncodeCertificate(csp, AT_SIGNATURE,
741 pCert->dwCertEncodingType, X509_CERT_TO_BE_SIGNED, pCert->pCertInfo,
742 &pCert->pCertInfo->SignatureAlgorithm, NULL, NULL, &size))
744 BYTE *certEncoded = CryptMemAlloc(size);
746 if (certEncoded)
748 if (CryptSignAndEncodeCertificate(csp, AT_SIGNATURE,
749 pCert->dwCertEncodingType, X509_CERT_TO_BE_SIGNED,
750 pCert->pCertInfo, &pCert->pCertInfo->SignatureAlgorithm,
751 NULL, certEncoded, &size))
753 if (size == pCert->cbCertEncoded &&
754 !memcmp(certEncoded, pCert->pbCertEncoded, size))
755 matches = TRUE;
757 CryptMemFree(certEncoded);
760 CryptReleaseContext(csp, 0);
762 return matches;
765 static BOOL container_matches_cert(PCCERT_CONTEXT pCert, LPCSTR container,
766 CRYPT_KEY_PROV_INFO *keyProvInfo)
768 CRYPT_KEY_PROV_INFO copy;
769 WCHAR containerW[MAX_PATH];
770 BOOL matches = FALSE;
772 MultiByteToWideChar(CP_ACP, 0, container, -1,
773 containerW, sizeof(containerW) / sizeof(containerW[0]));
774 /* We make a copy of the CRYPT_KEY_PROV_INFO because the caller expects
775 * keyProvInfo->pwszContainerName to be NULL or a heap-allocated container
776 * name.
778 memcpy(&copy, keyProvInfo, sizeof(copy));
779 copy.pwszContainerName = containerW;
780 matches = key_prov_info_matches_cert(pCert, &copy);
781 if (matches)
783 keyProvInfo->pwszContainerName =
784 CryptMemAlloc((strlenW(containerW) + 1) * sizeof(WCHAR));
785 if (keyProvInfo->pwszContainerName)
787 strcpyW(keyProvInfo->pwszContainerName, containerW);
788 keyProvInfo->dwKeySpec = AT_SIGNATURE;
790 else
791 matches = FALSE;
793 return matches;
796 /* Searches the provider named keyProvInfo.pwszProvName for a container whose
797 * private key matches pCert's public key. Upon success, updates keyProvInfo
798 * with the matching container's info (free keyProvInfo.pwszContainerName upon
799 * success.)
800 * Returns TRUE if found, FALSE if not.
802 static BOOL find_key_prov_info_in_provider(PCCERT_CONTEXT pCert,
803 CRYPT_KEY_PROV_INFO *keyProvInfo)
805 HCRYPTPROV defProvider;
806 BOOL ret, found = FALSE;
807 char containerA[MAX_PATH];
809 assert(keyProvInfo->pwszContainerName == NULL);
810 if ((ret = CryptAcquireContextW(&defProvider, NULL,
811 keyProvInfo->pwszProvName, keyProvInfo->dwProvType,
812 keyProvInfo->dwFlags | CRYPT_VERIFYCONTEXT)))
814 DWORD enumFlags = keyProvInfo->dwFlags | CRYPT_FIRST;
816 while (ret && !found)
818 DWORD size = sizeof(containerA);
820 ret = CryptGetProvParam(defProvider, PP_ENUMCONTAINERS,
821 (BYTE *)containerA, &size, enumFlags);
822 if (ret)
823 found = container_matches_cert(pCert, containerA, keyProvInfo);
824 if (enumFlags & CRYPT_FIRST)
826 enumFlags &= ~CRYPT_FIRST;
827 enumFlags |= CRYPT_NEXT;
830 CryptReleaseContext(defProvider, 0);
832 return found;
835 static BOOL find_matching_provider(PCCERT_CONTEXT pCert, DWORD dwFlags)
837 BOOL found = FALSE, ret = TRUE;
838 DWORD index = 0, cbProvName = 0;
839 CRYPT_KEY_PROV_INFO keyProvInfo;
841 TRACE("(%p, %08x)\n", pCert, dwFlags);
843 memset(&keyProvInfo, 0, sizeof(keyProvInfo));
844 while (ret && !found)
846 DWORD size = 0;
848 ret = CryptEnumProvidersW(index, NULL, 0, &keyProvInfo.dwProvType,
849 NULL, &size);
850 if (ret)
852 if (size <= cbProvName)
853 ret = CryptEnumProvidersW(index, NULL, 0,
854 &keyProvInfo.dwProvType, keyProvInfo.pwszProvName, &size);
855 else
857 CryptMemFree(keyProvInfo.pwszProvName);
858 keyProvInfo.pwszProvName = CryptMemAlloc(size);
859 if (keyProvInfo.pwszProvName)
861 cbProvName = size;
862 ret = CryptEnumProvidersW(index, NULL, 0,
863 &keyProvInfo.dwProvType, keyProvInfo.pwszProvName, &size);
864 if (ret)
866 if (dwFlags & CRYPT_FIND_SILENT_KEYSET_FLAG)
867 keyProvInfo.dwFlags |= CRYPT_SILENT;
868 if (dwFlags & CRYPT_FIND_USER_KEYSET_FLAG ||
869 !(dwFlags & (CRYPT_FIND_USER_KEYSET_FLAG |
870 CRYPT_FIND_MACHINE_KEYSET_FLAG)))
872 keyProvInfo.dwFlags |= CRYPT_USER_KEYSET;
873 found = find_key_prov_info_in_provider(pCert,
874 &keyProvInfo);
876 if (!found)
878 if (dwFlags & CRYPT_FIND_MACHINE_KEYSET_FLAG ||
879 !(dwFlags & (CRYPT_FIND_USER_KEYSET_FLAG |
880 CRYPT_FIND_MACHINE_KEYSET_FLAG)))
882 keyProvInfo.dwFlags &= ~CRYPT_USER_KEYSET;
883 keyProvInfo.dwFlags |= CRYPT_MACHINE_KEYSET;
884 found = find_key_prov_info_in_provider(pCert,
885 &keyProvInfo);
890 else
891 ret = FALSE;
893 index++;
896 if (found)
897 CertSetCertificateContextProperty(pCert, CERT_KEY_PROV_INFO_PROP_ID,
898 0, &keyProvInfo);
899 CryptMemFree(keyProvInfo.pwszProvName);
900 CryptMemFree(keyProvInfo.pwszContainerName);
901 return found;
904 static BOOL cert_prov_info_matches_cert(PCCERT_CONTEXT pCert)
906 BOOL matches = FALSE;
907 DWORD size;
909 if (CertGetCertificateContextProperty(pCert, CERT_KEY_PROV_INFO_PROP_ID,
910 NULL, &size))
912 CRYPT_KEY_PROV_INFO *keyProvInfo = CryptMemAlloc(size);
914 if (keyProvInfo)
916 if (CertGetCertificateContextProperty(pCert,
917 CERT_KEY_PROV_INFO_PROP_ID, keyProvInfo, &size))
918 matches = key_prov_info_matches_cert(pCert, keyProvInfo);
919 CryptMemFree(keyProvInfo);
922 return matches;
925 BOOL WINAPI CryptFindCertificateKeyProvInfo(PCCERT_CONTEXT pCert,
926 DWORD dwFlags, void *pvReserved)
928 BOOL matches = FALSE;
930 TRACE("(%p, %08x, %p)\n", pCert, dwFlags, pvReserved);
932 matches = cert_prov_info_matches_cert(pCert);
933 if (!matches)
934 matches = find_matching_provider(pCert, dwFlags);
935 return matches;
938 BOOL WINAPI CertCompareCertificate(DWORD dwCertEncodingType,
939 PCERT_INFO pCertId1, PCERT_INFO pCertId2)
941 BOOL ret;
943 TRACE("(%08x, %p, %p)\n", dwCertEncodingType, pCertId1, pCertId2);
945 ret = CertCompareCertificateName(dwCertEncodingType, &pCertId1->Issuer,
946 &pCertId2->Issuer) && CertCompareIntegerBlob(&pCertId1->SerialNumber,
947 &pCertId2->SerialNumber);
948 TRACE("returning %d\n", ret);
949 return ret;
952 BOOL WINAPI CertCompareCertificateName(DWORD dwCertEncodingType,
953 PCERT_NAME_BLOB pCertName1, PCERT_NAME_BLOB pCertName2)
955 BOOL ret;
957 TRACE("(%08x, %p, %p)\n", dwCertEncodingType, pCertName1, pCertName2);
959 if (pCertName1->cbData == pCertName2->cbData)
961 if (pCertName1->cbData)
962 ret = !memcmp(pCertName1->pbData, pCertName2->pbData,
963 pCertName1->cbData);
964 else
965 ret = TRUE;
967 else
968 ret = FALSE;
969 TRACE("returning %d\n", ret);
970 return ret;
973 /* Returns the number of significant bytes in pInt, where a byte is
974 * insignificant if it's a leading 0 for positive numbers or a leading 0xff
975 * for negative numbers. pInt is assumed to be little-endian.
977 static DWORD CRYPT_significantBytes(const CRYPT_INTEGER_BLOB *pInt)
979 DWORD ret = pInt->cbData;
981 while (ret > 1)
983 if (pInt->pbData[ret - 2] <= 0x7f && pInt->pbData[ret - 1] == 0)
984 ret--;
985 else if (pInt->pbData[ret - 2] >= 0x80 && pInt->pbData[ret - 1] == 0xff)
986 ret--;
987 else
988 break;
990 return ret;
993 BOOL WINAPI CertCompareIntegerBlob(PCRYPT_INTEGER_BLOB pInt1,
994 PCRYPT_INTEGER_BLOB pInt2)
996 BOOL ret;
997 DWORD cb1, cb2;
999 TRACE("(%p, %p)\n", pInt1, pInt2);
1001 cb1 = CRYPT_significantBytes(pInt1);
1002 cb2 = CRYPT_significantBytes(pInt2);
1003 if (cb1 == cb2)
1005 if (cb1)
1006 ret = !memcmp(pInt1->pbData, pInt2->pbData, cb1);
1007 else
1008 ret = TRUE;
1010 else
1011 ret = FALSE;
1012 TRACE("returning %d\n", ret);
1013 return ret;
1016 BOOL WINAPI CertComparePublicKeyInfo(DWORD dwCertEncodingType,
1017 PCERT_PUBLIC_KEY_INFO pPublicKey1, PCERT_PUBLIC_KEY_INFO pPublicKey2)
1019 BOOL ret;
1021 TRACE("(%08x, %p, %p)\n", dwCertEncodingType, pPublicKey1, pPublicKey2);
1023 switch (GET_CERT_ENCODING_TYPE(dwCertEncodingType))
1025 case 0: /* Seems to mean "raw binary bits" */
1026 if (pPublicKey1->PublicKey.cbData == pPublicKey2->PublicKey.cbData &&
1027 pPublicKey1->PublicKey.cUnusedBits == pPublicKey2->PublicKey.cUnusedBits)
1029 if (pPublicKey2->PublicKey.cbData)
1030 ret = !memcmp(pPublicKey1->PublicKey.pbData,
1031 pPublicKey2->PublicKey.pbData, pPublicKey1->PublicKey.cbData);
1032 else
1033 ret = TRUE;
1035 else
1036 ret = FALSE;
1037 break;
1038 default:
1039 WARN("Unknown encoding type %08x\n", dwCertEncodingType);
1040 /* FALLTHROUGH */
1041 case X509_ASN_ENCODING:
1043 BLOBHEADER *pblob1, *pblob2;
1044 DWORD length;
1045 ret = FALSE;
1046 if (CryptDecodeObject(dwCertEncodingType, RSA_CSP_PUBLICKEYBLOB,
1047 pPublicKey1->PublicKey.pbData, pPublicKey1->PublicKey.cbData,
1048 0, NULL, &length))
1050 pblob1 = CryptMemAlloc(length);
1051 if (CryptDecodeObject(dwCertEncodingType, RSA_CSP_PUBLICKEYBLOB,
1052 pPublicKey1->PublicKey.pbData, pPublicKey1->PublicKey.cbData,
1053 0, pblob1, &length))
1055 if (CryptDecodeObject(dwCertEncodingType, RSA_CSP_PUBLICKEYBLOB,
1056 pPublicKey2->PublicKey.pbData, pPublicKey2->PublicKey.cbData,
1057 0, NULL, &length))
1059 pblob2 = CryptMemAlloc(length);
1060 if (CryptDecodeObject(dwCertEncodingType, RSA_CSP_PUBLICKEYBLOB,
1061 pPublicKey2->PublicKey.pbData, pPublicKey2->PublicKey.cbData,
1062 0, pblob2, &length))
1064 /* The RSAPUBKEY structure directly follows the BLOBHEADER */
1065 RSAPUBKEY *pk1 = (LPVOID)(pblob1 + 1),
1066 *pk2 = (LPVOID)(pblob2 + 1);
1067 ret = (pk1->bitlen == pk2->bitlen) && (pk1->pubexp == pk2->pubexp)
1068 && !memcmp(pk1 + 1, pk2 + 1, pk1->bitlen/8);
1070 CryptMemFree(pblob2);
1073 CryptMemFree(pblob1);
1076 break;
1079 return ret;
1082 DWORD WINAPI CertGetPublicKeyLength(DWORD dwCertEncodingType,
1083 PCERT_PUBLIC_KEY_INFO pPublicKey)
1085 DWORD len = 0;
1087 TRACE("(%08x, %p)\n", dwCertEncodingType, pPublicKey);
1089 if (GET_CERT_ENCODING_TYPE(dwCertEncodingType) != X509_ASN_ENCODING)
1091 SetLastError(ERROR_FILE_NOT_FOUND);
1092 return 0;
1094 if (pPublicKey->Algorithm.pszObjId &&
1095 !strcmp(pPublicKey->Algorithm.pszObjId, szOID_RSA_DH))
1097 FIXME("unimplemented for DH public keys\n");
1098 SetLastError(CRYPT_E_ASN1_BADTAG);
1100 else
1102 DWORD size;
1103 PBYTE buf;
1104 BOOL ret = CryptDecodeObjectEx(dwCertEncodingType,
1105 RSA_CSP_PUBLICKEYBLOB, pPublicKey->PublicKey.pbData,
1106 pPublicKey->PublicKey.cbData, CRYPT_DECODE_ALLOC_FLAG, NULL, &buf,
1107 &size);
1109 if (ret)
1111 RSAPUBKEY *rsaPubKey = (RSAPUBKEY *)(buf + sizeof(BLOBHEADER));
1113 len = rsaPubKey->bitlen;
1114 LocalFree(buf);
1117 return len;
1120 typedef BOOL (*CertCompareFunc)(PCCERT_CONTEXT pCertContext, DWORD dwType,
1121 DWORD dwFlags, const void *pvPara);
1123 static BOOL compare_cert_any(PCCERT_CONTEXT pCertContext, DWORD dwType,
1124 DWORD dwFlags, const void *pvPara)
1126 return TRUE;
1129 static BOOL compare_cert_by_md5_hash(PCCERT_CONTEXT pCertContext, DWORD dwType,
1130 DWORD dwFlags, const void *pvPara)
1132 BOOL ret;
1133 BYTE hash[16];
1134 DWORD size = sizeof(hash);
1136 ret = CertGetCertificateContextProperty(pCertContext,
1137 CERT_MD5_HASH_PROP_ID, hash, &size);
1138 if (ret)
1140 const CRYPT_HASH_BLOB *pHash = pvPara;
1142 if (size == pHash->cbData)
1143 ret = !memcmp(pHash->pbData, hash, size);
1144 else
1145 ret = FALSE;
1147 return ret;
1150 static BOOL compare_cert_by_sha1_hash(PCCERT_CONTEXT pCertContext, DWORD dwType,
1151 DWORD dwFlags, const void *pvPara)
1153 BOOL ret;
1154 BYTE hash[20];
1155 DWORD size = sizeof(hash);
1157 ret = CertGetCertificateContextProperty(pCertContext,
1158 CERT_SHA1_HASH_PROP_ID, hash, &size);
1159 if (ret)
1161 const CRYPT_HASH_BLOB *pHash = pvPara;
1163 if (size == pHash->cbData)
1164 ret = !memcmp(pHash->pbData, hash, size);
1165 else
1166 ret = FALSE;
1168 return ret;
1171 static BOOL compare_cert_by_name(PCCERT_CONTEXT pCertContext, DWORD dwType,
1172 DWORD dwFlags, const void *pvPara)
1174 CERT_NAME_BLOB *blob = (CERT_NAME_BLOB *)pvPara, *toCompare;
1175 BOOL ret;
1177 if (dwType & CERT_INFO_SUBJECT_FLAG)
1178 toCompare = &pCertContext->pCertInfo->Subject;
1179 else
1180 toCompare = &pCertContext->pCertInfo->Issuer;
1181 ret = CertCompareCertificateName(pCertContext->dwCertEncodingType,
1182 toCompare, blob);
1183 return ret;
1186 static BOOL compare_cert_by_public_key(PCCERT_CONTEXT pCertContext,
1187 DWORD dwType, DWORD dwFlags, const void *pvPara)
1189 CERT_PUBLIC_KEY_INFO *publicKey = (CERT_PUBLIC_KEY_INFO *)pvPara;
1190 BOOL ret;
1192 ret = CertComparePublicKeyInfo(pCertContext->dwCertEncodingType,
1193 &pCertContext->pCertInfo->SubjectPublicKeyInfo, publicKey);
1194 return ret;
1197 static BOOL compare_cert_by_subject_cert(PCCERT_CONTEXT pCertContext,
1198 DWORD dwType, DWORD dwFlags, const void *pvPara)
1200 CERT_INFO *pCertInfo = (CERT_INFO *)pvPara;
1201 BOOL ret;
1203 /* Matching serial number and subject match.. */
1204 ret = CertCompareCertificateName(pCertContext->dwCertEncodingType,
1205 &pCertInfo->Issuer, &pCertContext->pCertInfo->Subject);
1206 if (ret)
1207 ret = CertCompareIntegerBlob(&pCertContext->pCertInfo->SerialNumber,
1208 &pCertInfo->SerialNumber);
1209 else
1211 /* failing that, if the serial number and issuer match, we match */
1212 ret = CertCompareIntegerBlob(&pCertContext->pCertInfo->SerialNumber,
1213 &pCertInfo->SerialNumber);
1214 if (ret)
1215 ret = CertCompareCertificateName(pCertContext->dwCertEncodingType,
1216 &pCertInfo->Issuer, &pCertContext->pCertInfo->Issuer);
1218 TRACE("returning %d\n", ret);
1219 return ret;
1222 static BOOL compare_cert_by_cert_id(PCCERT_CONTEXT pCertContext, DWORD dwType,
1223 DWORD dwFlags, const void *pvPara)
1225 CERT_ID *id = (CERT_ID *)pvPara;
1226 BOOL ret;
1228 switch (id->dwIdChoice)
1230 case CERT_ID_ISSUER_SERIAL_NUMBER:
1231 ret = CertCompareCertificateName(pCertContext->dwCertEncodingType,
1232 &pCertContext->pCertInfo->Issuer, &id->u.IssuerSerialNumber.Issuer);
1233 if (ret)
1234 ret = CertCompareIntegerBlob(&pCertContext->pCertInfo->SerialNumber,
1235 &id->u.IssuerSerialNumber.SerialNumber);
1236 break;
1237 case CERT_ID_SHA1_HASH:
1238 ret = compare_cert_by_sha1_hash(pCertContext, dwType, dwFlags,
1239 &id->u.HashId);
1240 break;
1241 case CERT_ID_KEY_IDENTIFIER:
1243 DWORD size = 0;
1245 ret = CertGetCertificateContextProperty(pCertContext,
1246 CERT_KEY_IDENTIFIER_PROP_ID, NULL, &size);
1247 if (ret && size == id->u.KeyId.cbData)
1249 LPBYTE buf = CryptMemAlloc(size);
1251 if (buf)
1253 CertGetCertificateContextProperty(pCertContext,
1254 CERT_KEY_IDENTIFIER_PROP_ID, buf, &size);
1255 ret = !memcmp(buf, id->u.KeyId.pbData, size);
1256 CryptMemFree(buf);
1259 else
1260 ret = FALSE;
1261 break;
1263 default:
1264 ret = FALSE;
1265 break;
1267 return ret;
1270 static BOOL compare_cert_by_issuer(PCCERT_CONTEXT pCertContext, DWORD dwType,
1271 DWORD dwFlags, const void *pvPara)
1273 BOOL ret = FALSE;
1274 PCCERT_CONTEXT subject = pvPara;
1275 PCERT_EXTENSION ext;
1276 DWORD size;
1278 if ((ext = CertFindExtension(szOID_AUTHORITY_KEY_IDENTIFIER,
1279 subject->pCertInfo->cExtension, subject->pCertInfo->rgExtension)))
1281 CERT_AUTHORITY_KEY_ID_INFO *info;
1283 ret = CryptDecodeObjectEx(subject->dwCertEncodingType,
1284 X509_AUTHORITY_KEY_ID, ext->Value.pbData, ext->Value.cbData,
1285 CRYPT_DECODE_ALLOC_FLAG | CRYPT_DECODE_NOCOPY_FLAG, NULL,
1286 &info, &size);
1287 if (ret)
1289 CERT_ID id;
1291 if (info->CertIssuer.cbData && info->CertSerialNumber.cbData)
1293 id.dwIdChoice = CERT_ID_ISSUER_SERIAL_NUMBER;
1294 memcpy(&id.u.IssuerSerialNumber.Issuer, &info->CertIssuer,
1295 sizeof(CERT_NAME_BLOB));
1296 memcpy(&id.u.IssuerSerialNumber.SerialNumber,
1297 &info->CertSerialNumber, sizeof(CRYPT_INTEGER_BLOB));
1298 ret = compare_cert_by_cert_id(pCertContext, dwType, dwFlags,
1299 &id);
1301 else if (info->KeyId.cbData)
1303 id.dwIdChoice = CERT_ID_KEY_IDENTIFIER;
1304 memcpy(&id.u.KeyId, &info->KeyId, sizeof(CRYPT_HASH_BLOB));
1305 ret = compare_cert_by_cert_id(pCertContext, dwType, dwFlags,
1306 &id);
1308 else
1309 ret = FALSE;
1310 LocalFree(info);
1313 else if ((ext = CertFindExtension(szOID_AUTHORITY_KEY_IDENTIFIER2,
1314 subject->pCertInfo->cExtension, subject->pCertInfo->rgExtension)))
1316 CERT_AUTHORITY_KEY_ID2_INFO *info;
1318 ret = CryptDecodeObjectEx(subject->dwCertEncodingType,
1319 X509_AUTHORITY_KEY_ID2, ext->Value.pbData, ext->Value.cbData,
1320 CRYPT_DECODE_ALLOC_FLAG | CRYPT_DECODE_NOCOPY_FLAG, NULL,
1321 &info, &size);
1322 if (ret)
1324 CERT_ID id;
1326 if (info->AuthorityCertIssuer.cAltEntry &&
1327 info->AuthorityCertSerialNumber.cbData)
1329 PCERT_ALT_NAME_ENTRY directoryName = NULL;
1330 DWORD i;
1332 for (i = 0; !directoryName &&
1333 i < info->AuthorityCertIssuer.cAltEntry; i++)
1334 if (info->AuthorityCertIssuer.rgAltEntry[i].dwAltNameChoice
1335 == CERT_ALT_NAME_DIRECTORY_NAME)
1336 directoryName =
1337 &info->AuthorityCertIssuer.rgAltEntry[i];
1338 if (directoryName)
1340 id.dwIdChoice = CERT_ID_ISSUER_SERIAL_NUMBER;
1341 memcpy(&id.u.IssuerSerialNumber.Issuer,
1342 &directoryName->u.DirectoryName, sizeof(CERT_NAME_BLOB));
1343 memcpy(&id.u.IssuerSerialNumber.SerialNumber,
1344 &info->AuthorityCertSerialNumber,
1345 sizeof(CRYPT_INTEGER_BLOB));
1346 ret = compare_cert_by_cert_id(pCertContext, dwType, dwFlags,
1347 &id);
1349 else
1351 FIXME("no supported name type in authority key id2\n");
1352 ret = FALSE;
1355 else if (info->KeyId.cbData)
1357 id.dwIdChoice = CERT_ID_KEY_IDENTIFIER;
1358 memcpy(&id.u.KeyId, &info->KeyId, sizeof(CRYPT_HASH_BLOB));
1359 ret = compare_cert_by_cert_id(pCertContext, dwType, dwFlags,
1360 &id);
1362 else
1363 ret = FALSE;
1364 LocalFree(info);
1367 else
1368 ret = compare_cert_by_name(pCertContext,
1369 CERT_COMPARE_NAME | CERT_COMPARE_SUBJECT_CERT, dwFlags,
1370 &subject->pCertInfo->Issuer);
1371 return ret;
1374 static BOOL compare_existing_cert(PCCERT_CONTEXT pCertContext, DWORD dwType,
1375 DWORD dwFlags, const void *pvPara)
1377 PCCERT_CONTEXT toCompare = pvPara;
1378 return CertCompareCertificate(pCertContext->dwCertEncodingType,
1379 pCertContext->pCertInfo, toCompare->pCertInfo);
1382 static BOOL compare_cert_by_signature_hash(PCCERT_CONTEXT pCertContext, DWORD dwType,
1383 DWORD dwFlags, const void *pvPara)
1385 const CRYPT_HASH_BLOB *hash = pvPara;
1386 DWORD size = 0;
1387 BOOL ret;
1389 ret = CertGetCertificateContextProperty(pCertContext,
1390 CERT_SIGNATURE_HASH_PROP_ID, NULL, &size);
1391 if (ret && size == hash->cbData)
1393 LPBYTE buf = CryptMemAlloc(size);
1395 if (buf)
1397 CertGetCertificateContextProperty(pCertContext,
1398 CERT_SIGNATURE_HASH_PROP_ID, buf, &size);
1399 ret = !memcmp(buf, hash->pbData, size);
1400 CryptMemFree(buf);
1403 else
1404 ret = FALSE;
1405 return ret;
1408 PCCERT_CONTEXT WINAPI CertFindCertificateInStore(HCERTSTORE hCertStore,
1409 DWORD dwCertEncodingType, DWORD dwFlags, DWORD dwType, const void *pvPara,
1410 PCCERT_CONTEXT pPrevCertContext)
1412 PCCERT_CONTEXT ret;
1413 CertCompareFunc compare;
1415 TRACE("(%p, %08x, %08x, %08x, %p, %p)\n", hCertStore, dwCertEncodingType,
1416 dwFlags, dwType, pvPara, pPrevCertContext);
1418 switch (dwType >> CERT_COMPARE_SHIFT)
1420 case CERT_COMPARE_ANY:
1421 compare = compare_cert_any;
1422 break;
1423 case CERT_COMPARE_MD5_HASH:
1424 compare = compare_cert_by_md5_hash;
1425 break;
1426 case CERT_COMPARE_SHA1_HASH:
1427 compare = compare_cert_by_sha1_hash;
1428 break;
1429 case CERT_COMPARE_NAME:
1430 compare = compare_cert_by_name;
1431 break;
1432 case CERT_COMPARE_PUBLIC_KEY:
1433 compare = compare_cert_by_public_key;
1434 break;
1435 case CERT_COMPARE_SUBJECT_CERT:
1436 compare = compare_cert_by_subject_cert;
1437 break;
1438 case CERT_COMPARE_CERT_ID:
1439 compare = compare_cert_by_cert_id;
1440 break;
1441 case CERT_COMPARE_ISSUER_OF:
1442 compare = compare_cert_by_issuer;
1443 break;
1444 case CERT_COMPARE_EXISTING:
1445 compare = compare_existing_cert;
1446 break;
1447 case CERT_COMPARE_SIGNATURE_HASH:
1448 compare = compare_cert_by_signature_hash;
1449 break;
1450 default:
1451 FIXME("find type %08x unimplemented\n", dwType);
1452 compare = NULL;
1455 if (compare)
1457 BOOL matches = FALSE;
1459 ret = pPrevCertContext;
1460 do {
1461 ret = CertEnumCertificatesInStore(hCertStore, ret);
1462 if (ret)
1463 matches = compare(ret, dwType, dwFlags, pvPara);
1464 } while (ret != NULL && !matches);
1465 if (!ret)
1466 SetLastError(CRYPT_E_NOT_FOUND);
1468 else
1470 SetLastError(CRYPT_E_NOT_FOUND);
1471 ret = NULL;
1473 TRACE("returning %p\n", ret);
1474 return ret;
1477 PCCERT_CONTEXT WINAPI CertGetSubjectCertificateFromStore(HCERTSTORE hCertStore,
1478 DWORD dwCertEncodingType, PCERT_INFO pCertId)
1480 TRACE("(%p, %08x, %p)\n", hCertStore, dwCertEncodingType, pCertId);
1482 if (!pCertId)
1484 SetLastError(E_INVALIDARG);
1485 return NULL;
1487 return CertFindCertificateInStore(hCertStore, dwCertEncodingType, 0,
1488 CERT_FIND_SUBJECT_CERT, pCertId, NULL);
1491 BOOL WINAPI CertVerifySubjectCertificateContext(PCCERT_CONTEXT pSubject,
1492 PCCERT_CONTEXT pIssuer, DWORD *pdwFlags)
1494 static const DWORD supportedFlags = CERT_STORE_REVOCATION_FLAG |
1495 CERT_STORE_SIGNATURE_FLAG | CERT_STORE_TIME_VALIDITY_FLAG;
1497 if (*pdwFlags & ~supportedFlags)
1499 SetLastError(E_INVALIDARG);
1500 return FALSE;
1502 if (*pdwFlags & CERT_STORE_REVOCATION_FLAG)
1504 DWORD flags = 0;
1505 PCCRL_CONTEXT crl = CertGetCRLFromStore(pSubject->hCertStore, pSubject,
1506 NULL, &flags);
1508 /* FIXME: what if the CRL has expired? */
1509 if (crl)
1511 if (CertVerifyCRLRevocation(pSubject->dwCertEncodingType,
1512 pSubject->pCertInfo, 1, (PCRL_INFO *)&crl->pCrlInfo))
1513 *pdwFlags &= CERT_STORE_REVOCATION_FLAG;
1515 else
1516 *pdwFlags |= CERT_STORE_NO_CRL_FLAG;
1518 if (*pdwFlags & CERT_STORE_TIME_VALIDITY_FLAG)
1520 if (0 == CertVerifyTimeValidity(NULL, pSubject->pCertInfo))
1521 *pdwFlags &= ~CERT_STORE_TIME_VALIDITY_FLAG;
1523 if (*pdwFlags & CERT_STORE_SIGNATURE_FLAG)
1525 if (CryptVerifyCertificateSignatureEx(0, pSubject->dwCertEncodingType,
1526 CRYPT_VERIFY_CERT_SIGN_SUBJECT_CERT, (void *)pSubject,
1527 CRYPT_VERIFY_CERT_SIGN_ISSUER_CERT, (void *)pIssuer, 0, NULL))
1528 *pdwFlags &= ~CERT_STORE_SIGNATURE_FLAG;
1530 return TRUE;
1533 PCCERT_CONTEXT WINAPI CertGetIssuerCertificateFromStore(HCERTSTORE hCertStore,
1534 PCCERT_CONTEXT pSubjectContext, PCCERT_CONTEXT pPrevIssuerContext,
1535 DWORD *pdwFlags)
1537 PCCERT_CONTEXT ret;
1539 TRACE("(%p, %p, %p, %08x)\n", hCertStore, pSubjectContext,
1540 pPrevIssuerContext, *pdwFlags);
1542 if (!pSubjectContext)
1544 SetLastError(E_INVALIDARG);
1545 return NULL;
1548 ret = CertFindCertificateInStore(hCertStore,
1549 pSubjectContext->dwCertEncodingType, 0, CERT_FIND_ISSUER_OF,
1550 pSubjectContext, pPrevIssuerContext);
1551 if (ret)
1553 if (!CertVerifySubjectCertificateContext(pSubjectContext, ret,
1554 pdwFlags))
1556 CertFreeCertificateContext(ret);
1557 ret = NULL;
1560 TRACE("returning %p\n", ret);
1561 return ret;
1564 typedef struct _OLD_CERT_REVOCATION_STATUS {
1565 DWORD cbSize;
1566 DWORD dwIndex;
1567 DWORD dwError;
1568 DWORD dwReason;
1569 } OLD_CERT_REVOCATION_STATUS, *POLD_CERT_REVOCATION_STATUS;
1571 typedef BOOL (WINAPI *CertVerifyRevocationFunc)(DWORD, DWORD, DWORD,
1572 void **, DWORD, PCERT_REVOCATION_PARA, PCERT_REVOCATION_STATUS);
1574 BOOL WINAPI CertVerifyRevocation(DWORD dwEncodingType, DWORD dwRevType,
1575 DWORD cContext, PVOID rgpvContext[], DWORD dwFlags,
1576 PCERT_REVOCATION_PARA pRevPara, PCERT_REVOCATION_STATUS pRevStatus)
1578 BOOL ret;
1580 TRACE("(%08x, %d, %d, %p, %08x, %p, %p)\n", dwEncodingType, dwRevType,
1581 cContext, rgpvContext, dwFlags, pRevPara, pRevStatus);
1583 if (pRevStatus->cbSize != sizeof(OLD_CERT_REVOCATION_STATUS) &&
1584 pRevStatus->cbSize != sizeof(CERT_REVOCATION_STATUS))
1586 SetLastError(E_INVALIDARG);
1587 return FALSE;
1589 if (cContext)
1591 static HCRYPTOIDFUNCSET set = NULL;
1592 DWORD size;
1594 if (!set)
1595 set = CryptInitOIDFunctionSet(CRYPT_OID_VERIFY_REVOCATION_FUNC, 0);
1596 ret = CryptGetDefaultOIDDllList(set, dwEncodingType, NULL, &size);
1597 if (ret)
1599 if (size == 1)
1601 /* empty list */
1602 SetLastError(CRYPT_E_NO_REVOCATION_DLL);
1603 ret = FALSE;
1605 else
1607 LPWSTR dllList = CryptMemAlloc(size * sizeof(WCHAR)), ptr;
1609 if (dllList)
1611 ret = CryptGetDefaultOIDDllList(set, dwEncodingType,
1612 dllList, &size);
1613 if (ret)
1615 for (ptr = dllList; ret && *ptr;
1616 ptr += lstrlenW(ptr) + 1)
1618 CertVerifyRevocationFunc func;
1619 HCRYPTOIDFUNCADDR hFunc;
1621 ret = CryptGetDefaultOIDFunctionAddress(set,
1622 dwEncodingType, ptr, 0, (void **)&func, &hFunc);
1623 if (ret)
1625 ret = func(dwEncodingType, dwRevType, cContext,
1626 rgpvContext, dwFlags, pRevPara, pRevStatus);
1627 CryptFreeOIDFunctionAddress(hFunc, 0);
1631 CryptMemFree(dllList);
1633 else
1635 SetLastError(ERROR_OUTOFMEMORY);
1636 ret = FALSE;
1641 else
1642 ret = TRUE;
1643 return ret;
1646 PCRYPT_ATTRIBUTE WINAPI CertFindAttribute(LPCSTR pszObjId, DWORD cAttr,
1647 CRYPT_ATTRIBUTE rgAttr[])
1649 PCRYPT_ATTRIBUTE ret = NULL;
1650 DWORD i;
1652 TRACE("%s %d %p\n", debugstr_a(pszObjId), cAttr, rgAttr);
1654 if (!cAttr)
1655 return NULL;
1656 if (!pszObjId)
1658 SetLastError(ERROR_INVALID_PARAMETER);
1659 return NULL;
1662 for (i = 0; !ret && i < cAttr; i++)
1663 if (rgAttr[i].pszObjId && !strcmp(pszObjId, rgAttr[i].pszObjId))
1664 ret = &rgAttr[i];
1665 return ret;
1668 PCERT_EXTENSION WINAPI CertFindExtension(LPCSTR pszObjId, DWORD cExtensions,
1669 CERT_EXTENSION rgExtensions[])
1671 PCERT_EXTENSION ret = NULL;
1672 DWORD i;
1674 TRACE("%s %d %p\n", debugstr_a(pszObjId), cExtensions, rgExtensions);
1676 if (!cExtensions)
1677 return NULL;
1678 if (!pszObjId)
1680 SetLastError(ERROR_INVALID_PARAMETER);
1681 return NULL;
1684 for (i = 0; !ret && i < cExtensions; i++)
1685 if (rgExtensions[i].pszObjId && !strcmp(pszObjId,
1686 rgExtensions[i].pszObjId))
1687 ret = &rgExtensions[i];
1688 return ret;
1691 PCERT_RDN_ATTR WINAPI CertFindRDNAttr(LPCSTR pszObjId, PCERT_NAME_INFO pName)
1693 PCERT_RDN_ATTR ret = NULL;
1694 DWORD i, j;
1696 TRACE("%s %p\n", debugstr_a(pszObjId), pName);
1698 if (!pszObjId)
1700 SetLastError(ERROR_INVALID_PARAMETER);
1701 return NULL;
1704 for (i = 0; !ret && i < pName->cRDN; i++)
1705 for (j = 0; !ret && j < pName->rgRDN[i].cRDNAttr; j++)
1706 if (pName->rgRDN[i].rgRDNAttr[j].pszObjId && !strcmp(pszObjId,
1707 pName->rgRDN[i].rgRDNAttr[j].pszObjId))
1708 ret = &pName->rgRDN[i].rgRDNAttr[j];
1709 return ret;
1712 LONG WINAPI CertVerifyTimeValidity(LPFILETIME pTimeToVerify,
1713 PCERT_INFO pCertInfo)
1715 FILETIME fileTime;
1716 LONG ret;
1718 if (!pTimeToVerify)
1720 GetSystemTimeAsFileTime(&fileTime);
1721 pTimeToVerify = &fileTime;
1723 if ((ret = CompareFileTime(pTimeToVerify, &pCertInfo->NotBefore)) >= 0)
1725 ret = CompareFileTime(pTimeToVerify, &pCertInfo->NotAfter);
1726 if (ret < 0)
1727 ret = 0;
1729 return ret;
1732 BOOL WINAPI CertVerifyValidityNesting(PCERT_INFO pSubjectInfo,
1733 PCERT_INFO pIssuerInfo)
1735 TRACE("(%p, %p)\n", pSubjectInfo, pIssuerInfo);
1737 return CertVerifyTimeValidity(&pSubjectInfo->NotBefore, pIssuerInfo) == 0
1738 && CertVerifyTimeValidity(&pSubjectInfo->NotAfter, pIssuerInfo) == 0;
1741 BOOL WINAPI CryptHashCertificate(HCRYPTPROV_LEGACY hCryptProv, ALG_ID Algid,
1742 DWORD dwFlags, const BYTE *pbEncoded, DWORD cbEncoded, BYTE *pbComputedHash,
1743 DWORD *pcbComputedHash)
1745 BOOL ret = TRUE;
1746 HCRYPTHASH hHash = 0;
1748 TRACE("(%08lx, %d, %08x, %p, %d, %p, %p)\n", hCryptProv, Algid, dwFlags,
1749 pbEncoded, cbEncoded, pbComputedHash, pcbComputedHash);
1751 if (!hCryptProv)
1752 hCryptProv = CRYPT_GetDefaultProvider();
1753 if (!Algid)
1754 Algid = CALG_SHA1;
1755 if (ret)
1757 ret = CryptCreateHash(hCryptProv, Algid, 0, 0, &hHash);
1758 if (ret)
1760 ret = CryptHashData(hHash, pbEncoded, cbEncoded, 0);
1761 if (ret)
1762 ret = CryptGetHashParam(hHash, HP_HASHVAL, pbComputedHash,
1763 pcbComputedHash, 0);
1764 CryptDestroyHash(hHash);
1767 return ret;
1770 BOOL WINAPI CryptHashPublicKeyInfo(HCRYPTPROV_LEGACY hCryptProv, ALG_ID Algid,
1771 DWORD dwFlags, DWORD dwCertEncodingType, PCERT_PUBLIC_KEY_INFO pInfo,
1772 BYTE *pbComputedHash, DWORD *pcbComputedHash)
1774 BOOL ret = TRUE;
1775 HCRYPTHASH hHash = 0;
1777 TRACE("(%08lx, %d, %08x, %d, %p, %p, %p)\n", hCryptProv, Algid, dwFlags,
1778 dwCertEncodingType, pInfo, pbComputedHash, pcbComputedHash);
1780 if (!hCryptProv)
1781 hCryptProv = CRYPT_GetDefaultProvider();
1782 if (!Algid)
1783 Algid = CALG_MD5;
1784 if (ret)
1786 BYTE *buf;
1787 DWORD size = 0;
1789 ret = CryptEncodeObjectEx(dwCertEncodingType, X509_PUBLIC_KEY_INFO,
1790 pInfo, CRYPT_ENCODE_ALLOC_FLAG, NULL, &buf, &size);
1791 if (ret)
1793 ret = CryptCreateHash(hCryptProv, Algid, 0, 0, &hHash);
1794 if (ret)
1796 ret = CryptHashData(hHash, buf, size, 0);
1797 if (ret)
1798 ret = CryptGetHashParam(hHash, HP_HASHVAL, pbComputedHash,
1799 pcbComputedHash, 0);
1800 CryptDestroyHash(hHash);
1802 LocalFree(buf);
1805 return ret;
1808 BOOL WINAPI CryptHashToBeSigned(HCRYPTPROV_LEGACY hCryptProv,
1809 DWORD dwCertEncodingType, const BYTE *pbEncoded, DWORD cbEncoded,
1810 BYTE *pbComputedHash, DWORD *pcbComputedHash)
1812 BOOL ret;
1813 CERT_SIGNED_CONTENT_INFO *info;
1814 DWORD size;
1816 TRACE("(%08lx, %08x, %p, %d, %p, %d)\n", hCryptProv, dwCertEncodingType,
1817 pbEncoded, cbEncoded, pbComputedHash, *pcbComputedHash);
1819 ret = CryptDecodeObjectEx(dwCertEncodingType, X509_CERT,
1820 pbEncoded, cbEncoded, CRYPT_DECODE_ALLOC_FLAG, NULL, &info, &size);
1821 if (ret)
1823 PCCRYPT_OID_INFO oidInfo;
1824 HCRYPTHASH hHash;
1826 if (!hCryptProv)
1827 hCryptProv = CRYPT_GetDefaultProvider();
1828 oidInfo = CryptFindOIDInfo(CRYPT_OID_INFO_OID_KEY,
1829 info->SignatureAlgorithm.pszObjId, 0);
1830 if (!oidInfo)
1832 SetLastError(NTE_BAD_ALGID);
1833 ret = FALSE;
1835 else
1837 ret = CryptCreateHash(hCryptProv, oidInfo->u.Algid, 0, 0, &hHash);
1838 if (ret)
1840 ret = CryptHashData(hHash, info->ToBeSigned.pbData,
1841 info->ToBeSigned.cbData, 0);
1842 if (ret)
1843 ret = CryptGetHashParam(hHash, HP_HASHVAL, pbComputedHash,
1844 pcbComputedHash, 0);
1845 CryptDestroyHash(hHash);
1848 LocalFree(info);
1850 return ret;
1853 BOOL WINAPI CryptSignCertificate(HCRYPTPROV_OR_NCRYPT_KEY_HANDLE hCryptProv,
1854 DWORD dwKeySpec, DWORD dwCertEncodingType, const BYTE *pbEncodedToBeSigned,
1855 DWORD cbEncodedToBeSigned, PCRYPT_ALGORITHM_IDENTIFIER pSignatureAlgorithm,
1856 const void *pvHashAuxInfo, BYTE *pbSignature, DWORD *pcbSignature)
1858 BOOL ret;
1859 PCCRYPT_OID_INFO info;
1860 HCRYPTHASH hHash;
1862 TRACE("(%08lx, %d, %d, %p, %d, %p, %p, %p, %p)\n", hCryptProv,
1863 dwKeySpec, dwCertEncodingType, pbEncodedToBeSigned, cbEncodedToBeSigned,
1864 pSignatureAlgorithm, pvHashAuxInfo, pbSignature, pcbSignature);
1866 info = CryptFindOIDInfo(CRYPT_OID_INFO_OID_KEY,
1867 pSignatureAlgorithm->pszObjId, 0);
1868 if (!info)
1870 SetLastError(NTE_BAD_ALGID);
1871 return FALSE;
1873 if (info->dwGroupId == CRYPT_HASH_ALG_OID_GROUP_ID)
1875 if (!hCryptProv)
1876 hCryptProv = CRYPT_GetDefaultProvider();
1877 ret = CryptCreateHash(hCryptProv, info->u.Algid, 0, 0, &hHash);
1878 if (ret)
1880 ret = CryptHashData(hHash, pbEncodedToBeSigned,
1881 cbEncodedToBeSigned, 0);
1882 if (ret)
1883 ret = CryptGetHashParam(hHash, HP_HASHVAL, pbSignature,
1884 pcbSignature, 0);
1885 CryptDestroyHash(hHash);
1888 else
1890 if (!hCryptProv)
1892 SetLastError(ERROR_INVALID_PARAMETER);
1893 ret = FALSE;
1895 else
1897 ret = CryptCreateHash(hCryptProv, info->u.Algid, 0, 0, &hHash);
1898 if (ret)
1900 ret = CryptHashData(hHash, pbEncodedToBeSigned,
1901 cbEncodedToBeSigned, 0);
1902 if (ret)
1903 ret = CryptSignHashW(hHash, dwKeySpec, NULL, 0, pbSignature,
1904 pcbSignature);
1905 CryptDestroyHash(hHash);
1909 return ret;
1912 BOOL WINAPI CryptSignAndEncodeCertificate(HCRYPTPROV_OR_NCRYPT_KEY_HANDLE hCryptProv,
1913 DWORD dwKeySpec, DWORD dwCertEncodingType, LPCSTR lpszStructType,
1914 const void *pvStructInfo, PCRYPT_ALGORITHM_IDENTIFIER pSignatureAlgorithm,
1915 const void *pvHashAuxInfo, BYTE *pbEncoded, DWORD *pcbEncoded)
1917 BOOL ret;
1918 DWORD encodedSize, hashSize;
1920 TRACE("(%08lx, %d, %d, %s, %p, %p, %p, %p, %p)\n", hCryptProv, dwKeySpec,
1921 dwCertEncodingType, debugstr_a(lpszStructType), pvStructInfo,
1922 pSignatureAlgorithm, pvHashAuxInfo, pbEncoded, pcbEncoded);
1924 ret = CryptEncodeObject(dwCertEncodingType, lpszStructType, pvStructInfo,
1925 NULL, &encodedSize);
1926 if (ret)
1928 PBYTE encoded = CryptMemAlloc(encodedSize);
1930 if (encoded)
1932 ret = CryptEncodeObject(dwCertEncodingType, lpszStructType,
1933 pvStructInfo, encoded, &encodedSize);
1934 if (ret)
1936 ret = CryptSignCertificate(hCryptProv, dwKeySpec,
1937 dwCertEncodingType, encoded, encodedSize, pSignatureAlgorithm,
1938 pvHashAuxInfo, NULL, &hashSize);
1939 if (ret)
1941 PBYTE hash = CryptMemAlloc(hashSize);
1943 if (hash)
1945 ret = CryptSignCertificate(hCryptProv, dwKeySpec,
1946 dwCertEncodingType, encoded, encodedSize,
1947 pSignatureAlgorithm, pvHashAuxInfo, hash, &hashSize);
1948 if (ret)
1950 CERT_SIGNED_CONTENT_INFO info = { { 0 } };
1952 info.ToBeSigned.cbData = encodedSize;
1953 info.ToBeSigned.pbData = encoded;
1954 memcpy(&info.SignatureAlgorithm,
1955 pSignatureAlgorithm,
1956 sizeof(info.SignatureAlgorithm));
1957 info.Signature.cbData = hashSize;
1958 info.Signature.pbData = hash;
1959 info.Signature.cUnusedBits = 0;
1960 ret = CryptEncodeObject(dwCertEncodingType,
1961 X509_CERT, &info, pbEncoded, pcbEncoded);
1963 CryptMemFree(hash);
1967 CryptMemFree(encoded);
1970 return ret;
1973 BOOL WINAPI CryptVerifyCertificateSignature(HCRYPTPROV_LEGACY hCryptProv,
1974 DWORD dwCertEncodingType, const BYTE *pbEncoded, DWORD cbEncoded,
1975 PCERT_PUBLIC_KEY_INFO pPublicKey)
1977 return CryptVerifyCertificateSignatureEx(hCryptProv, dwCertEncodingType,
1978 CRYPT_VERIFY_CERT_SIGN_SUBJECT_BLOB, (void *)pbEncoded,
1979 CRYPT_VERIFY_CERT_SIGN_ISSUER_PUBKEY, pPublicKey, 0, NULL);
1982 static BOOL CRYPT_VerifyCertSignatureFromPublicKeyInfo(HCRYPTPROV_LEGACY hCryptProv,
1983 DWORD dwCertEncodingType, PCERT_PUBLIC_KEY_INFO pubKeyInfo,
1984 const CERT_SIGNED_CONTENT_INFO *signedCert)
1986 BOOL ret;
1987 HCRYPTKEY key;
1988 PCCRYPT_OID_INFO info;
1989 ALG_ID pubKeyID, hashID;
1991 info = CryptFindOIDInfo(CRYPT_OID_INFO_OID_KEY,
1992 signedCert->SignatureAlgorithm.pszObjId, 0);
1993 if (!info || info->dwGroupId != CRYPT_SIGN_ALG_OID_GROUP_ID)
1995 SetLastError(NTE_BAD_ALGID);
1996 return FALSE;
1998 hashID = info->u.Algid;
1999 if (info->ExtraInfo.cbData >= sizeof(ALG_ID))
2000 pubKeyID = *(ALG_ID *)info->ExtraInfo.pbData;
2001 else
2002 pubKeyID = hashID;
2003 /* Load the default provider if necessary */
2004 if (!hCryptProv)
2005 hCryptProv = CRYPT_GetDefaultProvider();
2006 ret = CryptImportPublicKeyInfoEx(hCryptProv, dwCertEncodingType,
2007 pubKeyInfo, pubKeyID, 0, NULL, &key);
2008 if (ret)
2010 HCRYPTHASH hash;
2012 ret = CryptCreateHash(hCryptProv, hashID, 0, 0, &hash);
2013 if (ret)
2015 ret = CryptHashData(hash, signedCert->ToBeSigned.pbData,
2016 signedCert->ToBeSigned.cbData, 0);
2017 if (ret)
2018 ret = CryptVerifySignatureW(hash, signedCert->Signature.pbData,
2019 signedCert->Signature.cbData, key, NULL, 0);
2020 CryptDestroyHash(hash);
2022 CryptDestroyKey(key);
2024 return ret;
2027 BOOL WINAPI CryptVerifyCertificateSignatureEx(HCRYPTPROV_LEGACY hCryptProv,
2028 DWORD dwCertEncodingType, DWORD dwSubjectType, void *pvSubject,
2029 DWORD dwIssuerType, void *pvIssuer, DWORD dwFlags, void *pvReserved)
2031 BOOL ret = TRUE;
2032 CRYPT_DATA_BLOB subjectBlob;
2034 TRACE("(%08lx, %d, %d, %p, %d, %p, %08x, %p)\n", hCryptProv,
2035 dwCertEncodingType, dwSubjectType, pvSubject, dwIssuerType, pvIssuer,
2036 dwFlags, pvReserved);
2038 switch (dwSubjectType)
2040 case CRYPT_VERIFY_CERT_SIGN_SUBJECT_BLOB:
2042 PCRYPT_DATA_BLOB blob = pvSubject;
2044 subjectBlob.pbData = blob->pbData;
2045 subjectBlob.cbData = blob->cbData;
2046 break;
2048 case CRYPT_VERIFY_CERT_SIGN_SUBJECT_CERT:
2050 PCERT_CONTEXT context = pvSubject;
2052 subjectBlob.pbData = context->pbCertEncoded;
2053 subjectBlob.cbData = context->cbCertEncoded;
2054 break;
2056 case CRYPT_VERIFY_CERT_SIGN_SUBJECT_CRL:
2058 PCRL_CONTEXT context = pvSubject;
2060 subjectBlob.pbData = context->pbCrlEncoded;
2061 subjectBlob.cbData = context->cbCrlEncoded;
2062 break;
2064 default:
2065 SetLastError(E_INVALIDARG);
2066 ret = FALSE;
2069 if (ret)
2071 PCERT_SIGNED_CONTENT_INFO signedCert = NULL;
2072 DWORD size = 0;
2074 ret = CryptDecodeObjectEx(dwCertEncodingType, X509_CERT,
2075 subjectBlob.pbData, subjectBlob.cbData,
2076 CRYPT_DECODE_ALLOC_FLAG | CRYPT_DECODE_NOCOPY_FLAG, NULL,
2077 &signedCert, &size);
2078 if (ret)
2080 switch (dwIssuerType)
2082 case CRYPT_VERIFY_CERT_SIGN_ISSUER_PUBKEY:
2083 ret = CRYPT_VerifyCertSignatureFromPublicKeyInfo(hCryptProv,
2084 dwCertEncodingType, pvIssuer,
2085 signedCert);
2086 break;
2087 case CRYPT_VERIFY_CERT_SIGN_ISSUER_CERT:
2088 ret = CRYPT_VerifyCertSignatureFromPublicKeyInfo(hCryptProv,
2089 dwCertEncodingType,
2090 &((PCCERT_CONTEXT)pvIssuer)->pCertInfo->SubjectPublicKeyInfo,
2091 signedCert);
2092 break;
2093 case CRYPT_VERIFY_CERT_SIGN_ISSUER_CHAIN:
2094 FIXME("CRYPT_VERIFY_CERT_SIGN_ISSUER_CHAIN: stub\n");
2095 ret = FALSE;
2096 break;
2097 case CRYPT_VERIFY_CERT_SIGN_ISSUER_NULL:
2098 if (pvIssuer)
2100 SetLastError(E_INVALIDARG);
2101 ret = FALSE;
2103 else
2105 FIXME("unimplemented for NULL signer\n");
2106 SetLastError(E_INVALIDARG);
2107 ret = FALSE;
2109 break;
2110 default:
2111 SetLastError(E_INVALIDARG);
2112 ret = FALSE;
2114 LocalFree(signedCert);
2117 return ret;
2120 BOOL WINAPI CertGetEnhancedKeyUsage(PCCERT_CONTEXT pCertContext, DWORD dwFlags,
2121 PCERT_ENHKEY_USAGE pUsage, DWORD *pcbUsage)
2123 PCERT_ENHKEY_USAGE usage = NULL;
2124 DWORD bytesNeeded;
2125 BOOL ret = TRUE;
2127 if (!pCertContext || !pcbUsage)
2129 SetLastError(ERROR_INVALID_PARAMETER);
2130 return FALSE;
2133 TRACE("(%p, %08x, %p, %d)\n", pCertContext, dwFlags, pUsage, *pcbUsage);
2135 if (!(dwFlags & CERT_FIND_EXT_ONLY_ENHKEY_USAGE_FLAG))
2137 DWORD propSize = 0;
2139 if (CertGetCertificateContextProperty(pCertContext,
2140 CERT_ENHKEY_USAGE_PROP_ID, NULL, &propSize))
2142 LPBYTE buf = CryptMemAlloc(propSize);
2144 if (buf)
2146 if (CertGetCertificateContextProperty(pCertContext,
2147 CERT_ENHKEY_USAGE_PROP_ID, buf, &propSize))
2149 ret = CryptDecodeObjectEx(pCertContext->dwCertEncodingType,
2150 X509_ENHANCED_KEY_USAGE, buf, propSize,
2151 CRYPT_ENCODE_ALLOC_FLAG, NULL, &usage, &bytesNeeded);
2153 CryptMemFree(buf);
2157 if (!usage && !(dwFlags & CERT_FIND_PROP_ONLY_ENHKEY_USAGE_FLAG))
2159 PCERT_EXTENSION ext = CertFindExtension(szOID_ENHANCED_KEY_USAGE,
2160 pCertContext->pCertInfo->cExtension,
2161 pCertContext->pCertInfo->rgExtension);
2163 if (ext)
2165 ret = CryptDecodeObjectEx(pCertContext->dwCertEncodingType,
2166 X509_ENHANCED_KEY_USAGE, ext->Value.pbData, ext->Value.cbData,
2167 CRYPT_ENCODE_ALLOC_FLAG, NULL, &usage, &bytesNeeded);
2170 if (!usage)
2172 /* If a particular location is specified, this should fail. Otherwise
2173 * it should succeed with an empty usage. (This is true on Win2k and
2174 * later, which we emulate.)
2176 if (dwFlags)
2178 SetLastError(CRYPT_E_NOT_FOUND);
2179 ret = FALSE;
2181 else
2182 bytesNeeded = sizeof(CERT_ENHKEY_USAGE);
2185 if (ret)
2187 if (!pUsage)
2188 *pcbUsage = bytesNeeded;
2189 else if (*pcbUsage < bytesNeeded)
2191 SetLastError(ERROR_MORE_DATA);
2192 *pcbUsage = bytesNeeded;
2193 ret = FALSE;
2195 else
2197 *pcbUsage = bytesNeeded;
2198 if (usage)
2200 DWORD i;
2201 LPSTR nextOID = (LPSTR)((LPBYTE)pUsage +
2202 sizeof(CERT_ENHKEY_USAGE) +
2203 usage->cUsageIdentifier * sizeof(LPSTR));
2205 pUsage->cUsageIdentifier = usage->cUsageIdentifier;
2206 pUsage->rgpszUsageIdentifier = (LPSTR *)((LPBYTE)pUsage +
2207 sizeof(CERT_ENHKEY_USAGE));
2208 for (i = 0; i < usage->cUsageIdentifier; i++)
2210 pUsage->rgpszUsageIdentifier[i] = nextOID;
2211 strcpy(nextOID, usage->rgpszUsageIdentifier[i]);
2212 nextOID += strlen(nextOID) + 1;
2215 else
2216 pUsage->cUsageIdentifier = 0;
2219 if (usage)
2220 LocalFree(usage);
2221 TRACE("returning %d\n", ret);
2222 return ret;
2225 BOOL WINAPI CertSetEnhancedKeyUsage(PCCERT_CONTEXT pCertContext,
2226 PCERT_ENHKEY_USAGE pUsage)
2228 BOOL ret;
2230 TRACE("(%p, %p)\n", pCertContext, pUsage);
2232 if (pUsage)
2234 CRYPT_DATA_BLOB blob = { 0, NULL };
2236 ret = CryptEncodeObjectEx(X509_ASN_ENCODING, X509_ENHANCED_KEY_USAGE,
2237 pUsage, CRYPT_ENCODE_ALLOC_FLAG, NULL, &blob.pbData, &blob.cbData);
2238 if (ret)
2240 ret = CertSetCertificateContextProperty(pCertContext,
2241 CERT_ENHKEY_USAGE_PROP_ID, 0, &blob);
2242 LocalFree(blob.pbData);
2245 else
2246 ret = CertSetCertificateContextProperty(pCertContext,
2247 CERT_ENHKEY_USAGE_PROP_ID, 0, NULL);
2248 return ret;
2251 BOOL WINAPI CertAddEnhancedKeyUsageIdentifier(PCCERT_CONTEXT pCertContext,
2252 LPCSTR pszUsageIdentifier)
2254 BOOL ret;
2255 DWORD size;
2257 TRACE("(%p, %s)\n", pCertContext, debugstr_a(pszUsageIdentifier));
2259 if (CertGetEnhancedKeyUsage(pCertContext,
2260 CERT_FIND_PROP_ONLY_ENHKEY_USAGE_FLAG, NULL, &size))
2262 PCERT_ENHKEY_USAGE usage = CryptMemAlloc(size);
2264 if (usage)
2266 ret = CertGetEnhancedKeyUsage(pCertContext,
2267 CERT_FIND_PROP_ONLY_ENHKEY_USAGE_FLAG, usage, &size);
2268 if (ret)
2270 DWORD i;
2271 BOOL exists = FALSE;
2273 /* Make sure usage doesn't already exist */
2274 for (i = 0; !exists && i < usage->cUsageIdentifier; i++)
2276 if (!strcmp(usage->rgpszUsageIdentifier[i],
2277 pszUsageIdentifier))
2278 exists = TRUE;
2280 if (!exists)
2282 PCERT_ENHKEY_USAGE newUsage = CryptMemAlloc(size +
2283 sizeof(LPSTR) + strlen(pszUsageIdentifier) + 1);
2285 if (newUsage)
2287 LPSTR nextOID;
2289 newUsage->rgpszUsageIdentifier = (LPSTR *)
2290 ((LPBYTE)newUsage + sizeof(CERT_ENHKEY_USAGE));
2291 nextOID = (LPSTR)((LPBYTE)newUsage->rgpszUsageIdentifier
2292 + (usage->cUsageIdentifier + 1) * sizeof(LPSTR));
2293 for (i = 0; i < usage->cUsageIdentifier; i++)
2295 newUsage->rgpszUsageIdentifier[i] = nextOID;
2296 strcpy(nextOID, usage->rgpszUsageIdentifier[i]);
2297 nextOID += strlen(nextOID) + 1;
2299 newUsage->rgpszUsageIdentifier[i] = nextOID;
2300 strcpy(nextOID, pszUsageIdentifier);
2301 newUsage->cUsageIdentifier = i + 1;
2302 ret = CertSetEnhancedKeyUsage(pCertContext, newUsage);
2303 CryptMemFree(newUsage);
2305 else
2306 ret = FALSE;
2309 CryptMemFree(usage);
2311 else
2312 ret = FALSE;
2314 else
2316 PCERT_ENHKEY_USAGE usage = CryptMemAlloc(sizeof(CERT_ENHKEY_USAGE) +
2317 sizeof(LPSTR) + strlen(pszUsageIdentifier) + 1);
2319 if (usage)
2321 usage->rgpszUsageIdentifier =
2322 (LPSTR *)((LPBYTE)usage + sizeof(CERT_ENHKEY_USAGE));
2323 usage->rgpszUsageIdentifier[0] = (LPSTR)((LPBYTE)usage +
2324 sizeof(CERT_ENHKEY_USAGE) + sizeof(LPSTR));
2325 strcpy(usage->rgpszUsageIdentifier[0], pszUsageIdentifier);
2326 usage->cUsageIdentifier = 1;
2327 ret = CertSetEnhancedKeyUsage(pCertContext, usage);
2328 CryptMemFree(usage);
2330 else
2331 ret = FALSE;
2333 return ret;
2336 BOOL WINAPI CertRemoveEnhancedKeyUsageIdentifier(PCCERT_CONTEXT pCertContext,
2337 LPCSTR pszUsageIdentifier)
2339 BOOL ret;
2340 DWORD size;
2341 CERT_ENHKEY_USAGE usage;
2343 TRACE("(%p, %s)\n", pCertContext, debugstr_a(pszUsageIdentifier));
2345 size = sizeof(usage);
2346 ret = CertGetEnhancedKeyUsage(pCertContext,
2347 CERT_FIND_PROP_ONLY_ENHKEY_USAGE_FLAG, &usage, &size);
2348 if (!ret && GetLastError() == ERROR_MORE_DATA)
2350 PCERT_ENHKEY_USAGE pUsage = CryptMemAlloc(size);
2352 if (pUsage)
2354 ret = CertGetEnhancedKeyUsage(pCertContext,
2355 CERT_FIND_PROP_ONLY_ENHKEY_USAGE_FLAG, pUsage, &size);
2356 if (ret)
2358 if (pUsage->cUsageIdentifier)
2360 DWORD i;
2361 BOOL found = FALSE;
2363 for (i = 0; i < pUsage->cUsageIdentifier; i++)
2365 if (!strcmp(pUsage->rgpszUsageIdentifier[i],
2366 pszUsageIdentifier))
2367 found = TRUE;
2368 if (found && i < pUsage->cUsageIdentifier - 1)
2369 pUsage->rgpszUsageIdentifier[i] =
2370 pUsage->rgpszUsageIdentifier[i + 1];
2372 pUsage->cUsageIdentifier--;
2373 /* Remove the usage if it's empty */
2374 if (pUsage->cUsageIdentifier)
2375 ret = CertSetEnhancedKeyUsage(pCertContext, pUsage);
2376 else
2377 ret = CertSetEnhancedKeyUsage(pCertContext, NULL);
2380 CryptMemFree(pUsage);
2382 else
2383 ret = FALSE;
2385 else
2387 /* it fit in an empty usage, therefore there's nothing to remove */
2388 ret = TRUE;
2390 return ret;
2393 struct BitField
2395 DWORD cIndexes;
2396 DWORD *indexes;
2399 #define BITS_PER_DWORD (sizeof(DWORD) * 8)
2401 static void CRYPT_SetBitInField(struct BitField *field, DWORD bit)
2403 DWORD indexIndex = bit / BITS_PER_DWORD;
2405 if (indexIndex + 1 > field->cIndexes)
2407 if (field->cIndexes)
2408 field->indexes = CryptMemRealloc(field->indexes,
2409 (indexIndex + 1) * sizeof(DWORD));
2410 else
2411 field->indexes = CryptMemAlloc(sizeof(DWORD));
2412 if (field->indexes)
2414 field->indexes[indexIndex] = 0;
2415 field->cIndexes = indexIndex + 1;
2418 if (field->indexes)
2419 field->indexes[indexIndex] |= 1 << (bit % BITS_PER_DWORD);
2422 static BOOL CRYPT_IsBitInFieldSet(struct BitField *field, DWORD bit)
2424 BOOL set = FALSE;
2425 DWORD indexIndex = bit / BITS_PER_DWORD;
2427 assert(field->cIndexes);
2428 set = field->indexes[indexIndex] & (1 << (bit % BITS_PER_DWORD));
2429 return set;
2432 BOOL WINAPI CertGetValidUsages(DWORD cCerts, PCCERT_CONTEXT *rghCerts,
2433 int *cNumOIDs, LPSTR *rghOIDs, DWORD *pcbOIDs)
2435 BOOL ret = TRUE;
2436 DWORD i, cbOIDs = 0;
2437 BOOL allUsagesValid = TRUE;
2438 CERT_ENHKEY_USAGE validUsages = { 0, NULL };
2440 TRACE("(%d, %p, %d, %p, %d)\n", cCerts, rghCerts, *cNumOIDs,
2441 rghOIDs, *pcbOIDs);
2443 for (i = 0; i < cCerts; i++)
2445 CERT_ENHKEY_USAGE usage;
2446 DWORD size = sizeof(usage);
2448 ret = CertGetEnhancedKeyUsage(rghCerts[i], 0, &usage, &size);
2449 /* Success is deliberately ignored: it implies all usages are valid */
2450 if (!ret && GetLastError() == ERROR_MORE_DATA)
2452 PCERT_ENHKEY_USAGE pUsage = CryptMemAlloc(size);
2454 allUsagesValid = FALSE;
2455 if (pUsage)
2457 ret = CertGetEnhancedKeyUsage(rghCerts[i], 0, pUsage, &size);
2458 if (ret)
2460 if (!validUsages.cUsageIdentifier)
2462 DWORD j;
2464 cbOIDs = pUsage->cUsageIdentifier * sizeof(LPSTR);
2465 validUsages.cUsageIdentifier = pUsage->cUsageIdentifier;
2466 for (j = 0; j < validUsages.cUsageIdentifier; j++)
2467 cbOIDs += lstrlenA(pUsage->rgpszUsageIdentifier[j])
2468 + 1;
2469 validUsages.rgpszUsageIdentifier =
2470 CryptMemAlloc(cbOIDs);
2471 if (validUsages.rgpszUsageIdentifier)
2473 LPSTR nextOID = (LPSTR)
2474 ((LPBYTE)validUsages.rgpszUsageIdentifier +
2475 validUsages.cUsageIdentifier * sizeof(LPSTR));
2477 for (j = 0; j < validUsages.cUsageIdentifier; j++)
2479 validUsages.rgpszUsageIdentifier[j] = nextOID;
2480 lstrcpyA(validUsages.rgpszUsageIdentifier[j],
2481 pUsage->rgpszUsageIdentifier[j]);
2482 nextOID += lstrlenA(nextOID) + 1;
2486 else
2488 struct BitField validIndexes = { 0, NULL };
2489 DWORD j, k, numRemoved = 0;
2491 /* Merge: build a bitmap of all the indexes of
2492 * validUsages.rgpszUsageIdentifier that are in pUsage.
2494 for (j = 0; j < pUsage->cUsageIdentifier; j++)
2496 for (k = 0; k < validUsages.cUsageIdentifier; k++)
2498 if (!strcmp(pUsage->rgpszUsageIdentifier[j],
2499 validUsages.rgpszUsageIdentifier[k]))
2501 CRYPT_SetBitInField(&validIndexes, k);
2502 break;
2506 /* Merge by removing from validUsages those that are
2507 * not in the bitmap.
2509 for (j = 0; j < validUsages.cUsageIdentifier; j++)
2511 if (!CRYPT_IsBitInFieldSet(&validIndexes, j))
2513 if (j < validUsages.cUsageIdentifier - 1)
2515 memmove(&validUsages.rgpszUsageIdentifier[j],
2516 &validUsages.rgpszUsageIdentifier[j +
2517 numRemoved + 1],
2518 (validUsages.cUsageIdentifier - numRemoved
2519 - j - 1) * sizeof(LPSTR));
2520 cbOIDs -= lstrlenA(
2521 validUsages.rgpszUsageIdentifier[j]) + 1 +
2522 sizeof(LPSTR);
2523 validUsages.cUsageIdentifier--;
2524 numRemoved++;
2526 else
2527 validUsages.cUsageIdentifier--;
2530 CryptMemFree(validIndexes.indexes);
2533 CryptMemFree(pUsage);
2537 ret = TRUE;
2538 if (allUsagesValid)
2540 *cNumOIDs = -1;
2541 *pcbOIDs = 0;
2543 else
2545 *cNumOIDs = validUsages.cUsageIdentifier;
2546 if (!rghOIDs)
2547 *pcbOIDs = cbOIDs;
2548 else if (*pcbOIDs < cbOIDs)
2550 *pcbOIDs = cbOIDs;
2551 SetLastError(ERROR_MORE_DATA);
2552 ret = FALSE;
2554 else
2556 LPSTR nextOID = (LPSTR)((LPBYTE)rghOIDs +
2557 validUsages.cUsageIdentifier * sizeof(LPSTR));
2559 *pcbOIDs = cbOIDs;
2560 for (i = 0; i < validUsages.cUsageIdentifier; i++)
2562 rghOIDs[i] = nextOID;
2563 lstrcpyA(nextOID, validUsages.rgpszUsageIdentifier[i]);
2564 nextOID += lstrlenA(nextOID) + 1;
2568 CryptMemFree(validUsages.rgpszUsageIdentifier);
2569 TRACE("cNumOIDs: %d\n", *cNumOIDs);
2570 TRACE("returning %d\n", ret);
2571 return ret;
2574 /* Sets the CERT_KEY_PROV_INFO_PROP_ID property of context from pInfo, or, if
2575 * pInfo is NULL, from the attributes of hProv.
2577 static void CertContext_SetKeyProvInfo(PCCERT_CONTEXT context,
2578 const CRYPT_KEY_PROV_INFO *pInfo, HCRYPTPROV hProv)
2580 CRYPT_KEY_PROV_INFO info = { 0 };
2581 BOOL ret;
2583 if (!pInfo)
2585 DWORD size;
2586 int len;
2588 ret = CryptGetProvParam(hProv, PP_CONTAINER, NULL, &size, 0);
2589 if (ret)
2591 LPSTR szContainer = CryptMemAlloc(size);
2593 if (szContainer)
2595 ret = CryptGetProvParam(hProv, PP_CONTAINER,
2596 (BYTE *)szContainer, &size, 0);
2597 if (ret)
2599 len = MultiByteToWideChar(CP_ACP, 0, szContainer, -1,
2600 NULL, 0);
2601 if (len)
2603 info.pwszContainerName = CryptMemAlloc(len *
2604 sizeof(WCHAR));
2605 len = MultiByteToWideChar(CP_ACP, 0, szContainer, -1,
2606 info.pwszContainerName, len);
2609 CryptMemFree(szContainer);
2612 ret = CryptGetProvParam(hProv, PP_NAME, NULL, &size, 0);
2613 if (ret)
2615 LPSTR szProvider = CryptMemAlloc(size);
2617 if (szProvider)
2619 ret = CryptGetProvParam(hProv, PP_NAME, (BYTE *)szProvider,
2620 &size, 0);
2621 if (ret)
2623 len = MultiByteToWideChar(CP_ACP, 0, szProvider, -1,
2624 NULL, 0);
2625 if (len)
2627 info.pwszProvName = CryptMemAlloc(len *
2628 sizeof(WCHAR));
2629 len = MultiByteToWideChar(CP_ACP, 0, szProvider, -1,
2630 info.pwszProvName, len);
2633 CryptMemFree(szProvider);
2636 size = sizeof(info.dwKeySpec);
2637 /* in case no CRYPT_KEY_PROV_INFO given,
2638 * we always use AT_SIGNATURE key spec
2640 info.dwKeySpec = AT_SIGNATURE;
2641 size = sizeof(info.dwProvType);
2642 ret = CryptGetProvParam(hProv, PP_PROVTYPE, (LPBYTE)&info.dwProvType,
2643 &size, 0);
2644 if (!ret)
2645 info.dwProvType = PROV_RSA_FULL;
2646 pInfo = &info;
2649 ret = CertSetCertificateContextProperty(context, CERT_KEY_PROV_INFO_PROP_ID,
2650 0, pInfo);
2652 if (pInfo == &info)
2654 CryptMemFree(info.pwszContainerName);
2655 CryptMemFree(info.pwszProvName);
2659 /* Creates a signed certificate context from the unsigned, encoded certificate
2660 * in blob, using the crypto provider hProv and the signature algorithm sigAlgo.
2662 static PCCERT_CONTEXT CRYPT_CreateSignedCert(const CRYPT_DER_BLOB *blob,
2663 HCRYPTPROV hProv, DWORD dwKeySpec, PCRYPT_ALGORITHM_IDENTIFIER sigAlgo)
2665 PCCERT_CONTEXT context = NULL;
2666 BOOL ret;
2667 DWORD sigSize = 0;
2669 ret = CryptSignCertificate(hProv, dwKeySpec, X509_ASN_ENCODING,
2670 blob->pbData, blob->cbData, sigAlgo, NULL, NULL, &sigSize);
2671 if (ret)
2673 LPBYTE sig = CryptMemAlloc(sigSize);
2675 ret = CryptSignCertificate(hProv, dwKeySpec, X509_ASN_ENCODING,
2676 blob->pbData, blob->cbData, sigAlgo, NULL, sig, &sigSize);
2677 if (ret)
2679 CERT_SIGNED_CONTENT_INFO signedInfo;
2680 BYTE *encodedSignedCert = NULL;
2681 DWORD encodedSignedCertSize = 0;
2683 signedInfo.ToBeSigned.cbData = blob->cbData;
2684 signedInfo.ToBeSigned.pbData = blob->pbData;
2685 memcpy(&signedInfo.SignatureAlgorithm, sigAlgo,
2686 sizeof(signedInfo.SignatureAlgorithm));
2687 signedInfo.Signature.cbData = sigSize;
2688 signedInfo.Signature.pbData = sig;
2689 signedInfo.Signature.cUnusedBits = 0;
2690 ret = CryptEncodeObjectEx(X509_ASN_ENCODING, X509_CERT,
2691 &signedInfo, CRYPT_ENCODE_ALLOC_FLAG, NULL,
2692 &encodedSignedCert, &encodedSignedCertSize);
2693 if (ret)
2695 context = CertCreateCertificateContext(X509_ASN_ENCODING,
2696 encodedSignedCert, encodedSignedCertSize);
2697 LocalFree(encodedSignedCert);
2700 CryptMemFree(sig);
2702 return context;
2705 /* Copies data from the parameters into info, where:
2706 * pSerialNumber: The serial number. Must not be NULL.
2707 * pSubjectIssuerBlob: Specifies both the subject and issuer for info.
2708 * Must not be NULL
2709 * pSignatureAlgorithm: Optional.
2710 * pStartTime: The starting time of the certificate. If NULL, the current
2711 * system time is used.
2712 * pEndTime: The ending time of the certificate. If NULL, one year past the
2713 * starting time is used.
2714 * pubKey: The public key of the certificate. Must not be NULL.
2715 * pExtensions: Extensions to be included with the certificate. Optional.
2717 static void CRYPT_MakeCertInfo(PCERT_INFO info, const CRYPT_DATA_BLOB *pSerialNumber,
2718 const CERT_NAME_BLOB *pSubjectIssuerBlob,
2719 const CRYPT_ALGORITHM_IDENTIFIER *pSignatureAlgorithm, const SYSTEMTIME *pStartTime,
2720 const SYSTEMTIME *pEndTime, const CERT_PUBLIC_KEY_INFO *pubKey,
2721 const CERT_EXTENSIONS *pExtensions)
2723 static CHAR oid[] = szOID_RSA_SHA1RSA;
2725 assert(info);
2726 assert(pSerialNumber);
2727 assert(pSubjectIssuerBlob);
2728 assert(pubKey);
2730 info->dwVersion = CERT_V3;
2731 info->SerialNumber.cbData = pSerialNumber->cbData;
2732 info->SerialNumber.pbData = pSerialNumber->pbData;
2733 if (pSignatureAlgorithm)
2734 memcpy(&info->SignatureAlgorithm, pSignatureAlgorithm,
2735 sizeof(info->SignatureAlgorithm));
2736 else
2738 info->SignatureAlgorithm.pszObjId = oid;
2739 info->SignatureAlgorithm.Parameters.cbData = 0;
2740 info->SignatureAlgorithm.Parameters.pbData = NULL;
2742 info->Issuer.cbData = pSubjectIssuerBlob->cbData;
2743 info->Issuer.pbData = pSubjectIssuerBlob->pbData;
2744 if (pStartTime)
2745 SystemTimeToFileTime(pStartTime, &info->NotBefore);
2746 else
2747 GetSystemTimeAsFileTime(&info->NotBefore);
2748 if (pEndTime)
2749 SystemTimeToFileTime(pEndTime, &info->NotAfter);
2750 else
2752 SYSTEMTIME endTime;
2754 if (FileTimeToSystemTime(&info->NotBefore, &endTime))
2756 endTime.wYear++;
2757 SystemTimeToFileTime(&endTime, &info->NotAfter);
2760 info->Subject.cbData = pSubjectIssuerBlob->cbData;
2761 info->Subject.pbData = pSubjectIssuerBlob->pbData;
2762 memcpy(&info->SubjectPublicKeyInfo, pubKey,
2763 sizeof(info->SubjectPublicKeyInfo));
2764 if (pExtensions)
2766 info->cExtension = pExtensions->cExtension;
2767 info->rgExtension = pExtensions->rgExtension;
2769 else
2771 info->cExtension = 0;
2772 info->rgExtension = NULL;
2776 typedef RPC_STATUS (RPC_ENTRY *UuidCreateFunc)(UUID *);
2777 typedef RPC_STATUS (RPC_ENTRY *UuidToStringFunc)(UUID *, unsigned char **);
2778 typedef RPC_STATUS (RPC_ENTRY *RpcStringFreeFunc)(unsigned char **);
2780 static HCRYPTPROV CRYPT_CreateKeyProv(void)
2782 HCRYPTPROV hProv = 0;
2783 HMODULE rpcrt = LoadLibraryA("rpcrt4");
2785 if (rpcrt)
2787 UuidCreateFunc uuidCreate = (UuidCreateFunc)GetProcAddress(rpcrt,
2788 "UuidCreate");
2789 UuidToStringFunc uuidToString = (UuidToStringFunc)GetProcAddress(rpcrt,
2790 "UuidToStringA");
2791 RpcStringFreeFunc rpcStringFree = (RpcStringFreeFunc)GetProcAddress(
2792 rpcrt, "RpcStringFreeA");
2794 if (uuidCreate && uuidToString && rpcStringFree)
2796 UUID uuid;
2797 RPC_STATUS status = uuidCreate(&uuid);
2799 if (status == RPC_S_OK || status == RPC_S_UUID_LOCAL_ONLY)
2801 unsigned char *uuidStr;
2803 status = uuidToString(&uuid, &uuidStr);
2804 if (status == RPC_S_OK)
2806 BOOL ret = CryptAcquireContextA(&hProv, (LPCSTR)uuidStr,
2807 MS_DEF_PROV_A, PROV_RSA_FULL, CRYPT_NEWKEYSET);
2809 if (ret)
2811 HCRYPTKEY key;
2813 ret = CryptGenKey(hProv, AT_SIGNATURE, 0, &key);
2814 if (ret)
2815 CryptDestroyKey(key);
2817 rpcStringFree(&uuidStr);
2821 FreeLibrary(rpcrt);
2823 return hProv;
2826 PCCERT_CONTEXT WINAPI CertCreateSelfSignCertificate(HCRYPTPROV_OR_NCRYPT_KEY_HANDLE hProv,
2827 PCERT_NAME_BLOB pSubjectIssuerBlob, DWORD dwFlags,
2828 PCRYPT_KEY_PROV_INFO pKeyProvInfo,
2829 PCRYPT_ALGORITHM_IDENTIFIER pSignatureAlgorithm, PSYSTEMTIME pStartTime,
2830 PSYSTEMTIME pEndTime, PCERT_EXTENSIONS pExtensions)
2832 PCCERT_CONTEXT context = NULL;
2833 BOOL ret, releaseContext = FALSE;
2834 PCERT_PUBLIC_KEY_INFO pubKey = NULL;
2835 DWORD pubKeySize = 0,dwKeySpec = AT_SIGNATURE;
2837 TRACE("(%08lx, %p, %08x, %p, %p, %p, %p, %p)\n", hProv,
2838 pSubjectIssuerBlob, dwFlags, pKeyProvInfo, pSignatureAlgorithm, pStartTime,
2839 pExtensions, pExtensions);
2841 if(!pSubjectIssuerBlob)
2843 SetLastError(ERROR_INVALID_PARAMETER);
2844 return NULL;
2847 if (!hProv)
2849 if (!pKeyProvInfo)
2851 hProv = CRYPT_CreateKeyProv();
2852 releaseContext = TRUE;
2854 else if (pKeyProvInfo->dwFlags & CERT_SET_KEY_PROV_HANDLE_PROP_ID)
2856 SetLastError(NTE_BAD_FLAGS);
2857 return NULL;
2859 else
2861 HCRYPTKEY hKey = 0;
2862 /* acquire the context using the given information*/
2863 ret = CryptAcquireContextW(&hProv,pKeyProvInfo->pwszContainerName,
2864 pKeyProvInfo->pwszProvName,pKeyProvInfo->dwProvType,
2865 pKeyProvInfo->dwFlags);
2866 if (!ret)
2868 if(GetLastError() != NTE_BAD_KEYSET)
2869 return NULL;
2870 /* create the key set */
2871 ret = CryptAcquireContextW(&hProv,pKeyProvInfo->pwszContainerName,
2872 pKeyProvInfo->pwszProvName,pKeyProvInfo->dwProvType,
2873 pKeyProvInfo->dwFlags|CRYPT_NEWKEYSET);
2874 if (!ret)
2875 return NULL;
2877 dwKeySpec = pKeyProvInfo->dwKeySpec;
2878 /* check if the key is here */
2879 ret = CryptGetUserKey(hProv,dwKeySpec,&hKey);
2880 if(!ret)
2882 if (NTE_NO_KEY == GetLastError())
2883 { /* generate the key */
2884 ret = CryptGenKey(hProv,dwKeySpec,0,&hKey);
2886 if (!ret)
2888 CryptReleaseContext(hProv,0);
2889 SetLastError(NTE_BAD_KEYSET);
2890 return NULL;
2893 CryptDestroyKey(hKey);
2894 releaseContext = TRUE;
2897 else if (pKeyProvInfo)
2899 SetLastError(ERROR_INVALID_PARAMETER);
2900 return NULL;
2903 CryptExportPublicKeyInfo(hProv, dwKeySpec, X509_ASN_ENCODING, NULL,
2904 &pubKeySize);
2905 pubKey = CryptMemAlloc(pubKeySize);
2906 if (pubKey)
2908 ret = CryptExportPublicKeyInfo(hProv, dwKeySpec, X509_ASN_ENCODING,
2909 pubKey, &pubKeySize);
2910 if (ret)
2912 CERT_INFO info = { 0 };
2913 CRYPT_DER_BLOB blob = { 0, NULL };
2914 BYTE serial[16];
2915 CRYPT_DATA_BLOB serialBlob = { sizeof(serial), serial };
2917 CryptGenRandom(hProv, sizeof(serial), serial);
2918 CRYPT_MakeCertInfo(&info, &serialBlob, pSubjectIssuerBlob,
2919 pSignatureAlgorithm, pStartTime, pEndTime, pubKey, pExtensions);
2920 ret = CryptEncodeObjectEx(X509_ASN_ENCODING, X509_CERT_TO_BE_SIGNED,
2921 &info, CRYPT_ENCODE_ALLOC_FLAG, NULL, &blob.pbData,
2922 &blob.cbData);
2923 if (ret)
2925 if (!(dwFlags & CERT_CREATE_SELFSIGN_NO_SIGN))
2926 context = CRYPT_CreateSignedCert(&blob, hProv,dwKeySpec,
2927 &info.SignatureAlgorithm);
2928 else
2929 context = CertCreateCertificateContext(X509_ASN_ENCODING,
2930 blob.pbData, blob.cbData);
2931 if (context && !(dwFlags & CERT_CREATE_SELFSIGN_NO_KEY_INFO))
2932 CertContext_SetKeyProvInfo(context, pKeyProvInfo, hProv);
2933 LocalFree(blob.pbData);
2936 CryptMemFree(pubKey);
2938 if (releaseContext)
2939 CryptReleaseContext(hProv, 0);
2940 return context;
2943 BOOL WINAPI CertVerifyCTLUsage(DWORD dwEncodingType, DWORD dwSubjectType,
2944 void *pvSubject, PCTL_USAGE pSubjectUsage, DWORD dwFlags,
2945 PCTL_VERIFY_USAGE_PARA pVerifyUsagePara,
2946 PCTL_VERIFY_USAGE_STATUS pVerifyUsageStatus)
2948 FIXME("(0x%x, %d, %p, %p, 0x%x, %p, %p): stub\n", dwEncodingType,
2949 dwSubjectType, pvSubject, pSubjectUsage, dwFlags, pVerifyUsagePara,
2950 pVerifyUsageStatus);
2951 SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
2952 return FALSE;