GPU workaround to simulate Out of Memory errors with large textures
[chromium-blink-merge.git] / net / ssl / openssl_platform_key_win.cc
blob479e50b0c4b8ab94e9b67f180b7b5c7686798eba
1 // Copyright 2014 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
5 #include "net/ssl/openssl_platform_key.h"
7 #include <windows.h>
8 #include <NCrypt.h>
10 #include <string.h>
12 #include <algorithm>
13 #include <vector>
15 #include <openssl/bn.h>
16 #include <openssl/digest.h>
17 #include <openssl/ec_key.h>
18 #include <openssl/err.h>
19 #include <openssl/engine.h>
20 #include <openssl/evp.h>
21 #include <openssl/md5.h>
22 #include <openssl/obj_mac.h>
23 #include <openssl/rsa.h>
24 #include <openssl/sha.h>
25 #include <openssl/x509.h>
27 #include "base/debug/debugger.h"
28 #include "base/debug/stack_trace.h"
29 #include "base/lazy_instance.h"
30 #include "base/logging.h"
31 #include "base/memory/scoped_ptr.h"
32 #include "base/profiler/scoped_tracker.h"
33 #include "base/win/windows_version.h"
34 #include "crypto/openssl_util.h"
35 #include "crypto/scoped_capi_types.h"
36 #include "crypto/wincrypt_shim.h"
37 #include "net/base/net_errors.h"
38 #include "net/cert/x509_certificate.h"
39 #include "net/ssl/openssl_ssl_util.h"
40 #include "net/ssl/scoped_openssl_types.h"
42 namespace net {
44 namespace {
46 using NCryptFreeObjectFunc = SECURITY_STATUS(WINAPI*)(NCRYPT_HANDLE);
47 using NCryptSignHashFunc =
48 SECURITY_STATUS(WINAPI*)(NCRYPT_KEY_HANDLE, // hKey
49 VOID*, // pPaddingInfo
50 PBYTE, // pbHashValue
51 DWORD, // cbHashValue
52 PBYTE, // pbSignature
53 DWORD, // cbSignature
54 DWORD*, // pcbResult
55 DWORD); // dwFlags
57 class CNGFunctions {
58 public:
59 CNGFunctions()
60 : ncrypt_free_object_(nullptr),
61 ncrypt_sign_hash_(nullptr) {
62 HMODULE ncrypt = GetModuleHandle(L"ncrypt.dll");
63 if (ncrypt != nullptr) {
64 ncrypt_free_object_ = reinterpret_cast<NCryptFreeObjectFunc>(
65 GetProcAddress(ncrypt, "NCryptFreeObject"));
66 ncrypt_sign_hash_ = reinterpret_cast<NCryptSignHashFunc>(
67 GetProcAddress(ncrypt, "NCryptSignHash"));
71 NCryptFreeObjectFunc ncrypt_free_object() const {
72 return ncrypt_free_object_;
75 NCryptSignHashFunc ncrypt_sign_hash() const { return ncrypt_sign_hash_; }
77 private:
78 NCryptFreeObjectFunc ncrypt_free_object_;
79 NCryptSignHashFunc ncrypt_sign_hash_;
82 base::LazyInstance<CNGFunctions>::Leaky g_cng_functions =
83 LAZY_INSTANCE_INITIALIZER;
85 struct CERT_KEY_CONTEXTDeleter {
86 void operator()(PCERT_KEY_CONTEXT key) {
87 if (key->dwKeySpec == CERT_NCRYPT_KEY_SPEC) {
88 g_cng_functions.Get().ncrypt_free_object()(key->hNCryptKey);
89 } else {
90 CryptReleaseContext(key->hCryptProv, 0);
92 delete key;
96 using ScopedCERT_KEY_CONTEXT =
97 scoped_ptr<CERT_KEY_CONTEXT, CERT_KEY_CONTEXTDeleter>;
99 // KeyExData contains the data that is contained in the EX_DATA of the
100 // RSA and ECDSA objects that are created to wrap Windows system keys.
101 struct KeyExData {
102 KeyExData(ScopedCERT_KEY_CONTEXT key, size_t key_length)
103 : key(key.Pass()), key_length(key_length) {}
105 ScopedCERT_KEY_CONTEXT key;
106 size_t key_length;
109 // ExDataDup is called when one of the RSA or EC_KEY objects is
110 // duplicated. This is not supported and should never happen.
111 int ExDataDup(CRYPTO_EX_DATA* to,
112 const CRYPTO_EX_DATA* from,
113 void** from_d,
114 int idx,
115 long argl,
116 void* argp) {
117 CHECK_EQ((void*)nullptr, *from_d);
118 return 0;
121 // ExDataFree is called when one of the RSA or EC_KEY objects is freed.
122 void ExDataFree(void* parent,
123 void* ptr,
124 CRYPTO_EX_DATA* ex_data,
125 int idx,
126 long argl,
127 void* argp) {
128 KeyExData* data = reinterpret_cast<KeyExData*>(ptr);
129 delete data;
132 extern const RSA_METHOD win_rsa_method;
133 extern const ECDSA_METHOD win_ecdsa_method;
135 // BoringSSLEngine is a BoringSSL ENGINE that implements RSA and ECDSA
136 // by forwarding the requested operations to CAPI or CNG.
137 class BoringSSLEngine {
138 public:
139 BoringSSLEngine()
140 : rsa_index_(RSA_get_ex_new_index(0 /* argl */,
141 nullptr /* argp */,
142 nullptr /* new_func */,
143 ExDataDup,
144 ExDataFree)),
145 ec_key_index_(EC_KEY_get_ex_new_index(0 /* argl */,
146 nullptr /* argp */,
147 nullptr /* new_func */,
148 ExDataDup,
149 ExDataFree)),
150 engine_(ENGINE_new()) {
151 ENGINE_set_RSA_method(engine_, &win_rsa_method, sizeof(win_rsa_method));
152 ENGINE_set_ECDSA_method(engine_, &win_ecdsa_method,
153 sizeof(win_ecdsa_method));
156 int rsa_ex_index() const { return rsa_index_; }
157 int ec_key_ex_index() const { return ec_key_index_; }
159 const ENGINE* engine() const { return engine_; }
161 private:
162 const int rsa_index_;
163 const int ec_key_index_;
164 ENGINE* const engine_;
167 base::LazyInstance<BoringSSLEngine>::Leaky global_boringssl_engine =
168 LAZY_INSTANCE_INITIALIZER;
170 // Signs |in| with |key|, writing the output to |out| and the size to |out_len|.
171 // Although the buffer is preallocated, this calls NCryptSignHash twice. Some
172 // smartcards are buggy and assume the two-call pattern. See
173 // https://crbug.com/470204. Returns true on success and false on error.
174 bool DoNCryptSignHash(NCRYPT_KEY_HANDLE key,
175 void* padding,
176 const BYTE* in,
177 DWORD in_len,
178 BYTE* out,
179 DWORD max_out,
180 DWORD* out_len,
181 DWORD flags) {
182 // Determine the output length.
183 DWORD signature_len;
184 SECURITY_STATUS ncrypt_status = g_cng_functions.Get().ncrypt_sign_hash()(
185 key, padding, const_cast<BYTE*>(in), in_len, nullptr, 0, &signature_len,
186 flags);
187 if (FAILED(ncrypt_status)) {
188 LOG(ERROR) << "NCryptSignHash failed: " << ncrypt_status;
189 return false;
191 // Check |max_out| externally rather than trust the smartcard.
192 if (signature_len == 0 || signature_len > max_out) {
193 LOG(ERROR) << "Bad signature length.";
194 return false;
196 // It is important that |signature_len| already be initialized with the
197 // correct size. Some smartcards are buggy and do not write to it on the
198 // second call.
199 ncrypt_status = g_cng_functions.Get().ncrypt_sign_hash()(
200 key, padding, const_cast<PBYTE>(in), in_len, out, signature_len,
201 &signature_len, flags);
202 if (FAILED(ncrypt_status)) {
203 LOG(ERROR) << "NCryptSignHash failed: " << ncrypt_status;
204 return false;
206 if (signature_len == 0) {
207 LOG(ERROR) << "Bad signature length.";
208 return false;
210 *out_len = signature_len;
211 return true;
214 // Custom RSA_METHOD that uses the platform APIs for signing.
216 const KeyExData* RsaGetExData(const RSA* rsa) {
217 return reinterpret_cast<const KeyExData*>(
218 RSA_get_ex_data(rsa, global_boringssl_engine.Get().rsa_ex_index()));
221 size_t RsaMethodSize(const RSA* rsa) {
222 const KeyExData* ex_data = RsaGetExData(rsa);
223 return (ex_data->key_length + 7) / 8;
226 int RsaMethodSign(int hash_nid,
227 const uint8_t* in,
228 unsigned in_len,
229 uint8_t* out,
230 unsigned* out_len,
231 const RSA* rsa) {
232 // TODO(vadimt): Remove ScopedTracker below once crbug.com/424386 is fixed.
233 tracked_objects::ScopedTracker tracking_profile(
234 FROM_HERE_WITH_EXPLICIT_FUNCTION("424386 RsaMethodSign"));
236 // TODO(davidben): Switch BoringSSL's sign hook to using size_t rather than
237 // unsigned.
238 const KeyExData* ex_data = RsaGetExData(rsa);
239 if (!ex_data) {
240 NOTREACHED();
241 OPENSSL_PUT_ERROR(RSA, RSA_sign, ERR_R_INTERNAL_ERROR);
242 return 0;
245 if (ex_data->key->dwKeySpec == CERT_NCRYPT_KEY_SPEC) {
246 BCRYPT_PKCS1_PADDING_INFO rsa_padding_info;
247 switch (hash_nid) {
248 case NID_md5_sha1:
249 rsa_padding_info.pszAlgId = nullptr;
250 break;
251 case NID_sha1:
252 rsa_padding_info.pszAlgId = BCRYPT_SHA1_ALGORITHM;
253 break;
254 case NID_sha256:
255 rsa_padding_info.pszAlgId = BCRYPT_SHA256_ALGORITHM;
256 break;
257 case NID_sha384:
258 rsa_padding_info.pszAlgId = BCRYPT_SHA384_ALGORITHM;
259 break;
260 case NID_sha512:
261 rsa_padding_info.pszAlgId = BCRYPT_SHA512_ALGORITHM;
262 break;
263 default:
264 OPENSSL_PUT_ERROR(RSA, RSA_sign, RSA_R_UNKNOWN_ALGORITHM_TYPE);
265 return 0;
268 DWORD signature_len;
269 if (!DoNCryptSignHash(ex_data->key->hNCryptKey, &rsa_padding_info, in,
270 in_len, out, RSA_size(rsa), &signature_len,
271 BCRYPT_PAD_PKCS1)) {
272 OpenSSLPutNetError(FROM_HERE, ERR_SSL_CLIENT_AUTH_SIGNATURE_FAILED);
273 return 0;
275 *out_len = signature_len;
276 return 1;
279 ALG_ID hash_alg;
280 switch (hash_nid) {
281 case NID_md5_sha1:
282 hash_alg = CALG_SSL3_SHAMD5;
283 break;
284 case NID_sha1:
285 hash_alg = CALG_SHA1;
286 break;
287 case NID_sha256:
288 hash_alg = CALG_SHA_256;
289 break;
290 case NID_sha384:
291 hash_alg = CALG_SHA_384;
292 break;
293 case NID_sha512:
294 hash_alg = CALG_SHA_512;
295 break;
296 default:
297 OPENSSL_PUT_ERROR(RSA, RSA_sign, RSA_R_UNKNOWN_ALGORITHM_TYPE);
298 return 0;
301 HCRYPTHASH hash;
302 if (!CryptCreateHash(ex_data->key->hCryptProv, hash_alg, 0, 0, &hash)) {
303 PLOG(ERROR) << "CreateCreateHash failed";
304 OpenSSLPutNetError(FROM_HERE, ERR_SSL_CLIENT_AUTH_SIGNATURE_FAILED);
305 return 0;
307 DWORD hash_len;
308 DWORD arg_len = sizeof(hash_len);
309 if (!CryptGetHashParam(hash, HP_HASHSIZE, reinterpret_cast<BYTE*>(&hash_len),
310 &arg_len, 0)) {
311 PLOG(ERROR) << "CryptGetHashParam HP_HASHSIZE failed";
312 OpenSSLPutNetError(FROM_HERE, ERR_SSL_CLIENT_AUTH_SIGNATURE_FAILED);
313 return 0;
315 if (hash_len != in_len) {
316 OpenSSLPutNetError(FROM_HERE, ERR_SSL_CLIENT_AUTH_SIGNATURE_FAILED);
317 return 0;
319 if (!CryptSetHashParam(hash, HP_HASHVAL, const_cast<BYTE*>(in), 0)) {
320 PLOG(ERROR) << "CryptSetHashParam HP_HASHVAL failed";
321 OpenSSLPutNetError(FROM_HERE, ERR_SSL_CLIENT_AUTH_SIGNATURE_FAILED);
322 return 0;
324 DWORD signature_len = RSA_size(rsa);
325 if (!CryptSignHash(hash, ex_data->key->dwKeySpec, nullptr, 0, out,
326 &signature_len)) {
327 PLOG(ERROR) << "CryptSignHash failed";
328 OpenSSLPutNetError(FROM_HERE, ERR_SSL_CLIENT_AUTH_SIGNATURE_FAILED);
329 return 0;
332 /* CryptoAPI signs in little-endian, so reverse it. */
333 std::reverse(out, out + signature_len);
334 *out_len = signature_len;
335 return 1;
338 int RsaMethodEncrypt(RSA* rsa,
339 size_t* out_len,
340 uint8_t* out,
341 size_t max_out,
342 const uint8_t* in,
343 size_t in_len,
344 int padding) {
345 NOTIMPLEMENTED();
346 OPENSSL_PUT_ERROR(RSA, encrypt, RSA_R_UNKNOWN_ALGORITHM_TYPE);
347 return 0;
350 int RsaMethodSignRaw(RSA* rsa,
351 size_t* out_len,
352 uint8_t* out,
353 size_t max_out,
354 const uint8_t* in,
355 size_t in_len,
356 int padding) {
357 NOTIMPLEMENTED();
358 OPENSSL_PUT_ERROR(RSA, encrypt, RSA_R_UNKNOWN_ALGORITHM_TYPE);
359 return 0;
362 int RsaMethodDecrypt(RSA* rsa,
363 size_t* out_len,
364 uint8_t* out,
365 size_t max_out,
366 const uint8_t* in,
367 size_t in_len,
368 int padding) {
369 NOTIMPLEMENTED();
370 OPENSSL_PUT_ERROR(RSA, decrypt, RSA_R_UNKNOWN_ALGORITHM_TYPE);
371 return 0;
374 int RsaMethodVerifyRaw(RSA* rsa,
375 size_t* out_len,
376 uint8_t* out,
377 size_t max_out,
378 const uint8_t* in,
379 size_t in_len,
380 int padding) {
381 NOTIMPLEMENTED();
382 OPENSSL_PUT_ERROR(RSA, verify_raw, RSA_R_UNKNOWN_ALGORITHM_TYPE);
383 return 0;
386 int RsaMethodSupportsDigest(const RSA* rsa, const EVP_MD* md) {
387 const KeyExData* ex_data = RsaGetExData(rsa);
388 if (!ex_data) {
389 NOTREACHED();
390 return 0;
393 int hash_nid = EVP_MD_type(md);
394 if (ex_data->key->dwKeySpec == CERT_NCRYPT_KEY_SPEC) {
395 // Only hashes which appear in RsaSignPKCS1 are supported.
396 if (hash_nid != NID_sha1 && hash_nid != NID_sha256 &&
397 hash_nid != NID_sha384 && hash_nid != NID_sha512) {
398 return 0;
401 // If the key is a 1024-bit RSA, assume conservatively that it may only be
402 // able to sign SHA-1 hashes. This is the case for older Estonian ID cards
403 // that have 1024-bit RSA keys.
405 // CNG does provide NCryptIsAlgSupported and NCryptEnumAlgorithms functions,
406 // however they seem to both return NTE_NOT_SUPPORTED when querying the
407 // NCRYPT_PROV_HANDLE at the key's NCRYPT_PROVIDER_HANDLE_PROPERTY.
408 if (ex_data->key_length <= 1024 && hash_nid != NID_sha1)
409 return 0;
411 return 1;
412 } else {
413 // If the key is in CAPI, assume conservatively that the CAPI service
414 // provider may only be able to sign SHA-1 hashes.
415 return hash_nid == NID_sha1;
419 const RSA_METHOD win_rsa_method = {
421 0, // references
422 1, // is_static
424 nullptr, // app_data
426 nullptr, // init
427 nullptr, // finish
428 RsaMethodSize,
429 RsaMethodSign,
430 nullptr, // verify
431 RsaMethodEncrypt,
432 RsaMethodSignRaw,
433 RsaMethodDecrypt,
434 RsaMethodVerifyRaw,
435 nullptr, // private_transform
436 nullptr, // mod_exp
437 nullptr, // bn_mod_exp
438 RSA_FLAG_OPAQUE,
439 nullptr, // keygen
440 RsaMethodSupportsDigest,
443 // Custom ECDSA_METHOD that uses the platform APIs.
444 // Note that for now, only signing through ECDSA_sign() is really supported.
445 // all other method pointers are either stubs returning errors, or no-ops.
447 const KeyExData* EcKeyGetExData(const EC_KEY* ec_key) {
448 return reinterpret_cast<const KeyExData*>(EC_KEY_get_ex_data(
449 ec_key, global_boringssl_engine.Get().ec_key_ex_index()));
452 size_t EcdsaMethodGroupOrderSize(const EC_KEY* ec_key) {
453 const KeyExData* ex_data = EcKeyGetExData(ec_key);
454 // key_length is the size of the group order for EC keys.
455 return (ex_data->key_length + 7) / 8;
458 int EcdsaMethodSign(const uint8_t* digest,
459 size_t digest_len,
460 uint8_t* out_sig,
461 unsigned int* out_sig_len,
462 EC_KEY* ec_key) {
463 // TODO(vadimt): Remove ScopedTracker below once crbug.com/424386 is fixed.
464 tracked_objects::ScopedTracker tracking_profile(
465 FROM_HERE_WITH_EXPLICIT_FUNCTION("424386 EcdsaMethodSign"));
467 const KeyExData* ex_data = EcKeyGetExData(ec_key);
468 // Only CNG supports ECDSA.
469 if (!ex_data || ex_data->key->dwKeySpec != CERT_NCRYPT_KEY_SPEC) {
470 NOTREACHED();
471 OPENSSL_PUT_ERROR(RSA, sign_raw, ERR_R_INTERNAL_ERROR);
472 return 0;
475 // An ECDSA signature is two integers, modulo the order of the group.
476 size_t order_len = (ex_data->key_length + 7) / 8;
477 if (order_len == 0) {
478 NOTREACHED();
479 OpenSSLPutNetError(FROM_HERE, ERR_SSL_CLIENT_AUTH_SIGNATURE_FAILED);
480 return 0;
482 std::vector<uint8_t> raw_sig(order_len * 2);
484 DWORD signature_len;
485 if (!DoNCryptSignHash(ex_data->key->hNCryptKey, nullptr, digest, digest_len,
486 &raw_sig[0], raw_sig.size(), &signature_len, 0)) {
487 OpenSSLPutNetError(FROM_HERE, ERR_SSL_CLIENT_AUTH_SIGNATURE_FAILED);
488 return 0;
490 if (signature_len != raw_sig.size()) {
491 LOG(ERROR) << "Bad signature length";
492 OpenSSLPutNetError(FROM_HERE, ERR_SSL_CLIENT_AUTH_SIGNATURE_FAILED);
493 return 0;
496 // Convert the RAW ECDSA signature to a DER-encoded ECDSA-Sig-Value.
497 crypto::ScopedECDSA_SIG sig(ECDSA_SIG_new());
498 if (!sig) {
499 OpenSSLPutNetError(FROM_HERE, ERR_SSL_CLIENT_AUTH_SIGNATURE_FAILED);
500 return 0;
502 sig->r = BN_bin2bn(&raw_sig[0], order_len, nullptr);
503 sig->s = BN_bin2bn(&raw_sig[order_len], order_len, nullptr);
504 if (!sig->r || !sig->s) {
505 OpenSSLPutNetError(FROM_HERE, ERR_SSL_CLIENT_AUTH_SIGNATURE_FAILED);
506 return 0;
509 // Ensure the DER-encoded signature fits in the bounds.
510 int len = i2d_ECDSA_SIG(sig.get(), nullptr);
511 if (len < 0 || static_cast<size_t>(len) > ECDSA_size(ec_key)) {
512 OpenSSLPutNetError(FROM_HERE, ERR_SSL_CLIENT_AUTH_SIGNATURE_FAILED);
513 return 0;
516 len = i2d_ECDSA_SIG(sig.get(), &out_sig);
517 if (len < 0) {
518 OpenSSLPutNetError(FROM_HERE, ERR_SSL_CLIENT_AUTH_SIGNATURE_FAILED);
519 return 0;
521 *out_sig_len = len;
522 return 1;
525 int EcdsaMethodVerify(const uint8_t* digest,
526 size_t digest_len,
527 const uint8_t* sig,
528 size_t sig_len,
529 EC_KEY* eckey) {
530 NOTIMPLEMENTED();
531 OPENSSL_PUT_ERROR(ECDSA, ECDSA_do_verify, ECDSA_R_NOT_IMPLEMENTED);
532 return 0;
535 const ECDSA_METHOD win_ecdsa_method = {
537 0, // references
538 1, // is_static
540 nullptr, // app_data
542 nullptr, // init
543 nullptr, // finish
544 EcdsaMethodGroupOrderSize,
545 EcdsaMethodSign,
546 EcdsaMethodVerify,
547 ECDSA_FLAG_OPAQUE,
550 // Determines the key type and length of |certificate|'s public key. The type is
551 // returned as an OpenSSL EVP_PKEY type. The key length for RSA key is the size
552 // of the RSA modulus in bits. For an ECDSA key, it is the number of bits to
553 // represent the group order. It returns true on success and false on failure.
554 bool GetKeyInfo(const X509Certificate* certificate,
555 int* out_type,
556 size_t* out_length) {
557 crypto::OpenSSLErrStackTracer tracker(FROM_HERE);
559 std::string der_encoded;
560 if (!X509Certificate::GetDEREncoded(certificate->os_cert_handle(),
561 &der_encoded))
562 return false;
563 const uint8_t* bytes = reinterpret_cast<const uint8_t*>(der_encoded.data());
564 ScopedX509 x509(d2i_X509(NULL, &bytes, der_encoded.size()));
565 if (!x509)
566 return false;
567 crypto::ScopedEVP_PKEY key(X509_get_pubkey(x509.get()));
568 if (!key)
569 return false;
570 *out_type = EVP_PKEY_id(key.get());
571 *out_length = EVP_PKEY_bits(key.get());
572 return true;
575 crypto::ScopedEVP_PKEY CreateRSAWrapper(ScopedCERT_KEY_CONTEXT key,
576 size_t key_length) {
577 crypto::ScopedRSA rsa(RSA_new_method(global_boringssl_engine.Get().engine()));
578 if (!rsa)
579 return nullptr;
581 RSA_set_ex_data(rsa.get(), global_boringssl_engine.Get().rsa_ex_index(),
582 new KeyExData(key.Pass(), key_length));
584 crypto::ScopedEVP_PKEY pkey(EVP_PKEY_new());
585 if (!pkey || !EVP_PKEY_set1_RSA(pkey.get(), rsa.get()))
586 return nullptr;
587 return pkey.Pass();
590 crypto::ScopedEVP_PKEY CreateECDSAWrapper(ScopedCERT_KEY_CONTEXT key,
591 size_t key_length) {
592 crypto::ScopedEC_KEY ec_key(
593 EC_KEY_new_method(global_boringssl_engine.Get().engine()));
594 if (!ec_key)
595 return nullptr;
597 EC_KEY_set_ex_data(ec_key.get(),
598 global_boringssl_engine.Get().ec_key_ex_index(),
599 new KeyExData(key.Pass(), key_length));
601 crypto::ScopedEVP_PKEY pkey(EVP_PKEY_new());
602 if (!pkey || !EVP_PKEY_set1_EC_KEY(pkey.get(), ec_key.get()))
603 return nullptr;
605 return pkey.Pass();
608 } // namespace
610 crypto::ScopedEVP_PKEY FetchClientCertPrivateKey(
611 const X509Certificate* certificate) {
612 PCCERT_CONTEXT cert_context = certificate->os_cert_handle();
614 HCRYPTPROV_OR_NCRYPT_KEY_HANDLE crypt_prov = 0;
615 DWORD key_spec = 0;
616 BOOL must_free = FALSE;
617 DWORD flags = 0;
618 if (base::win::GetVersion() >= base::win::VERSION_VISTA)
619 flags |= CRYPT_ACQUIRE_PREFER_NCRYPT_KEY_FLAG;
621 if (!CryptAcquireCertificatePrivateKey(cert_context, flags, nullptr,
622 &crypt_prov, &key_spec, &must_free)) {
623 PLOG(WARNING) << "Could not acquire private key";
624 return nullptr;
627 // Should never get a cached handle back - ownership must always be
628 // transferred.
629 CHECK_EQ(must_free, TRUE);
630 ScopedCERT_KEY_CONTEXT key(new CERT_KEY_CONTEXT);
631 key->dwKeySpec = key_spec;
632 key->hCryptProv = crypt_prov;
634 // Rather than query the private key for metadata, extract the public key from
635 // the certificate without using Windows APIs. CAPI and CNG do not
636 // consistently work depending on the system. See https://crbug.com/468345.
637 int key_type;
638 size_t key_length;
639 if (!GetKeyInfo(certificate, &key_type, &key_length))
640 return nullptr;
642 switch (key_type) {
643 case EVP_PKEY_RSA:
644 return CreateRSAWrapper(key.Pass(), key_length);
645 case EVP_PKEY_EC:
646 return CreateECDSAWrapper(key.Pass(), key_length);
647 default:
648 return nullptr;
652 } // namespace net