Roll src/third_party/WebKit 8b42d1d:744641d (svn 186770:186771)
[chromium-blink-merge.git] / net / ssl / openssl_platform_key_win.cc
blobc625bff3b4202f0f6b1dd0e0e0a9a3f17b8210c8
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>
26 #include "base/debug/debugger.h"
27 #include "base/debug/stack_trace.h"
28 #include "base/lazy_instance.h"
29 #include "base/logging.h"
30 #include "base/memory/scoped_ptr.h"
31 #include "base/win/windows_version.h"
32 #include "crypto/scoped_capi_types.h"
33 #include "crypto/wincrypt_shim.h"
34 #include "net/base/net_errors.h"
35 #include "net/cert/x509_certificate.h"
36 #include "net/ssl/openssl_ssl_util.h"
38 namespace net {
40 namespace {
42 using NCryptFreeObjectFunc = SECURITY_STATUS(WINAPI*)(NCRYPT_HANDLE);
43 using NCryptGetPropertyFunc =
44 SECURITY_STATUS(WINAPI*)(NCRYPT_HANDLE, // hObject
45 LPCWSTR, // pszProperty
46 PBYTE, // pbOutput
47 DWORD, // cbOutput
48 DWORD*, // pcbResult
49 DWORD); // dwFlags
50 using NCryptSignHashFunc =
51 SECURITY_STATUS(WINAPI*)(NCRYPT_KEY_HANDLE, // hKey
52 VOID*, // pPaddingInfo
53 PBYTE, // pbHashValue
54 DWORD, // cbHashValue
55 PBYTE, // pbSignature
56 DWORD, // cbSignature
57 DWORD*, // pcbResult
58 DWORD); // dwFlags
60 class CNGFunctions {
61 public:
62 CNGFunctions()
63 : ncrypt_free_object_(nullptr),
64 ncrypt_get_property_(nullptr),
65 ncrypt_sign_hash_(nullptr) {
66 HMODULE ncrypt = GetModuleHandle(L"ncrypt.dll");
67 if (ncrypt != nullptr) {
68 ncrypt_free_object_ = reinterpret_cast<NCryptFreeObjectFunc>(
69 GetProcAddress(ncrypt, "NCryptFreeObject"));
70 ncrypt_get_property_ = reinterpret_cast<NCryptGetPropertyFunc>(
71 GetProcAddress(ncrypt, "NCryptGetProperty"));
72 ncrypt_sign_hash_ = reinterpret_cast<NCryptSignHashFunc>(
73 GetProcAddress(ncrypt, "NCryptSignHash"));
77 NCryptFreeObjectFunc ncrypt_free_object() const {
78 return ncrypt_free_object_;
81 NCryptGetPropertyFunc ncrypt_get_property() const {
82 return ncrypt_get_property_;
85 NCryptSignHashFunc ncrypt_sign_hash() const { return ncrypt_sign_hash_; }
87 private:
88 NCryptFreeObjectFunc ncrypt_free_object_;
89 NCryptGetPropertyFunc ncrypt_get_property_;
90 NCryptSignHashFunc ncrypt_sign_hash_;
93 base::LazyInstance<CNGFunctions>::Leaky g_cng_functions =
94 LAZY_INSTANCE_INITIALIZER;
96 struct CERT_KEY_CONTEXTDeleter {
97 void operator()(PCERT_KEY_CONTEXT key) {
98 if (key->dwKeySpec == CERT_NCRYPT_KEY_SPEC) {
99 g_cng_functions.Get().ncrypt_free_object()(key->hNCryptKey);
100 } else {
101 CryptReleaseContext(key->hCryptProv, 0);
103 delete key;
107 using ScopedCERT_KEY_CONTEXT =
108 scoped_ptr<CERT_KEY_CONTEXT, CERT_KEY_CONTEXTDeleter>;
110 // KeyExData contains the data that is contained in the EX_DATA of the
111 // RSA and ECDSA objects that are created to wrap Windows system keys.
112 struct KeyExData {
113 KeyExData(ScopedCERT_KEY_CONTEXT key, DWORD key_length)
114 : key(key.Pass()), key_length(key_length) {}
116 ScopedCERT_KEY_CONTEXT key;
117 DWORD key_length;
120 // ExDataDup is called when one of the RSA or EC_KEY objects is
121 // duplicated. This is not supported and should never happen.
122 int ExDataDup(CRYPTO_EX_DATA* to,
123 const CRYPTO_EX_DATA* from,
124 void** from_d,
125 int idx,
126 long argl,
127 void* argp) {
128 CHECK_EQ((void*)nullptr, *from_d);
129 return 0;
132 // ExDataFree is called when one of the RSA or EC_KEY objects is freed.
133 void ExDataFree(void* parent,
134 void* ptr,
135 CRYPTO_EX_DATA* ex_data,
136 int idx,
137 long argl,
138 void* argp) {
139 KeyExData* data = reinterpret_cast<KeyExData*>(ptr);
140 delete data;
143 extern const RSA_METHOD win_rsa_method;
144 extern const ECDSA_METHOD win_ecdsa_method;
146 // BoringSSLEngine is a BoringSSL ENGINE that implements RSA and ECDSA
147 // by forwarding the requested operations to CAPI or CNG.
148 class BoringSSLEngine {
149 public:
150 BoringSSLEngine()
151 : rsa_index_(RSA_get_ex_new_index(0 /* argl */,
152 nullptr /* argp */,
153 nullptr /* new_func */,
154 ExDataDup,
155 ExDataFree)),
156 ec_key_index_(EC_KEY_get_ex_new_index(0 /* argl */,
157 nullptr /* argp */,
158 nullptr /* new_func */,
159 ExDataDup,
160 ExDataFree)),
161 engine_(ENGINE_new()) {
162 ENGINE_set_RSA_method(engine_, &win_rsa_method, sizeof(win_rsa_method));
163 ENGINE_set_ECDSA_method(engine_, &win_ecdsa_method,
164 sizeof(win_ecdsa_method));
167 int rsa_ex_index() const { return rsa_index_; }
168 int ec_key_ex_index() const { return ec_key_index_; }
170 const ENGINE* engine() const { return engine_; }
172 private:
173 const int rsa_index_;
174 const int ec_key_index_;
175 ENGINE* const engine_;
178 base::LazyInstance<BoringSSLEngine>::Leaky global_boringssl_engine =
179 LAZY_INSTANCE_INITIALIZER;
181 // Custom RSA_METHOD that uses the platform APIs for signing.
183 const KeyExData* RsaGetExData(const RSA* rsa) {
184 return reinterpret_cast<const KeyExData*>(
185 RSA_get_ex_data(rsa, global_boringssl_engine.Get().rsa_ex_index()));
188 size_t RsaMethodSize(const RSA* rsa) {
189 const KeyExData* ex_data = RsaGetExData(rsa);
190 return (ex_data->key_length + 7) / 8;
193 int RsaMethodSign(int hash_nid,
194 const uint8_t* in,
195 unsigned in_len,
196 uint8_t* out,
197 unsigned* out_len,
198 const RSA* rsa) {
199 // TODO(davidben): Switch BoringSSL's sign hook to using size_t rather than
200 // unsigned.
201 const KeyExData* ex_data = RsaGetExData(rsa);
202 if (!ex_data) {
203 NOTREACHED();
204 OPENSSL_PUT_ERROR(RSA, RSA_sign, ERR_R_INTERNAL_ERROR);
205 return 0;
208 if (ex_data->key->dwKeySpec == CERT_NCRYPT_KEY_SPEC) {
209 BCRYPT_PKCS1_PADDING_INFO rsa_padding_info;
210 switch (hash_nid) {
211 case NID_md5_sha1:
212 rsa_padding_info.pszAlgId = nullptr;
213 break;
214 case NID_sha1:
215 rsa_padding_info.pszAlgId = BCRYPT_SHA1_ALGORITHM;
216 break;
217 case NID_sha256:
218 rsa_padding_info.pszAlgId = BCRYPT_SHA256_ALGORITHM;
219 break;
220 case NID_sha384:
221 rsa_padding_info.pszAlgId = BCRYPT_SHA384_ALGORITHM;
222 break;
223 case NID_sha512:
224 rsa_padding_info.pszAlgId = BCRYPT_SHA512_ALGORITHM;
225 break;
226 default:
227 OPENSSL_PUT_ERROR(RSA, RSA_sign, RSA_R_UNKNOWN_ALGORITHM_TYPE);
228 return 0;
231 DWORD signature_len;
232 SECURITY_STATUS ncrypt_status = g_cng_functions.Get().ncrypt_sign_hash()(
233 ex_data->key->hNCryptKey, &rsa_padding_info, const_cast<PBYTE>(in),
234 in_len, out, RSA_size(rsa), &signature_len, BCRYPT_PAD_PKCS1);
235 if (FAILED(ncrypt_status) || signature_len == 0) {
236 OpenSSLPutNetError(FROM_HERE, ERR_SSL_CLIENT_AUTH_SIGNATURE_FAILED);
237 return 0;
239 *out_len = signature_len;
240 return 1;
243 ALG_ID hash_alg;
244 switch (hash_nid) {
245 case NID_md5_sha1:
246 hash_alg = CALG_SSL3_SHAMD5;
247 break;
248 case NID_sha1:
249 hash_alg = CALG_SHA1;
250 break;
251 case NID_sha256:
252 hash_alg = CALG_SHA_256;
253 break;
254 case NID_sha384:
255 hash_alg = CALG_SHA_384;
256 break;
257 case NID_sha512:
258 hash_alg = CALG_SHA_512;
259 break;
260 default:
261 OPENSSL_PUT_ERROR(RSA, RSA_sign, RSA_R_UNKNOWN_ALGORITHM_TYPE);
262 return 0;
265 HCRYPTHASH hash;
266 if (!CryptCreateHash(ex_data->key->hCryptProv, hash_alg, 0, 0, &hash)) {
267 PLOG(ERROR) << "CreateCreateHash failed";
268 OpenSSLPutNetError(FROM_HERE, ERR_SSL_CLIENT_AUTH_SIGNATURE_FAILED);
269 return 0;
271 DWORD hash_len;
272 DWORD arg_len = sizeof(hash_len);
273 if (!CryptGetHashParam(hash, HP_HASHSIZE, reinterpret_cast<BYTE*>(&hash_len),
274 &arg_len, 0)) {
275 PLOG(ERROR) << "CryptGetHashParam HP_HASHSIZE failed";
276 OpenSSLPutNetError(FROM_HERE, ERR_SSL_CLIENT_AUTH_SIGNATURE_FAILED);
277 return 0;
279 if (hash_len != in_len) {
280 OpenSSLPutNetError(FROM_HERE, ERR_SSL_CLIENT_AUTH_SIGNATURE_FAILED);
281 return 0;
283 if (!CryptSetHashParam(hash, HP_HASHVAL, const_cast<BYTE*>(in), 0)) {
284 PLOG(ERROR) << "CryptSetHashParam HP_HASHVAL failed";
285 OpenSSLPutNetError(FROM_HERE, ERR_SSL_CLIENT_AUTH_SIGNATURE_FAILED);
286 return 0;
288 DWORD signature_len = RSA_size(rsa);
289 if (!CryptSignHash(hash, ex_data->key->dwKeySpec, nullptr, 0, out,
290 &signature_len)) {
291 PLOG(ERROR) << "CryptSignHash failed";
292 OpenSSLPutNetError(FROM_HERE, ERR_SSL_CLIENT_AUTH_SIGNATURE_FAILED);
293 return 0;
296 /* CryptoAPI signs in little-endian, so reverse it. */
297 std::reverse(out, out + signature_len);
298 *out_len = signature_len;
299 return 1;
302 int RsaMethodEncrypt(RSA* rsa,
303 size_t* out_len,
304 uint8_t* out,
305 size_t max_out,
306 const uint8_t* in,
307 size_t in_len,
308 int padding) {
309 NOTIMPLEMENTED();
310 OPENSSL_PUT_ERROR(RSA, encrypt, RSA_R_UNKNOWN_ALGORITHM_TYPE);
311 return 0;
314 int RsaMethodSignRaw(RSA* rsa,
315 size_t* out_len,
316 uint8_t* out,
317 size_t max_out,
318 const uint8_t* in,
319 size_t in_len,
320 int padding) {
321 NOTIMPLEMENTED();
322 OPENSSL_PUT_ERROR(RSA, encrypt, RSA_R_UNKNOWN_ALGORITHM_TYPE);
323 return 0;
326 int RsaMethodDecrypt(RSA* rsa,
327 size_t* out_len,
328 uint8_t* out,
329 size_t max_out,
330 const uint8_t* in,
331 size_t in_len,
332 int padding) {
333 NOTIMPLEMENTED();
334 OPENSSL_PUT_ERROR(RSA, decrypt, RSA_R_UNKNOWN_ALGORITHM_TYPE);
335 return 0;
338 int RsaMethodVerifyRaw(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, verify_raw, RSA_R_UNKNOWN_ALGORITHM_TYPE);
347 return 0;
350 int RsaMethodSupportsDigest(const RSA* rsa, const EVP_MD* md) {
351 const KeyExData* ex_data = RsaGetExData(rsa);
352 if (!ex_data) {
353 NOTREACHED();
354 return 0;
357 int hash_nid = EVP_MD_type(md);
358 if (ex_data->key->dwKeySpec == CERT_NCRYPT_KEY_SPEC) {
359 // Only hashes which appear in RsaSignPKCS1 are supported.
360 if (hash_nid != NID_sha1 && hash_nid != NID_sha256 &&
361 hash_nid != NID_sha384 && hash_nid != NID_sha512) {
362 return 0;
365 // If the key is a 1024-bit RSA, assume conservatively that it may only be
366 // able to sign SHA-1 hashes. This is the case for older Estonian ID cards
367 // that have 1024-bit RSA keys.
369 // CNG does provide NCryptIsAlgSupported and NCryptEnumAlgorithms functions,
370 // however they seem to both return NTE_NOT_SUPPORTED when querying the
371 // NCRYPT_PROV_HANDLE at the key's NCRYPT_PROVIDER_HANDLE_PROPERTY.
372 if (ex_data->key_length <= 1024 && hash_nid != NID_sha1)
373 return 0;
375 return 1;
376 } else {
377 // If the key is in CAPI, assume conservatively that the CAPI service
378 // provider may only be able to sign SHA-1 hashes.
379 return hash_nid == NID_sha1;
383 const RSA_METHOD win_rsa_method = {
385 0, // references
386 1, // is_static
388 nullptr, // app_data
390 nullptr, // init
391 nullptr, // finish
392 RsaMethodSize,
393 RsaMethodSign,
394 nullptr, // verify
395 RsaMethodEncrypt,
396 RsaMethodSignRaw,
397 RsaMethodDecrypt,
398 RsaMethodVerifyRaw,
399 nullptr, // private_transform
400 nullptr, // mod_exp
401 nullptr, // bn_mod_exp
402 RSA_FLAG_OPAQUE,
403 nullptr, // keygen
404 RsaMethodSupportsDigest,
407 // Custom ECDSA_METHOD that uses the platform APIs.
408 // Note that for now, only signing through ECDSA_sign() is really supported.
409 // all other method pointers are either stubs returning errors, or no-ops.
411 const KeyExData* EcKeyGetExData(const EC_KEY* ec_key) {
412 return reinterpret_cast<const KeyExData*>(EC_KEY_get_ex_data(
413 ec_key, global_boringssl_engine.Get().ec_key_ex_index()));
416 size_t EcdsaMethodGroupOrderSize(const EC_KEY* ec_key) {
417 const KeyExData* ex_data = EcKeyGetExData(ec_key);
418 // Windows doesn't distinguish the sizes of the curve's degree (which
419 // determines the size of a point on the curve) and the base point's order
420 // (which determines the size of a scalar). For P-256, P-384, and P-521, these
421 // two sizes are the same.
423 // See
424 // http://msdn.microsoft.com/en-us/library/windows/desktop/aa375520(v=vs.85).aspx
425 // which uses the same length for both.
426 return (ex_data->key_length + 7) / 8;
429 int EcdsaMethodSign(const uint8_t* digest,
430 size_t digest_len,
431 uint8_t* out_sig,
432 unsigned int* out_sig_len,
433 EC_KEY* ec_key) {
434 const KeyExData* ex_data = EcKeyGetExData(ec_key);
435 // Only CNG supports ECDSA.
436 if (!ex_data || ex_data->key->dwKeySpec != CERT_NCRYPT_KEY_SPEC) {
437 NOTREACHED();
438 OPENSSL_PUT_ERROR(RSA, sign_raw, ERR_R_INTERNAL_ERROR);
439 return 0;
442 size_t degree = (ex_data->key_length + 7) / 8;
443 if (degree == 0) {
444 NOTREACHED();
445 OpenSSLPutNetError(FROM_HERE, ERR_SSL_CLIENT_AUTH_SIGNATURE_FAILED);
446 return 0;
448 std::vector<uint8_t> raw_sig(degree * 2);
450 DWORD signature_len;
451 SECURITY_STATUS ncrypt_status = g_cng_functions.Get().ncrypt_sign_hash()(
452 ex_data->key->hNCryptKey, nullptr, const_cast<PBYTE>(digest), digest_len,
453 &raw_sig[0], raw_sig.size(), &signature_len, 0);
454 if (FAILED(ncrypt_status) || signature_len != raw_sig.size()) {
455 OpenSSLPutNetError(FROM_HERE, ERR_SSL_CLIENT_AUTH_SIGNATURE_FAILED);
456 return 0;
459 // Convert the RAW ECDSA signature to a DER-encoded ECDSA-Sig-Value.
460 crypto::ScopedECDSA_SIG sig(ECDSA_SIG_new());
461 if (!sig) {
462 OpenSSLPutNetError(FROM_HERE, ERR_SSL_CLIENT_AUTH_SIGNATURE_FAILED);
463 return 0;
465 sig->r = BN_bin2bn(&raw_sig[0], degree, nullptr);
466 sig->s = BN_bin2bn(&raw_sig[degree], degree, nullptr);
467 if (!sig->r || !sig->s) {
468 OpenSSLPutNetError(FROM_HERE, ERR_SSL_CLIENT_AUTH_SIGNATURE_FAILED);
469 return 0;
472 // Ensure the DER-encoded signature fits in the bounds.
473 int len = i2d_ECDSA_SIG(sig.get(), nullptr);
474 if (len < 0 || static_cast<size_t>(len) > ECDSA_size(ec_key)) {
475 OpenSSLPutNetError(FROM_HERE, ERR_SSL_CLIENT_AUTH_SIGNATURE_FAILED);
476 return 0;
479 len = i2d_ECDSA_SIG(sig.get(), &out_sig);
480 if (len < 0) {
481 OpenSSLPutNetError(FROM_HERE, ERR_SSL_CLIENT_AUTH_SIGNATURE_FAILED);
482 return 0;
484 *out_sig_len = len;
485 return 1;
488 int EcdsaMethodVerify(const uint8_t* digest,
489 size_t digest_len,
490 const uint8_t* sig,
491 size_t sig_len,
492 EC_KEY* eckey) {
493 NOTIMPLEMENTED();
494 OPENSSL_PUT_ERROR(ECDSA, ECDSA_do_verify, ECDSA_R_NOT_IMPLEMENTED);
495 return 0;
498 const ECDSA_METHOD win_ecdsa_method = {
500 0, // references
501 1, // is_static
503 nullptr, // app_data
505 nullptr, // init
506 nullptr, // finish
507 EcdsaMethodGroupOrderSize,
508 EcdsaMethodSign,
509 EcdsaMethodVerify,
510 ECDSA_FLAG_OPAQUE,
513 // Determines the key type and length of |key|. The type is returned as an
514 // OpenSSL EVP_PKEY type. The key length for RSA key is the size of the RSA
515 // modulus in bits. For an ECDSA key, it is the number of bits to represent the
516 // group order. It returns true on success and false on failure.
517 bool GetKeyInfo(PCERT_KEY_CONTEXT key, int* out_type, DWORD* out_length) {
518 if (key->dwKeySpec == CERT_NCRYPT_KEY_SPEC) {
519 DWORD prop_len;
520 SECURITY_STATUS status = g_cng_functions.Get().ncrypt_get_property()(
521 key->hNCryptKey, NCRYPT_ALGORITHM_GROUP_PROPERTY, nullptr, 0, &prop_len,
523 if (FAILED(status) || prop_len == 0 || prop_len % 2 != 0) {
524 LOG(ERROR) << "Could not query CNG key type: " << status;
525 return false;
528 std::vector<BYTE> prop_buf(prop_len);
529 status = g_cng_functions.Get().ncrypt_get_property()(
530 key->hNCryptKey, NCRYPT_ALGORITHM_GROUP_PROPERTY, &prop_buf[0],
531 prop_buf.size(), &prop_len, 0);
532 if (FAILED(status) || prop_len == 0 || prop_len % 2 != 0) {
533 LOG(ERROR) << "Could not query CNG key type: " << status;
534 return false;
537 int type;
538 const wchar_t* alg = reinterpret_cast<const wchar_t*>(&prop_buf[0]);
539 if (wcsncmp(NCRYPT_RSA_ALGORITHM_GROUP, alg, prop_len / 2) == 0) {
540 type = EVP_PKEY_RSA;
541 } else if (wcsncmp(NCRYPT_ECDSA_ALGORITHM_GROUP, alg, prop_len / 2) == 0 ||
542 wcsncmp(NCRYPT_ECDH_ALGORITHM_GROUP, alg, prop_len / 2) == 0) {
543 // Importing an ECDSA key via PKCS #12 seems to label it as ECDH rather
544 // than ECDSA, so also allow ECDH.
545 type = EVP_PKEY_EC;
546 } else {
547 LOG(ERROR) << "Unknown CNG key type: "
548 << std::wstring(alg, wcsnlen(alg, prop_len / 2));
549 return false;
552 DWORD length;
553 prop_len;
554 status = g_cng_functions.Get().ncrypt_get_property()(
555 key->hNCryptKey, NCRYPT_LENGTH_PROPERTY,
556 reinterpret_cast<BYTE*>(&length), sizeof(DWORD), &prop_len, 0);
557 if (FAILED(status)) {
558 LOG(ERROR) << "Could not get CNG key length " << status;
559 return false;
561 DCHECK_EQ(sizeof(DWORD), prop_len);
563 *out_type = type;
564 *out_length = length;
565 return true;
568 crypto::ScopedHCRYPTKEY hcryptkey;
569 if (!CryptGetUserKey(key->hCryptProv, key->dwKeySpec, hcryptkey.receive())) {
570 PLOG(ERROR) << "Could not get CAPI key handle";
571 return false;
574 ALG_ID alg_id;
575 DWORD prop_len = sizeof(alg_id);
576 if (!CryptGetKeyParam(hcryptkey.get(), KP_ALGID,
577 reinterpret_cast<BYTE*>(&alg_id), &prop_len, 0)) {
578 PLOG(ERROR) << "Could not query CAPI key type";
579 return false;
582 if (alg_id != CALG_RSA_SIGN && alg_id != CALG_RSA_KEYX) {
583 LOG(ERROR) << "Unknown CAPI key type: " << alg_id;
584 return false;
587 DWORD length;
588 prop_len = sizeof(DWORD);
589 if (!CryptGetKeyParam(hcryptkey.get(), KP_KEYLEN,
590 reinterpret_cast<BYTE*>(&length), &prop_len, 0)) {
591 PLOG(ERROR) << "Could not get CAPI key length";
592 return false;
594 DCHECK_EQ(sizeof(DWORD), prop_len);
596 *out_type = EVP_PKEY_RSA;
597 *out_length = length;
598 return true;
601 crypto::ScopedEVP_PKEY CreateRSAWrapper(ScopedCERT_KEY_CONTEXT key,
602 DWORD key_length) {
603 crypto::ScopedRSA rsa(RSA_new_method(global_boringssl_engine.Get().engine()));
604 if (!rsa)
605 return nullptr;
607 RSA_set_ex_data(rsa.get(), global_boringssl_engine.Get().rsa_ex_index(),
608 new KeyExData(key.Pass(), key_length));
610 crypto::ScopedEVP_PKEY pkey(EVP_PKEY_new());
611 if (!pkey || !EVP_PKEY_set1_RSA(pkey.get(), rsa.get()))
612 return nullptr;
613 return pkey.Pass();
616 crypto::ScopedEVP_PKEY CreateECDSAWrapper(ScopedCERT_KEY_CONTEXT key,
617 DWORD key_length) {
618 crypto::ScopedEC_KEY ec_key(
619 EC_KEY_new_method(global_boringssl_engine.Get().engine()));
620 if (!ec_key)
621 return nullptr;
623 EC_KEY_set_ex_data(ec_key.get(),
624 global_boringssl_engine.Get().ec_key_ex_index(),
625 new KeyExData(key.Pass(), key_length));
627 crypto::ScopedEVP_PKEY pkey(EVP_PKEY_new());
628 if (!pkey || !EVP_PKEY_set1_EC_KEY(pkey.get(), ec_key.get()))
629 return nullptr;
631 return pkey.Pass();
634 } // namespace
636 crypto::ScopedEVP_PKEY FetchClientCertPrivateKey(
637 const X509Certificate* certificate) {
638 PCCERT_CONTEXT cert_context = certificate->os_cert_handle();
640 HCRYPTPROV_OR_NCRYPT_KEY_HANDLE crypt_prov = 0;
641 DWORD key_spec = 0;
642 BOOL must_free = FALSE;
643 DWORD flags = 0;
644 if (base::win::GetVersion() >= base::win::VERSION_VISTA)
645 flags |= CRYPT_ACQUIRE_PREFER_NCRYPT_KEY_FLAG;
647 if (!CryptAcquireCertificatePrivateKey(cert_context, flags, nullptr,
648 &crypt_prov, &key_spec, &must_free)) {
649 PLOG(WARNING) << "Could not acquire private key";
650 return nullptr;
653 // Should never get a cached handle back - ownership must always be
654 // transferred.
655 CHECK_EQ(must_free, TRUE);
656 ScopedCERT_KEY_CONTEXT key(new CERT_KEY_CONTEXT);
657 key->dwKeySpec = key_spec;
658 key->hCryptProv = crypt_prov;
660 int key_type;
661 DWORD key_length;
662 if (!GetKeyInfo(key.get(), &key_type, &key_length))
663 return nullptr;
665 switch (key_type) {
666 case EVP_PKEY_RSA:
667 return CreateRSAWrapper(key.Pass(), key_length);
668 case EVP_PKEY_EC:
669 return CreateECDSAWrapper(key.Pass(), key_length);
670 default:
671 return nullptr;
675 } // namespace net