Update To 11.40.268.0
[platform/framework/web/crosswalk.git] / src / content / child / webcrypto / nss / rsa_key_nss.cc
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.
4
5 #include "content/child/webcrypto/nss/rsa_key_nss.h"
6
7 #include "base/logging.h"
8 #include "content/child/webcrypto/crypto_data.h"
9 #include "content/child/webcrypto/generate_key_result.h"
10 #include "content/child/webcrypto/jwk.h"
11 #include "content/child/webcrypto/nss/key_nss.h"
12 #include "content/child/webcrypto/nss/util_nss.h"
13 #include "content/child/webcrypto/status.h"
14 #include "content/child/webcrypto/webcrypto_util.h"
15 #include "crypto/scoped_nss_types.h"
16 #include "third_party/WebKit/public/platform/WebCryptoAlgorithmParams.h"
17 #include "third_party/WebKit/public/platform/WebCryptoKeyAlgorithm.h"
18
19 namespace content {
20
21 namespace webcrypto {
22
23 namespace {
24
25 #if defined(USE_NSS) && !defined(OS_CHROMEOS)
26 Status ErrorRsaPrivateKeyImportNotSupported() {
27   return Status::ErrorUnsupported(
28       "NSS version must be at least 3.16.2 for RSA private key import. See "
29       "http://crbug.com/380424");
30 }
31
32 // Prior to NSS 3.16.2 RSA key parameters were not validated. This is
33 // a security problem for RSA private key import from JWK which uses a
34 // CKA_ID based on the public modulus to retrieve the private key.
35 Status NssSupportsRsaPrivateKeyImport() {
36   if (!NSS_VersionCheck("3.16.2"))
37     return ErrorRsaPrivateKeyImportNotSupported();
38
39   // Also ensure that the version of Softoken is 3.16.2 or later.
40   crypto::ScopedPK11Slot slot(PK11_GetInternalSlot());
41   CK_SLOT_INFO info = {};
42   if (PK11_GetSlotInfo(slot.get(), &info) != SECSuccess)
43     return ErrorRsaPrivateKeyImportNotSupported();
44
45   // CK_SLOT_INFO.hardwareVersion contains the major.minor
46   // version info for Softoken in the corresponding .major/.minor
47   // fields, and .firmwareVersion contains the patch.build
48   // version info (in the .major/.minor fields)
49   if ((info.hardwareVersion.major > 3) ||
50       (info.hardwareVersion.major == 3 &&
51        (info.hardwareVersion.minor > 16 ||
52         (info.hardwareVersion.minor == 16 &&
53          info.firmwareVersion.major >= 2)))) {
54     return Status::Success();
55   }
56
57   return ErrorRsaPrivateKeyImportNotSupported();
58 }
59 #else
60 Status NssSupportsRsaPrivateKeyImport() {
61   return Status::Success();
62 }
63 #endif
64
65 bool CreateRsaHashedPublicKeyAlgorithm(
66     blink::WebCryptoAlgorithmId rsa_algorithm,
67     blink::WebCryptoAlgorithmId hash_algorithm,
68     SECKEYPublicKey* key,
69     blink::WebCryptoKeyAlgorithm* key_algorithm) {
70   // TODO(eroman): What about other key types rsaPss, rsaOaep.
71   if (!key || key->keyType != rsaKey)
72     return false;
73
74   unsigned int modulus_length_bits = SECKEY_PublicKeyStrength(key) * 8;
75   CryptoData public_exponent(key->u.rsa.publicExponent.data,
76                              key->u.rsa.publicExponent.len);
77
78   *key_algorithm = blink::WebCryptoKeyAlgorithm::createRsaHashed(
79       rsa_algorithm,
80       modulus_length_bits,
81       public_exponent.bytes(),
82       public_exponent.byte_length(),
83       hash_algorithm);
84   return true;
85 }
86
87 bool CreateRsaHashedPrivateKeyAlgorithm(
88     blink::WebCryptoAlgorithmId rsa_algorithm,
89     blink::WebCryptoAlgorithmId hash_algorithm,
90     SECKEYPrivateKey* key,
91     blink::WebCryptoKeyAlgorithm* key_algorithm) {
92   crypto::ScopedSECKEYPublicKey public_key(SECKEY_ConvertToPublicKey(key));
93   if (!public_key)
94     return false;
95   return CreateRsaHashedPublicKeyAlgorithm(
96       rsa_algorithm, hash_algorithm, public_key.get(), key_algorithm);
97 }
98
99 // From PKCS#1 [http://tools.ietf.org/html/rfc3447]:
100 //
101 //    RSAPrivateKey ::= SEQUENCE {
102 //      version           Version,
103 //      modulus           INTEGER,  -- n
104 //      publicExponent    INTEGER,  -- e
105 //      privateExponent   INTEGER,  -- d
106 //      prime1            INTEGER,  -- p
107 //      prime2            INTEGER,  -- q
108 //      exponent1         INTEGER,  -- d mod (p-1)
109 //      exponent2         INTEGER,  -- d mod (q-1)
110 //      coefficient       INTEGER,  -- (inverse of q) mod p
111 //      otherPrimeInfos   OtherPrimeInfos OPTIONAL
112 //    }
113 //
114 // Note that otherPrimeInfos is only applicable for version=1. Since NSS
115 // doesn't use multi-prime can safely use version=0.
116 struct RSAPrivateKey {
117   SECItem version;
118   SECItem modulus;
119   SECItem public_exponent;
120   SECItem private_exponent;
121   SECItem prime1;
122   SECItem prime2;
123   SECItem exponent1;
124   SECItem exponent2;
125   SECItem coefficient;
126 };
127
128 // The system NSS library doesn't have the new PK11_ExportDERPrivateKeyInfo
129 // function yet (https://bugzilla.mozilla.org/show_bug.cgi?id=519255). So we
130 // provide a fallback implementation.
131 #if defined(USE_NSS)
132 const SEC_ASN1Template RSAPrivateKeyTemplate[] = {
133     {SEC_ASN1_SEQUENCE, 0, NULL, sizeof(RSAPrivateKey)},
134     {SEC_ASN1_INTEGER, offsetof(RSAPrivateKey, version)},
135     {SEC_ASN1_INTEGER, offsetof(RSAPrivateKey, modulus)},
136     {SEC_ASN1_INTEGER, offsetof(RSAPrivateKey, public_exponent)},
137     {SEC_ASN1_INTEGER, offsetof(RSAPrivateKey, private_exponent)},
138     {SEC_ASN1_INTEGER, offsetof(RSAPrivateKey, prime1)},
139     {SEC_ASN1_INTEGER, offsetof(RSAPrivateKey, prime2)},
140     {SEC_ASN1_INTEGER, offsetof(RSAPrivateKey, exponent1)},
141     {SEC_ASN1_INTEGER, offsetof(RSAPrivateKey, exponent2)},
142     {SEC_ASN1_INTEGER, offsetof(RSAPrivateKey, coefficient)},
143     {0}};
144 #endif  // defined(USE_NSS)
145
146 // On success |value| will be filled with data which must be freed by
147 // SECITEM_FreeItem(value, PR_FALSE);
148 bool ReadUint(SECKEYPrivateKey* key,
149               CK_ATTRIBUTE_TYPE attribute,
150               SECItem* value) {
151   SECStatus rv = PK11_ReadRawAttribute(PK11_TypePrivKey, key, attribute, value);
152
153   // PK11_ReadRawAttribute() returns items of type siBuffer. However in order
154   // for the ASN.1 encoding to be correct, the items must be of type
155   // siUnsignedInteger.
156   value->type = siUnsignedInteger;
157
158   return rv == SECSuccess;
159 }
160
161 // Fills |out| with the RSA private key properties. Returns true on success.
162 // Regardless of the return value, the caller must invoke FreeRSAPrivateKey()
163 // to free up any allocated memory.
164 //
165 // The passed in RSAPrivateKey must be zero-initialized.
166 bool InitRSAPrivateKey(SECKEYPrivateKey* key, RSAPrivateKey* out) {
167   if (key->keyType != rsaKey)
168     return false;
169
170   // Everything should be zero-ed out. These are just some spot checks.
171   DCHECK(!out->version.data);
172   DCHECK(!out->version.len);
173   DCHECK(!out->modulus.data);
174   DCHECK(!out->modulus.len);
175
176   // Always use version=0 since not using multi-prime.
177   if (!SEC_ASN1EncodeInteger(NULL, &out->version, 0))
178     return false;
179
180   if (!ReadUint(key, CKA_MODULUS, &out->modulus))
181     return false;
182   if (!ReadUint(key, CKA_PUBLIC_EXPONENT, &out->public_exponent))
183     return false;
184   if (!ReadUint(key, CKA_PRIVATE_EXPONENT, &out->private_exponent))
185     return false;
186   if (!ReadUint(key, CKA_PRIME_1, &out->prime1))
187     return false;
188   if (!ReadUint(key, CKA_PRIME_2, &out->prime2))
189     return false;
190   if (!ReadUint(key, CKA_EXPONENT_1, &out->exponent1))
191     return false;
192   if (!ReadUint(key, CKA_EXPONENT_2, &out->exponent2))
193     return false;
194   if (!ReadUint(key, CKA_COEFFICIENT, &out->coefficient))
195     return false;
196
197   return true;
198 }
199
200 struct FreeRsaPrivateKey {
201   void operator()(RSAPrivateKey* out) {
202     SECITEM_FreeItem(&out->version, PR_FALSE);
203     SECITEM_FreeItem(&out->modulus, PR_FALSE);
204     SECITEM_FreeItem(&out->public_exponent, PR_FALSE);
205     SECITEM_FreeItem(&out->private_exponent, PR_FALSE);
206     SECITEM_FreeItem(&out->prime1, PR_FALSE);
207     SECITEM_FreeItem(&out->prime2, PR_FALSE);
208     SECITEM_FreeItem(&out->exponent1, PR_FALSE);
209     SECITEM_FreeItem(&out->exponent2, PR_FALSE);
210     SECITEM_FreeItem(&out->coefficient, PR_FALSE);
211   }
212 };
213
214 typedef scoped_ptr<CERTSubjectPublicKeyInfo,
215                    crypto::NSSDestroyer<CERTSubjectPublicKeyInfo,
216                                         SECKEY_DestroySubjectPublicKeyInfo> >
217     ScopedCERTSubjectPublicKeyInfo;
218
219 struct DestroyGenericObject {
220   void operator()(PK11GenericObject* o) const {
221     if (o)
222       PK11_DestroyGenericObject(o);
223   }
224 };
225
226 typedef scoped_ptr<PK11GenericObject, DestroyGenericObject>
227     ScopedPK11GenericObject;
228
229 // Helper to add an attribute to a template.
230 void AddAttribute(CK_ATTRIBUTE_TYPE type,
231                   void* value,
232                   unsigned long length,
233                   std::vector<CK_ATTRIBUTE>* templ) {
234   CK_ATTRIBUTE attribute = {type, value, length};
235   templ->push_back(attribute);
236 }
237
238 void AddAttribute(CK_ATTRIBUTE_TYPE type,
239                   const CryptoData& data,
240                   std::vector<CK_ATTRIBUTE>* templ) {
241   CK_ATTRIBUTE attribute = {type, const_cast<unsigned char*>(data.bytes()),
242                             data.byte_length()};
243   templ->push_back(attribute);
244 }
245
246 void AddAttribute(CK_ATTRIBUTE_TYPE type,
247                   const std::string& data,
248                   std::vector<CK_ATTRIBUTE>* templ) {
249   AddAttribute(type, CryptoData(data), templ);
250 }
251
252 Status ExportKeyPkcs8Nss(SECKEYPrivateKey* key, std::vector<uint8_t>* buffer) {
253   if (key->keyType != rsaKey)
254     return Status::ErrorUnsupported();
255
256 // TODO(rsleevi): Implement OAEP support according to the spec.
257
258 #if defined(USE_NSS)
259   // PK11_ExportDERPrivateKeyInfo isn't available. Use our fallback code.
260   const SECOidTag algorithm = SEC_OID_PKCS1_RSA_ENCRYPTION;
261   const int kPrivateKeyInfoVersion = 0;
262
263   SECKEYPrivateKeyInfo private_key_info = {};
264   RSAPrivateKey rsa_private_key = {};
265   scoped_ptr<RSAPrivateKey, FreeRsaPrivateKey> free_private_key(
266       &rsa_private_key);
267
268   // http://crbug.com/366427: the spec does not define any other failures for
269   // exporting, so none of the subsequent errors are spec compliant.
270   if (!InitRSAPrivateKey(key, &rsa_private_key))
271     return Status::OperationError();
272
273   crypto::ScopedPLArenaPool arena(PORT_NewArena(DER_DEFAULT_CHUNKSIZE));
274   if (!arena.get())
275     return Status::OperationError();
276
277   if (!SEC_ASN1EncodeItem(arena.get(),
278                           &private_key_info.privateKey,
279                           &rsa_private_key,
280                           RSAPrivateKeyTemplate))
281     return Status::OperationError();
282
283   if (SECSuccess !=
284       SECOID_SetAlgorithmID(
285           arena.get(), &private_key_info.algorithm, algorithm, NULL))
286     return Status::OperationError();
287
288   if (!SEC_ASN1EncodeInteger(
289           arena.get(), &private_key_info.version, kPrivateKeyInfoVersion))
290     return Status::OperationError();
291
292   crypto::ScopedSECItem encoded_key(
293       SEC_ASN1EncodeItem(NULL,
294                          NULL,
295                          &private_key_info,
296                          SEC_ASN1_GET(SECKEY_PrivateKeyInfoTemplate)));
297 #else   // defined(USE_NSS)
298   crypto::ScopedSECItem encoded_key(PK11_ExportDERPrivateKeyInfo(key, NULL));
299 #endif  // defined(USE_NSS)
300
301   if (!encoded_key.get())
302     return Status::OperationError();
303
304   buffer->assign(encoded_key->data, encoded_key->data + encoded_key->len);
305   return Status::Success();
306 }
307
308 Status ImportRsaPrivateKey(const blink::WebCryptoAlgorithm& algorithm,
309                            bool extractable,
310                            blink::WebCryptoKeyUsageMask usages,
311                            const JwkRsaInfo& params,
312                            blink::WebCryptoKey* key) {
313   Status status = NssSupportsRsaPrivateKeyImport();
314   if (status.IsError())
315     return status;
316
317   CK_OBJECT_CLASS obj_class = CKO_PRIVATE_KEY;
318   CK_KEY_TYPE key_type = CKK_RSA;
319   CK_BBOOL ck_false = CK_FALSE;
320
321   std::vector<CK_ATTRIBUTE> key_template;
322
323   AddAttribute(CKA_CLASS, &obj_class, sizeof(obj_class), &key_template);
324   AddAttribute(CKA_KEY_TYPE, &key_type, sizeof(key_type), &key_template);
325   AddAttribute(CKA_TOKEN, &ck_false, sizeof(ck_false), &key_template);
326   AddAttribute(CKA_SENSITIVE, &ck_false, sizeof(ck_false), &key_template);
327   AddAttribute(CKA_PRIVATE, &ck_false, sizeof(ck_false), &key_template);
328
329   // Required properties by JWA.
330   AddAttribute(CKA_MODULUS, params.n, &key_template);
331   AddAttribute(CKA_PUBLIC_EXPONENT, params.e, &key_template);
332   AddAttribute(CKA_PRIVATE_EXPONENT, params.d, &key_template);
333
334   // Manufacture a CKA_ID so the created key can be retrieved later as a
335   // SECKEYPrivateKey using FindKeyByKeyID(). Unfortunately there isn't a more
336   // direct way to do this in NSS.
337   //
338   // For consistency with other NSS key creation methods, set the CKA_ID to
339   // PK11_MakeIDFromPubKey(). There are some problems with
340   // this approach:
341   //
342   //  (1) Prior to NSS 3.16.2, there is no parameter validation when creating
343   //      private keys. It is therefore possible to construct a key using the
344   //      known public modulus, and where all the other parameters are bogus.
345   //      FindKeyByKeyID() returns the first key matching the ID. So this would
346   //      effectively allow an attacker to retrieve a private key of their
347   //      choice.
348   //
349   //  (2) The ID space is shared by different key types. So theoretically
350   //      possible to retrieve a key of the wrong type which has a matching
351   //      CKA_ID. In practice I am told this is not likely except for small key
352   //      sizes, since would require constructing keys with the same public
353   //      data.
354   //
355   //  (3) FindKeyByKeyID() doesn't necessarily return the object that was just
356   //      created by CreateGenericObject. If the pre-existing key was
357   //      provisioned with flags incompatible with WebCrypto (for instance
358   //      marked sensitive) then this will break things.
359   SECItem modulus_item = MakeSECItemForBuffer(CryptoData(params.n));
360   crypto::ScopedSECItem object_id(PK11_MakeIDFromPubKey(&modulus_item));
361   AddAttribute(
362       CKA_ID, CryptoData(object_id->data, object_id->len), &key_template);
363
364   // Optional properties by JWA, however guaranteed to be present by Chromium's
365   // implementation.
366   AddAttribute(CKA_PRIME_1, params.p, &key_template);
367   AddAttribute(CKA_PRIME_2, params.q, &key_template);
368   AddAttribute(CKA_EXPONENT_1, params.dp, &key_template);
369   AddAttribute(CKA_EXPONENT_2, params.dq, &key_template);
370   AddAttribute(CKA_COEFFICIENT, params.qi, &key_template);
371
372   crypto::ScopedPK11Slot slot(PK11_GetInternalSlot());
373
374   ScopedPK11GenericObject key_object(PK11_CreateGenericObject(
375       slot.get(), &key_template[0], key_template.size(), PR_FALSE));
376
377   if (!key_object)
378     return Status::OperationError();
379
380   crypto::ScopedSECKEYPrivateKey private_key_tmp(
381       PK11_FindKeyByKeyID(slot.get(), object_id.get(), NULL));
382
383   // PK11_FindKeyByKeyID() may return a handle to an existing key, rather than
384   // the object created by PK11_CreateGenericObject().
385   crypto::ScopedSECKEYPrivateKey private_key(
386       SECKEY_CopyPrivateKey(private_key_tmp.get()));
387
388   if (!private_key)
389     return Status::OperationError();
390
391   blink::WebCryptoKeyAlgorithm key_algorithm;
392   if (!CreateRsaHashedPrivateKeyAlgorithm(
393           algorithm.id(),
394           algorithm.rsaHashedImportParams()->hash().id(),
395           private_key.get(),
396           &key_algorithm)) {
397     return Status::ErrorUnexpected();
398   }
399
400   std::vector<uint8_t> pkcs8_data;
401   status = ExportKeyPkcs8Nss(private_key.get(), &pkcs8_data);
402   if (status.IsError())
403     return status;
404
405   scoped_ptr<PrivateKeyNss> key_handle(
406       new PrivateKeyNss(private_key.Pass(), CryptoData(pkcs8_data)));
407
408   *key = blink::WebCryptoKey::create(key_handle.release(),
409                                      blink::WebCryptoKeyTypePrivate,
410                                      extractable,
411                                      key_algorithm,
412                                      usages);
413   return Status::Success();
414 }
415
416 Status ExportKeySpkiNss(SECKEYPublicKey* key, std::vector<uint8_t>* buffer) {
417   const crypto::ScopedSECItem spki_der(
418       SECKEY_EncodeDERSubjectPublicKeyInfo(key));
419   if (!spki_der)
420     return Status::OperationError();
421
422   buffer->assign(spki_der->data, spki_der->data + spki_der->len);
423   return Status::Success();
424 }
425
426 Status ImportRsaPublicKey(const blink::WebCryptoAlgorithm& algorithm,
427                           bool extractable,
428                           blink::WebCryptoKeyUsageMask usages,
429                           const CryptoData& modulus_data,
430                           const CryptoData& exponent_data,
431                           blink::WebCryptoKey* key) {
432   if (!modulus_data.byte_length())
433     return Status::ErrorImportRsaEmptyModulus();
434
435   if (!exponent_data.byte_length())
436     return Status::ErrorImportRsaEmptyExponent();
437
438   DCHECK(modulus_data.bytes());
439   DCHECK(exponent_data.bytes());
440
441   // NSS does not provide a way to create an RSA public key directly from the
442   // modulus and exponent values, but it can import an DER-encoded ASN.1 blob
443   // with these values and create the public key from that. The code below
444   // follows the recommendation described in
445   // https://developer.mozilla.org/en-US/docs/NSS/NSS_Tech_Notes/nss_tech_note7
446
447   // Pack the input values into a struct compatible with NSS ASN.1 encoding, and
448   // set up an ASN.1 encoder template for it.
449   struct RsaPublicKeyData {
450     SECItem modulus;
451     SECItem exponent;
452   };
453   const RsaPublicKeyData pubkey_in = {
454       {siUnsignedInteger, const_cast<unsigned char*>(modulus_data.bytes()),
455        modulus_data.byte_length()},
456       {siUnsignedInteger, const_cast<unsigned char*>(exponent_data.bytes()),
457        exponent_data.byte_length()}};
458   const SEC_ASN1Template rsa_public_key_template[] = {
459       {SEC_ASN1_SEQUENCE, 0, NULL, sizeof(RsaPublicKeyData)},
460       {
461        SEC_ASN1_INTEGER, offsetof(RsaPublicKeyData, modulus),
462       },
463       {
464        SEC_ASN1_INTEGER, offsetof(RsaPublicKeyData, exponent),
465       },
466       {
467        0,
468       }};
469
470   // DER-encode the public key.
471   crypto::ScopedSECItem pubkey_der(
472       SEC_ASN1EncodeItem(NULL, NULL, &pubkey_in, rsa_public_key_template));
473   if (!pubkey_der)
474     return Status::OperationError();
475
476   // Import the DER-encoded public key to create an RSA SECKEYPublicKey.
477   crypto::ScopedSECKEYPublicKey pubkey(
478       SECKEY_ImportDERPublicKey(pubkey_der.get(), CKK_RSA));
479   if (!pubkey)
480     return Status::OperationError();
481
482   blink::WebCryptoKeyAlgorithm key_algorithm;
483   if (!CreateRsaHashedPublicKeyAlgorithm(
484           algorithm.id(),
485           algorithm.rsaHashedImportParams()->hash().id(),
486           pubkey.get(),
487           &key_algorithm)) {
488     return Status::ErrorUnexpected();
489   }
490
491   std::vector<uint8_t> spki_data;
492   Status status = ExportKeySpkiNss(pubkey.get(), &spki_data);
493   if (status.IsError())
494     return status;
495
496   scoped_ptr<PublicKeyNss> key_handle(
497       new PublicKeyNss(pubkey.Pass(), CryptoData(spki_data)));
498
499   *key = blink::WebCryptoKey::create(key_handle.release(),
500                                      blink::WebCryptoKeyTypePublic,
501                                      extractable,
502                                      key_algorithm,
503                                      usages);
504   return Status::Success();
505 }
506
507 }  // namespace
508
509 Status RsaHashedAlgorithm::GenerateKey(
510     const blink::WebCryptoAlgorithm& algorithm,
511     bool extractable,
512     blink::WebCryptoKeyUsageMask combined_usages,
513     GenerateKeyResult* result) const {
514   Status status = CheckKeyCreationUsages(
515       all_public_key_usages_ | all_private_key_usages_, combined_usages);
516   if (status.IsError())
517     return status;
518
519   const blink::WebCryptoKeyUsageMask public_usages =
520       combined_usages & all_public_key_usages_;
521   const blink::WebCryptoKeyUsageMask private_usages =
522       combined_usages & all_private_key_usages_;
523
524   unsigned int public_exponent = 0;
525   unsigned int modulus_length_bits = 0;
526   status = GetRsaKeyGenParameters(algorithm.rsaHashedKeyGenParams(),
527                                   &public_exponent,
528                                   &modulus_length_bits);
529   if (status.IsError())
530     return status;
531
532   crypto::ScopedPK11Slot slot(PK11_GetInternalKeySlot());
533   if (!slot)
534     return Status::OperationError();
535
536   PK11RSAGenParams rsa_gen_params;
537   rsa_gen_params.keySizeInBits = modulus_length_bits;
538   rsa_gen_params.pe = public_exponent;
539
540   const CK_FLAGS operation_flags_mask =
541       CKF_ENCRYPT | CKF_DECRYPT | CKF_SIGN | CKF_VERIFY | CKF_WRAP | CKF_UNWRAP;
542
543   // The private key must be marked as insensitive and extractable, otherwise it
544   // cannot later be exported in unencrypted form or structured-cloned.
545   const PK11AttrFlags attribute_flags =
546       PK11_ATTR_INSENSITIVE | PK11_ATTR_EXTRACTABLE;
547
548   // Note: NSS does not generate an sec_public_key if the call below fails,
549   // so there is no danger of a leaked sec_public_key.
550   SECKEYPublicKey* sec_public_key;
551   crypto::ScopedSECKEYPrivateKey scoped_sec_private_key(
552       PK11_GenerateKeyPairWithOpFlags(slot.get(),
553                                       CKM_RSA_PKCS_KEY_PAIR_GEN,
554                                       &rsa_gen_params,
555                                       &sec_public_key,
556                                       attribute_flags,
557                                       generate_flags_,
558                                       operation_flags_mask,
559                                       NULL));
560   if (!scoped_sec_private_key)
561     return Status::OperationError();
562
563   blink::WebCryptoKeyAlgorithm key_algorithm;
564   if (!CreateRsaHashedPublicKeyAlgorithm(
565           algorithm.id(),
566           algorithm.rsaHashedKeyGenParams()->hash().id(),
567           sec_public_key,
568           &key_algorithm)) {
569     return Status::ErrorUnexpected();
570   }
571
572   std::vector<uint8_t> spki_data;
573   status = ExportKeySpkiNss(sec_public_key, &spki_data);
574   if (status.IsError())
575     return status;
576
577   scoped_ptr<PublicKeyNss> public_key_handle(new PublicKeyNss(
578       crypto::ScopedSECKEYPublicKey(sec_public_key), CryptoData(spki_data)));
579
580   std::vector<uint8_t> pkcs8_data;
581   status = ExportKeyPkcs8Nss(scoped_sec_private_key.get(), &pkcs8_data);
582   if (status.IsError())
583     return status;
584
585   scoped_ptr<PrivateKeyNss> private_key_handle(
586       new PrivateKeyNss(scoped_sec_private_key.Pass(), CryptoData(pkcs8_data)));
587
588   blink::WebCryptoKey public_key =
589       blink::WebCryptoKey::create(public_key_handle.release(),
590                                   blink::WebCryptoKeyTypePublic,
591                                   true,
592                                   key_algorithm,
593                                   public_usages);
594
595   blink::WebCryptoKey private_key =
596       blink::WebCryptoKey::create(private_key_handle.release(),
597                                   blink::WebCryptoKeyTypePrivate,
598                                   extractable,
599                                   key_algorithm,
600                                   private_usages);
601
602   result->AssignKeyPair(public_key, private_key);
603   return Status::Success();
604 }
605
606 Status RsaHashedAlgorithm::VerifyKeyUsagesBeforeImportKey(
607     blink::WebCryptoKeyFormat format,
608     blink::WebCryptoKeyUsageMask usages) const {
609   switch (format) {
610     case blink::WebCryptoKeyFormatSpki:
611       return CheckKeyCreationUsages(all_public_key_usages_, usages);
612     case blink::WebCryptoKeyFormatPkcs8:
613       return CheckKeyCreationUsages(all_private_key_usages_, usages);
614     case blink::WebCryptoKeyFormatJwk:
615       // The JWK could represent either a public key or private key. The usages
616       // must make sense for one of the two. The usages will be checked again by
617       // ImportKeyJwk() once the key type has been determined.
618       if (CheckKeyCreationUsages(all_private_key_usages_, usages)
619               .IsSuccess() ||
620           CheckKeyCreationUsages(all_public_key_usages_, usages)
621               .IsSuccess()) {
622         return Status::Success();
623       }
624       return Status::ErrorCreateKeyBadUsages();
625     default:
626       return Status::ErrorUnsupportedImportKeyFormat();
627   }
628 }
629
630 Status RsaHashedAlgorithm::ImportKeyPkcs8(
631     const CryptoData& key_data,
632     const blink::WebCryptoAlgorithm& algorithm,
633     bool extractable,
634     blink::WebCryptoKeyUsageMask usages,
635     blink::WebCryptoKey* key) const {
636   Status status = NssSupportsRsaPrivateKeyImport();
637   if (status.IsError())
638     return status;
639
640   if (!key_data.byte_length())
641     return Status::ErrorImportEmptyKeyData();
642
643   // The binary blob 'key_data' is expected to be a DER-encoded ASN.1 PKCS#8
644   // private key info object.
645   SECItem pki_der = MakeSECItemForBuffer(key_data);
646
647   SECKEYPrivateKey* seckey_private_key = NULL;
648   crypto::ScopedPK11Slot slot(PK11_GetInternalSlot());
649   if (PK11_ImportDERPrivateKeyInfoAndReturnKey(slot.get(),
650                                                &pki_der,
651                                                NULL,    // nickname
652                                                NULL,    // publicValue
653                                                false,   // isPerm
654                                                false,   // isPrivate
655                                                KU_ALL,  // usage
656                                                &seckey_private_key,
657                                                NULL) != SECSuccess) {
658     return Status::DataError();
659   }
660   DCHECK(seckey_private_key);
661   crypto::ScopedSECKEYPrivateKey private_key(seckey_private_key);
662
663   const KeyType sec_key_type = SECKEY_GetPrivateKeyType(private_key.get());
664   if (sec_key_type != rsaKey)
665     return Status::DataError();
666
667   blink::WebCryptoKeyAlgorithm key_algorithm;
668   if (!CreateRsaHashedPrivateKeyAlgorithm(
669           algorithm.id(),
670           algorithm.rsaHashedImportParams()->hash().id(),
671           private_key.get(),
672           &key_algorithm)) {
673     return Status::ErrorUnexpected();
674   }
675
676   // TODO(eroman): This is probably going to be the same as the input.
677   std::vector<uint8_t> pkcs8_data;
678   status = ExportKeyPkcs8Nss(private_key.get(), &pkcs8_data);
679   if (status.IsError())
680     return status;
681
682   scoped_ptr<PrivateKeyNss> key_handle(
683       new PrivateKeyNss(private_key.Pass(), CryptoData(pkcs8_data)));
684
685   *key = blink::WebCryptoKey::create(key_handle.release(),
686                                      blink::WebCryptoKeyTypePrivate,
687                                      extractable,
688                                      key_algorithm,
689                                      usages);
690
691   return Status::Success();
692 }
693
694 Status RsaHashedAlgorithm::ImportKeySpki(
695     const CryptoData& key_data,
696     const blink::WebCryptoAlgorithm& algorithm,
697     bool extractable,
698     blink::WebCryptoKeyUsageMask usages,
699     blink::WebCryptoKey* key) const {
700   if (!key_data.byte_length())
701     return Status::ErrorImportEmptyKeyData();
702
703   // The binary blob 'key_data' is expected to be a DER-encoded ASN.1 Subject
704   // Public Key Info. Decode this to a CERTSubjectPublicKeyInfo.
705   SECItem spki_item = MakeSECItemForBuffer(key_data);
706   const ScopedCERTSubjectPublicKeyInfo spki(
707       SECKEY_DecodeDERSubjectPublicKeyInfo(&spki_item));
708   if (!spki)
709     return Status::DataError();
710
711   crypto::ScopedSECKEYPublicKey sec_public_key(
712       SECKEY_ExtractPublicKey(spki.get()));
713   if (!sec_public_key)
714     return Status::DataError();
715
716   const KeyType sec_key_type = SECKEY_GetPublicKeyType(sec_public_key.get());
717   if (sec_key_type != rsaKey)
718     return Status::DataError();
719
720   blink::WebCryptoKeyAlgorithm key_algorithm;
721   if (!CreateRsaHashedPublicKeyAlgorithm(
722           algorithm.id(),
723           algorithm.rsaHashedImportParams()->hash().id(),
724           sec_public_key.get(),
725           &key_algorithm)) {
726     return Status::ErrorUnexpected();
727   }
728
729   // TODO(eroman): This is probably going to be the same as the input.
730   std::vector<uint8_t> spki_data;
731   Status status = ExportKeySpkiNss(sec_public_key.get(), &spki_data);
732   if (status.IsError())
733     return status;
734
735   scoped_ptr<PublicKeyNss> key_handle(
736       new PublicKeyNss(sec_public_key.Pass(), CryptoData(spki_data)));
737
738   *key = blink::WebCryptoKey::create(key_handle.release(),
739                                      blink::WebCryptoKeyTypePublic,
740                                      extractable,
741                                      key_algorithm,
742                                      usages);
743
744   return Status::Success();
745 }
746
747 Status RsaHashedAlgorithm::ExportKeyPkcs8(const blink::WebCryptoKey& key,
748                                           std::vector<uint8_t>* buffer) const {
749   if (key.type() != blink::WebCryptoKeyTypePrivate)
750     return Status::ErrorUnexpectedKeyType();
751   *buffer = PrivateKeyNss::Cast(key)->pkcs8_data();
752   return Status::Success();
753 }
754
755 Status RsaHashedAlgorithm::ExportKeySpki(const blink::WebCryptoKey& key,
756                                          std::vector<uint8_t>* buffer) const {
757   if (key.type() != blink::WebCryptoKeyTypePublic)
758     return Status::ErrorUnexpectedKeyType();
759   *buffer = PublicKeyNss::Cast(key)->spki_data();
760   return Status::Success();
761 }
762
763 Status RsaHashedAlgorithm::ImportKeyJwk(
764     const CryptoData& key_data,
765     const blink::WebCryptoAlgorithm& algorithm,
766     bool extractable,
767     blink::WebCryptoKeyUsageMask usages,
768     blink::WebCryptoKey* key) const {
769   const char* jwk_algorithm =
770       GetJwkAlgorithm(algorithm.rsaHashedImportParams()->hash().id());
771
772   if (!jwk_algorithm)
773     return Status::ErrorUnexpected();
774
775   JwkRsaInfo jwk;
776   Status status =
777       ReadRsaKeyJwk(key_data, jwk_algorithm, extractable, usages, &jwk);
778   if (status.IsError())
779     return status;
780
781   // Once the key type is known, verify the usages.
782   status = CheckKeyCreationUsages(
783       jwk.is_private_key ? all_private_key_usages_ : all_public_key_usages_,
784       usages);
785   if (status.IsError())
786     return Status::ErrorCreateKeyBadUsages();
787
788   return jwk.is_private_key
789              ? ImportRsaPrivateKey(algorithm, extractable, usages, jwk, key)
790              : ImportRsaPublicKey(algorithm,
791                                   extractable,
792                                   usages,
793                                   CryptoData(jwk.n),
794                                   CryptoData(jwk.e),
795                                   key);
796 }
797
798 Status RsaHashedAlgorithm::ExportKeyJwk(const blink::WebCryptoKey& key,
799                                         std::vector<uint8_t>* buffer) const {
800   const char* jwk_algorithm =
801       GetJwkAlgorithm(key.algorithm().rsaHashedParams()->hash().id());
802
803   if (!jwk_algorithm)
804     return Status::ErrorUnexpected();
805
806   switch (key.type()) {
807     case blink::WebCryptoKeyTypePublic: {
808       SECKEYPublicKey* nss_key = PublicKeyNss::Cast(key)->key();
809       if (nss_key->keyType != rsaKey)
810         return Status::ErrorUnsupported();
811
812       WriteRsaPublicKeyJwk(SECItemToCryptoData(nss_key->u.rsa.modulus),
813                            SECItemToCryptoData(nss_key->u.rsa.publicExponent),
814                            jwk_algorithm,
815                            key.extractable(),
816                            key.usages(),
817                            buffer);
818
819       return Status::Success();
820     }
821
822     case blink::WebCryptoKeyTypePrivate: {
823       SECKEYPrivateKey* nss_key = PrivateKeyNss::Cast(key)->key();
824       RSAPrivateKey key_props = {};
825       scoped_ptr<RSAPrivateKey, FreeRsaPrivateKey> free_private_key(&key_props);
826
827       if (!InitRSAPrivateKey(nss_key, &key_props))
828         return Status::OperationError();
829
830       WriteRsaPrivateKeyJwk(SECItemToCryptoData(key_props.modulus),
831                             SECItemToCryptoData(key_props.public_exponent),
832                             SECItemToCryptoData(key_props.private_exponent),
833                             SECItemToCryptoData(key_props.prime1),
834                             SECItemToCryptoData(key_props.prime2),
835                             SECItemToCryptoData(key_props.exponent1),
836                             SECItemToCryptoData(key_props.exponent2),
837                             SECItemToCryptoData(key_props.coefficient),
838                             jwk_algorithm,
839                             key.extractable(),
840                             key.usages(),
841                             buffer);
842
843       return Status::Success();
844     }
845     default:
846       return Status::ErrorUnexpected();
847   }
848 }
849
850 }  // namespace webcrypto
851
852 }  // namespace content