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 "content/child/webcrypto/nss/rsa_key_nss.h"
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"
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");
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();
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();
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();
57 return ErrorRsaPrivateKeyImportNotSupported();
60 Status NssSupportsRsaPrivateKeyImport() {
61 return Status::Success();
65 bool CreateRsaHashedPublicKeyAlgorithm(
66 blink::WebCryptoAlgorithmId rsa_algorithm,
67 blink::WebCryptoAlgorithmId hash_algorithm,
69 blink::WebCryptoKeyAlgorithm* key_algorithm) {
70 // TODO(eroman): What about other key types rsaPss, rsaOaep.
71 if (!key || key->keyType != rsaKey)
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);
78 *key_algorithm = blink::WebCryptoKeyAlgorithm::createRsaHashed(
81 public_exponent.bytes(),
82 public_exponent.byte_length(),
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));
95 return CreateRsaHashedPublicKeyAlgorithm(
96 rsa_algorithm, hash_algorithm, public_key.get(), key_algorithm);
99 // From PKCS#1 [http://tools.ietf.org/html/rfc3447]:
101 // RSAPrivateKey ::= SEQUENCE {
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
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 {
119 SECItem public_exponent;
120 SECItem private_exponent;
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.
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)},
144 #endif // defined(USE_NSS)
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,
151 SECStatus rv = PK11_ReadRawAttribute(PK11_TypePrivKey, key, attribute, value);
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;
158 return rv == SECSuccess;
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.
165 // The passed in RSAPrivateKey must be zero-initialized.
166 bool InitRSAPrivateKey(SECKEYPrivateKey* key, RSAPrivateKey* out) {
167 if (key->keyType != rsaKey)
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);
176 // Always use version=0 since not using multi-prime.
177 if (!SEC_ASN1EncodeInteger(NULL, &out->version, 0))
180 if (!ReadUint(key, CKA_MODULUS, &out->modulus))
182 if (!ReadUint(key, CKA_PUBLIC_EXPONENT, &out->public_exponent))
184 if (!ReadUint(key, CKA_PRIVATE_EXPONENT, &out->private_exponent))
186 if (!ReadUint(key, CKA_PRIME_1, &out->prime1))
188 if (!ReadUint(key, CKA_PRIME_2, &out->prime2))
190 if (!ReadUint(key, CKA_EXPONENT_1, &out->exponent1))
192 if (!ReadUint(key, CKA_EXPONENT_2, &out->exponent2))
194 if (!ReadUint(key, CKA_COEFFICIENT, &out->coefficient))
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);
214 typedef scoped_ptr<CERTSubjectPublicKeyInfo,
215 crypto::NSSDestroyer<CERTSubjectPublicKeyInfo,
216 SECKEY_DestroySubjectPublicKeyInfo> >
217 ScopedCERTSubjectPublicKeyInfo;
219 struct DestroyGenericObject {
220 void operator()(PK11GenericObject* o) const {
222 PK11_DestroyGenericObject(o);
226 typedef scoped_ptr<PK11GenericObject, DestroyGenericObject>
227 ScopedPK11GenericObject;
229 // Helper to add an attribute to a template.
230 void AddAttribute(CK_ATTRIBUTE_TYPE type,
232 unsigned long length,
233 std::vector<CK_ATTRIBUTE>* templ) {
234 CK_ATTRIBUTE attribute = {type, value, length};
235 templ->push_back(attribute);
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()),
243 templ->push_back(attribute);
246 void AddAttribute(CK_ATTRIBUTE_TYPE type,
247 const std::string& data,
248 std::vector<CK_ATTRIBUTE>* templ) {
249 AddAttribute(type, CryptoData(data), templ);
252 Status ExportKeyPkcs8Nss(SECKEYPrivateKey* key, std::vector<uint8_t>* buffer) {
253 if (key->keyType != rsaKey)
254 return Status::ErrorUnsupported();
256 // TODO(rsleevi): Implement OAEP support according to the spec.
259 // PK11_ExportDERPrivateKeyInfo isn't available. Use our fallback code.
260 const SECOidTag algorithm = SEC_OID_PKCS1_RSA_ENCRYPTION;
261 const int kPrivateKeyInfoVersion = 0;
263 SECKEYPrivateKeyInfo private_key_info = {};
264 RSAPrivateKey rsa_private_key = {};
265 scoped_ptr<RSAPrivateKey, FreeRsaPrivateKey> free_private_key(
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();
273 crypto::ScopedPLArenaPool arena(PORT_NewArena(DER_DEFAULT_CHUNKSIZE));
275 return Status::OperationError();
277 if (!SEC_ASN1EncodeItem(arena.get(),
278 &private_key_info.privateKey,
280 RSAPrivateKeyTemplate))
281 return Status::OperationError();
284 SECOID_SetAlgorithmID(
285 arena.get(), &private_key_info.algorithm, algorithm, NULL))
286 return Status::OperationError();
288 if (!SEC_ASN1EncodeInteger(
289 arena.get(), &private_key_info.version, kPrivateKeyInfoVersion))
290 return Status::OperationError();
292 crypto::ScopedSECItem encoded_key(
293 SEC_ASN1EncodeItem(NULL,
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)
301 if (!encoded_key.get())
302 return Status::OperationError();
304 buffer->assign(encoded_key->data, encoded_key->data + encoded_key->len);
305 return Status::Success();
308 Status ImportRsaPrivateKey(const blink::WebCryptoAlgorithm& algorithm,
310 blink::WebCryptoKeyUsageMask usages,
311 const JwkRsaInfo& params,
312 blink::WebCryptoKey* key) {
313 Status status = NssSupportsRsaPrivateKeyImport();
314 if (status.IsError())
317 CK_OBJECT_CLASS obj_class = CKO_PRIVATE_KEY;
318 CK_KEY_TYPE key_type = CKK_RSA;
319 CK_BBOOL ck_false = CK_FALSE;
321 std::vector<CK_ATTRIBUTE> key_template;
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);
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);
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.
338 // For consistency with other NSS key creation methods, set the CKA_ID to
339 // PK11_MakeIDFromPubKey(). There are some problems with
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
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
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));
362 CKA_ID, CryptoData(object_id->data, object_id->len), &key_template);
364 // Optional properties by JWA, however guaranteed to be present by Chromium's
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);
372 crypto::ScopedPK11Slot slot(PK11_GetInternalSlot());
374 ScopedPK11GenericObject key_object(PK11_CreateGenericObject(
375 slot.get(), &key_template[0], key_template.size(), PR_FALSE));
378 return Status::OperationError();
380 crypto::ScopedSECKEYPrivateKey private_key_tmp(
381 PK11_FindKeyByKeyID(slot.get(), object_id.get(), NULL));
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()));
389 return Status::OperationError();
391 blink::WebCryptoKeyAlgorithm key_algorithm;
392 if (!CreateRsaHashedPrivateKeyAlgorithm(
394 algorithm.rsaHashedImportParams()->hash().id(),
397 return Status::ErrorUnexpected();
400 std::vector<uint8_t> pkcs8_data;
401 status = ExportKeyPkcs8Nss(private_key.get(), &pkcs8_data);
402 if (status.IsError())
405 scoped_ptr<PrivateKeyNss> key_handle(
406 new PrivateKeyNss(private_key.Pass(), CryptoData(pkcs8_data)));
408 *key = blink::WebCryptoKey::create(key_handle.release(),
409 blink::WebCryptoKeyTypePrivate,
413 return Status::Success();
416 Status ExportKeySpkiNss(SECKEYPublicKey* key, std::vector<uint8_t>* buffer) {
417 const crypto::ScopedSECItem spki_der(
418 SECKEY_EncodeDERSubjectPublicKeyInfo(key));
420 return Status::OperationError();
422 buffer->assign(spki_der->data, spki_der->data + spki_der->len);
423 return Status::Success();
426 Status ImportRsaPublicKey(const blink::WebCryptoAlgorithm& algorithm,
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();
435 if (!exponent_data.byte_length())
436 return Status::ErrorImportRsaEmptyExponent();
438 DCHECK(modulus_data.bytes());
439 DCHECK(exponent_data.bytes());
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
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 {
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)},
461 SEC_ASN1_INTEGER, offsetof(RsaPublicKeyData, modulus),
464 SEC_ASN1_INTEGER, offsetof(RsaPublicKeyData, exponent),
470 // DER-encode the public key.
471 crypto::ScopedSECItem pubkey_der(
472 SEC_ASN1EncodeItem(NULL, NULL, &pubkey_in, rsa_public_key_template));
474 return Status::OperationError();
476 // Import the DER-encoded public key to create an RSA SECKEYPublicKey.
477 crypto::ScopedSECKEYPublicKey pubkey(
478 SECKEY_ImportDERPublicKey(pubkey_der.get(), CKK_RSA));
480 return Status::OperationError();
482 blink::WebCryptoKeyAlgorithm key_algorithm;
483 if (!CreateRsaHashedPublicKeyAlgorithm(
485 algorithm.rsaHashedImportParams()->hash().id(),
488 return Status::ErrorUnexpected();
491 std::vector<uint8_t> spki_data;
492 Status status = ExportKeySpkiNss(pubkey.get(), &spki_data);
493 if (status.IsError())
496 scoped_ptr<PublicKeyNss> key_handle(
497 new PublicKeyNss(pubkey.Pass(), CryptoData(spki_data)));
499 *key = blink::WebCryptoKey::create(key_handle.release(),
500 blink::WebCryptoKeyTypePublic,
504 return Status::Success();
509 Status RsaHashedAlgorithm::GenerateKey(
510 const blink::WebCryptoAlgorithm& algorithm,
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())
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_;
524 unsigned int public_exponent = 0;
525 unsigned int modulus_length_bits = 0;
526 status = GetRsaKeyGenParameters(algorithm.rsaHashedKeyGenParams(),
528 &modulus_length_bits);
529 if (status.IsError())
532 crypto::ScopedPK11Slot slot(PK11_GetInternalKeySlot());
534 return Status::OperationError();
536 PK11RSAGenParams rsa_gen_params;
537 rsa_gen_params.keySizeInBits = modulus_length_bits;
538 rsa_gen_params.pe = public_exponent;
540 const CK_FLAGS operation_flags_mask =
541 CKF_ENCRYPT | CKF_DECRYPT | CKF_SIGN | CKF_VERIFY | CKF_WRAP | CKF_UNWRAP;
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;
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,
558 operation_flags_mask,
560 if (!scoped_sec_private_key)
561 return Status::OperationError();
563 blink::WebCryptoKeyAlgorithm key_algorithm;
564 if (!CreateRsaHashedPublicKeyAlgorithm(
566 algorithm.rsaHashedKeyGenParams()->hash().id(),
569 return Status::ErrorUnexpected();
572 std::vector<uint8_t> spki_data;
573 status = ExportKeySpkiNss(sec_public_key, &spki_data);
574 if (status.IsError())
577 scoped_ptr<PublicKeyNss> public_key_handle(new PublicKeyNss(
578 crypto::ScopedSECKEYPublicKey(sec_public_key), CryptoData(spki_data)));
580 std::vector<uint8_t> pkcs8_data;
581 status = ExportKeyPkcs8Nss(scoped_sec_private_key.get(), &pkcs8_data);
582 if (status.IsError())
585 scoped_ptr<PrivateKeyNss> private_key_handle(
586 new PrivateKeyNss(scoped_sec_private_key.Pass(), CryptoData(pkcs8_data)));
588 blink::WebCryptoKey public_key =
589 blink::WebCryptoKey::create(public_key_handle.release(),
590 blink::WebCryptoKeyTypePublic,
595 blink::WebCryptoKey private_key =
596 blink::WebCryptoKey::create(private_key_handle.release(),
597 blink::WebCryptoKeyTypePrivate,
602 result->AssignKeyPair(public_key, private_key);
603 return Status::Success();
606 Status RsaHashedAlgorithm::VerifyKeyUsagesBeforeImportKey(
607 blink::WebCryptoKeyFormat format,
608 blink::WebCryptoKeyUsageMask usages) const {
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)
620 CheckKeyCreationUsages(all_public_key_usages_, usages)
622 return Status::Success();
624 return Status::ErrorCreateKeyBadUsages();
626 return Status::ErrorUnsupportedImportKeyFormat();
630 Status RsaHashedAlgorithm::ImportKeyPkcs8(
631 const CryptoData& key_data,
632 const blink::WebCryptoAlgorithm& algorithm,
634 blink::WebCryptoKeyUsageMask usages,
635 blink::WebCryptoKey* key) const {
636 Status status = NssSupportsRsaPrivateKeyImport();
637 if (status.IsError())
640 if (!key_data.byte_length())
641 return Status::ErrorImportEmptyKeyData();
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);
647 SECKEYPrivateKey* seckey_private_key = NULL;
648 crypto::ScopedPK11Slot slot(PK11_GetInternalSlot());
649 if (PK11_ImportDERPrivateKeyInfoAndReturnKey(slot.get(),
657 NULL) != SECSuccess) {
658 return Status::DataError();
660 DCHECK(seckey_private_key);
661 crypto::ScopedSECKEYPrivateKey private_key(seckey_private_key);
663 const KeyType sec_key_type = SECKEY_GetPrivateKeyType(private_key.get());
664 if (sec_key_type != rsaKey)
665 return Status::DataError();
667 blink::WebCryptoKeyAlgorithm key_algorithm;
668 if (!CreateRsaHashedPrivateKeyAlgorithm(
670 algorithm.rsaHashedImportParams()->hash().id(),
673 return Status::ErrorUnexpected();
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())
682 scoped_ptr<PrivateKeyNss> key_handle(
683 new PrivateKeyNss(private_key.Pass(), CryptoData(pkcs8_data)));
685 *key = blink::WebCryptoKey::create(key_handle.release(),
686 blink::WebCryptoKeyTypePrivate,
691 return Status::Success();
694 Status RsaHashedAlgorithm::ImportKeySpki(
695 const CryptoData& key_data,
696 const blink::WebCryptoAlgorithm& algorithm,
698 blink::WebCryptoKeyUsageMask usages,
699 blink::WebCryptoKey* key) const {
700 if (!key_data.byte_length())
701 return Status::ErrorImportEmptyKeyData();
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));
709 return Status::DataError();
711 crypto::ScopedSECKEYPublicKey sec_public_key(
712 SECKEY_ExtractPublicKey(spki.get()));
714 return Status::DataError();
716 const KeyType sec_key_type = SECKEY_GetPublicKeyType(sec_public_key.get());
717 if (sec_key_type != rsaKey)
718 return Status::DataError();
720 blink::WebCryptoKeyAlgorithm key_algorithm;
721 if (!CreateRsaHashedPublicKeyAlgorithm(
723 algorithm.rsaHashedImportParams()->hash().id(),
724 sec_public_key.get(),
726 return Status::ErrorUnexpected();
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())
735 scoped_ptr<PublicKeyNss> key_handle(
736 new PublicKeyNss(sec_public_key.Pass(), CryptoData(spki_data)));
738 *key = blink::WebCryptoKey::create(key_handle.release(),
739 blink::WebCryptoKeyTypePublic,
744 return Status::Success();
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();
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();
763 Status RsaHashedAlgorithm::ImportKeyJwk(
764 const CryptoData& key_data,
765 const blink::WebCryptoAlgorithm& algorithm,
767 blink::WebCryptoKeyUsageMask usages,
768 blink::WebCryptoKey* key) const {
769 const char* jwk_algorithm =
770 GetJwkAlgorithm(algorithm.rsaHashedImportParams()->hash().id());
773 return Status::ErrorUnexpected();
777 ReadRsaKeyJwk(key_data, jwk_algorithm, extractable, usages, &jwk);
778 if (status.IsError())
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_,
785 if (status.IsError())
786 return Status::ErrorCreateKeyBadUsages();
788 return jwk.is_private_key
789 ? ImportRsaPrivateKey(algorithm, extractable, usages, jwk, key)
790 : ImportRsaPublicKey(algorithm,
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());
804 return Status::ErrorUnexpected();
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();
812 WriteRsaPublicKeyJwk(SECItemToCryptoData(nss_key->u.rsa.modulus),
813 SECItemToCryptoData(nss_key->u.rsa.publicExponent),
819 return Status::Success();
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);
827 if (!InitRSAPrivateKey(nss_key, &key_props))
828 return Status::OperationError();
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),
843 return Status::Success();
846 return Status::ErrorUnexpected();
850 } // namespace webcrypto
852 } // namespace content