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/platform_crypto.h"
14 #include "base/lazy_instance.h"
15 #include "base/logging.h"
16 #include "base/memory/scoped_ptr.h"
17 #include "content/child/webcrypto/crypto_data.h"
18 #include "content/child/webcrypto/status.h"
19 #include "content/child/webcrypto/webcrypto_util.h"
20 #include "crypto/nss_util.h"
21 #include "crypto/scoped_nss_types.h"
22 #include "third_party/WebKit/public/platform/WebCryptoAlgorithm.h"
23 #include "third_party/WebKit/public/platform/WebCryptoAlgorithmParams.h"
24 #include "third_party/WebKit/public/platform/WebCryptoKeyAlgorithm.h"
31 // At the time of this writing:
32 // * Windows and Mac builds ship with their own copy of NSS (3.15+)
33 // * Linux builds use the system's libnss, which is 3.14 on Debian (but 3.15+
36 // Since NSS provides AES-GCM support starting in version 3.15, it may be
37 // unavailable for Linux Chrome users.
39 // * !defined(CKM_AES_GCM)
41 // This means that at build time, the NSS header pkcs11t.h is older than
42 // 3.15. However at runtime support may be present.
44 // * !defined(USE_NSS)
46 // This means that Chrome is being built with an embedded copy of NSS,
47 // which can be assumed to be >= 3.15. On the other hand if USE_NSS is
48 // defined, it also implies running on Linux.
50 // TODO(eroman): Simplify this once 3.15+ is required by Linux builds.
51 #if !defined(CKM_AES_GCM)
52 #define CKM_AES_GCM 0x00001087
54 struct CK_GCM_PARAMS {
61 #endif // !defined(CKM_AES_GCM)
63 // Signature for PK11_Encrypt and PK11_Decrypt.
64 typedef SECStatus (*PK11_EncryptDecryptFunction)(PK11SymKey*,
73 // Singleton to abstract away dynamically loading libnss3.so
76 bool IsSupported() const { return pk11_encrypt_func_ && pk11_decrypt_func_; }
78 // Returns NULL if unsupported.
79 PK11_EncryptDecryptFunction pk11_encrypt_func() const {
80 return pk11_encrypt_func_;
83 // Returns NULL if unsupported.
84 PK11_EncryptDecryptFunction pk11_decrypt_func() const {
85 return pk11_decrypt_func_;
89 friend struct base::DefaultLazyInstanceTraits<AesGcmSupport>;
93 // Using a bundled version of NSS that is guaranteed to have this symbol.
94 pk11_encrypt_func_ = PK11_Encrypt;
95 pk11_decrypt_func_ = PK11_Decrypt;
97 // Using system NSS libraries and PCKS #11 modules, which may not have the
98 // necessary function (PK11_Encrypt) or mechanism support (CKM_AES_GCM).
100 // If PK11_Encrypt() was successfully resolved, then NSS will support
101 // AES-GCM directly. This was introduced in NSS 3.15.
102 pk11_encrypt_func_ = reinterpret_cast<PK11_EncryptDecryptFunction>(
103 dlsym(RTLD_DEFAULT, "PK11_Encrypt"));
104 pk11_decrypt_func_ = reinterpret_cast<PK11_EncryptDecryptFunction>(
105 dlsym(RTLD_DEFAULT, "PK11_Decrypt"));
109 PK11_EncryptDecryptFunction pk11_encrypt_func_;
110 PK11_EncryptDecryptFunction pk11_decrypt_func_;
113 base::LazyInstance<AesGcmSupport>::Leaky g_aes_gcm_support =
114 LAZY_INSTANCE_INITIALIZER;
118 namespace webcrypto {
122 // Each key maintains a copy of its serialized form
123 // in either 'raw', 'pkcs8', or 'spki' format. This is to allow
124 // structured cloning of keys synchronously from the target Blink
125 // thread without having to lock access to the key.
127 // TODO(eroman): Take advantage of this for implementing exportKey(): no need
128 // to call into NSS if the serialized form already exists.
129 // http://crubg.com/366836
130 class SymKey : public Key {
132 static Status Create(crypto::ScopedPK11SymKey key, scoped_ptr<SymKey>* out) {
133 out->reset(new SymKey(key.Pass()));
134 return ExportKeyRaw(out->get(), &(*out)->serialized_key_);
137 PK11SymKey* key() { return key_.get(); }
139 virtual SymKey* AsSymKey() OVERRIDE { return this; }
140 virtual PublicKey* AsPublicKey() OVERRIDE { return NULL; }
141 virtual PrivateKey* AsPrivateKey() OVERRIDE { return NULL; }
143 virtual bool ThreadSafeSerializeForClone(
144 blink::WebVector<uint8>* key_data) OVERRIDE {
145 key_data->assign(Uint8VectorStart(serialized_key_), serialized_key_.size());
150 explicit SymKey(crypto::ScopedPK11SymKey key) : key_(key.Pass()) {}
152 crypto::ScopedPK11SymKey key_;
153 std::vector<uint8> serialized_key_;
155 DISALLOW_COPY_AND_ASSIGN(SymKey);
158 class PublicKey : public Key {
160 static Status Create(crypto::ScopedSECKEYPublicKey key,
161 scoped_ptr<PublicKey>* out) {
162 out->reset(new PublicKey(key.Pass()));
163 return ExportKeySpki(out->get(), &(*out)->serialized_key_);
166 SECKEYPublicKey* key() { return key_.get(); }
168 virtual SymKey* AsSymKey() OVERRIDE { return NULL; }
169 virtual PublicKey* AsPublicKey() OVERRIDE { return this; }
170 virtual PrivateKey* AsPrivateKey() OVERRIDE { return NULL; }
172 virtual bool ThreadSafeSerializeForClone(
173 blink::WebVector<uint8>* key_data) OVERRIDE {
174 key_data->assign(Uint8VectorStart(serialized_key_), serialized_key_.size());
179 explicit PublicKey(crypto::ScopedSECKEYPublicKey key) : key_(key.Pass()) {}
181 crypto::ScopedSECKEYPublicKey key_;
182 std::vector<uint8> serialized_key_;
184 DISALLOW_COPY_AND_ASSIGN(PublicKey);
187 class PrivateKey : public Key {
189 static Status Create(crypto::ScopedSECKEYPrivateKey key,
190 const blink::WebCryptoKeyAlgorithm& algorithm,
191 scoped_ptr<PrivateKey>* out) {
192 out->reset(new PrivateKey(key.Pass()));
193 return ExportKeyPkcs8(out->get(), algorithm, &(*out)->serialized_key_);
196 SECKEYPrivateKey* key() { return key_.get(); }
198 virtual SymKey* AsSymKey() OVERRIDE { return NULL; }
199 virtual PublicKey* AsPublicKey() OVERRIDE { return NULL; }
200 virtual PrivateKey* AsPrivateKey() OVERRIDE { return this; }
202 virtual bool ThreadSafeSerializeForClone(
203 blink::WebVector<uint8>* key_data) OVERRIDE {
204 key_data->assign(Uint8VectorStart(serialized_key_), serialized_key_.size());
209 explicit PrivateKey(crypto::ScopedSECKEYPrivateKey key) : key_(key.Pass()) {}
211 crypto::ScopedSECKEYPrivateKey key_;
212 std::vector<uint8> serialized_key_;
214 DISALLOW_COPY_AND_ASSIGN(PrivateKey);
219 // Creates a SECItem for the data in |buffer|. This does NOT make a copy, so
220 // |buffer| should outlive the SECItem.
221 SECItem MakeSECItemForBuffer(const CryptoData& buffer) {
224 // NSS requires non-const data even though it is just for input.
225 const_cast<unsigned char*>(buffer.bytes()), buffer.byte_length()};
229 HASH_HashType WebCryptoAlgorithmToNSSHashType(
230 blink::WebCryptoAlgorithmId algorithm) {
232 case blink::WebCryptoAlgorithmIdSha1:
234 case blink::WebCryptoAlgorithmIdSha256:
235 return HASH_AlgSHA256;
236 case blink::WebCryptoAlgorithmIdSha384:
237 return HASH_AlgSHA384;
238 case blink::WebCryptoAlgorithmIdSha512:
239 return HASH_AlgSHA512;
241 // Not a digest algorithm.
246 CK_MECHANISM_TYPE WebCryptoHashToHMACMechanism(
247 const blink::WebCryptoAlgorithm& algorithm) {
248 switch (algorithm.id()) {
249 case blink::WebCryptoAlgorithmIdSha1:
250 return CKM_SHA_1_HMAC;
251 case blink::WebCryptoAlgorithmIdSha256:
252 return CKM_SHA256_HMAC;
253 case blink::WebCryptoAlgorithmIdSha384:
254 return CKM_SHA384_HMAC;
255 case blink::WebCryptoAlgorithmIdSha512:
256 return CKM_SHA512_HMAC;
258 // Not a supported algorithm.
259 return CKM_INVALID_MECHANISM;
263 Status AesCbcEncryptDecrypt(EncryptOrDecrypt mode,
265 const CryptoData& iv,
266 const CryptoData& data,
267 std::vector<uint8>* buffer) {
268 CK_ATTRIBUTE_TYPE operation = (mode == ENCRYPT) ? CKA_ENCRYPT : CKA_DECRYPT;
270 SECItem iv_item = MakeSECItemForBuffer(iv);
272 crypto::ScopedSECItem param(PK11_ParamFromIV(CKM_AES_CBC_PAD, &iv_item));
274 return Status::OperationError();
276 crypto::ScopedPK11Context context(PK11_CreateContextBySymKey(
277 CKM_AES_CBC_PAD, operation, key->key(), param.get()));
280 return Status::OperationError();
282 // Oddly PK11_CipherOp takes input and output lengths as "int" rather than
283 // "unsigned int". Do some checks now to avoid integer overflowing.
284 if (data.byte_length() >= INT_MAX - AES_BLOCK_SIZE) {
285 // TODO(eroman): Handle this by chunking the input fed into NSS. Right now
286 // it doesn't make much difference since the one-shot API would end up
287 // blowing out the memory and crashing anyway.
288 return Status::ErrorDataTooLarge();
291 // PK11_CipherOp does an invalid memory access when given empty decryption
292 // input, or input which is not a multiple of the block size. See also
293 // https://bugzilla.mozilla.com/show_bug.cgi?id=921687.
294 if (operation == CKA_DECRYPT &&
295 (data.byte_length() == 0 || (data.byte_length() % AES_BLOCK_SIZE != 0))) {
296 return Status::OperationError();
299 // TODO(eroman): Refine the output buffer size. It can be computed exactly for
300 // encryption, and can be smaller for decryption.
301 unsigned int output_max_len = data.byte_length() + AES_BLOCK_SIZE;
302 CHECK_GT(output_max_len, data.byte_length());
304 buffer->resize(output_max_len);
306 unsigned char* buffer_data = Uint8VectorStart(buffer);
309 if (SECSuccess != PK11_CipherOp(context.get(),
314 data.byte_length())) {
315 return Status::OperationError();
318 unsigned int final_output_chunk_len;
319 if (SECSuccess != PK11_DigestFinal(context.get(),
320 buffer_data + output_len,
321 &final_output_chunk_len,
322 output_max_len - output_len)) {
323 return Status::OperationError();
326 buffer->resize(final_output_chunk_len + output_len);
327 return Status::Success();
330 // Helper to either encrypt or decrypt for AES-GCM. The result of encryption is
331 // the concatenation of the ciphertext and the authentication tag. Similarly,
332 // this is the expectation for the input to decryption.
333 Status AesGcmEncryptDecrypt(EncryptOrDecrypt mode,
335 const CryptoData& data,
336 const CryptoData& iv,
337 const CryptoData& additional_data,
338 unsigned int tag_length_bits,
339 std::vector<uint8>* buffer) {
340 if (!g_aes_gcm_support.Get().IsSupported())
341 return Status::ErrorUnsupported();
343 unsigned int tag_length_bytes = tag_length_bits / 8;
345 CK_GCM_PARAMS gcm_params = {0};
346 gcm_params.pIv = const_cast<unsigned char*>(iv.bytes());
347 gcm_params.ulIvLen = iv.byte_length();
349 gcm_params.pAAD = const_cast<unsigned char*>(additional_data.bytes());
350 gcm_params.ulAADLen = additional_data.byte_length();
352 gcm_params.ulTagBits = tag_length_bits;
355 param.type = siBuffer;
356 param.data = reinterpret_cast<unsigned char*>(&gcm_params);
357 param.len = sizeof(gcm_params);
359 unsigned int buffer_size = 0;
361 // Calculate the output buffer size.
362 if (mode == ENCRYPT) {
363 // TODO(eroman): This is ugly, abstract away the safe integer arithmetic.
364 if (data.byte_length() > (UINT_MAX - tag_length_bytes))
365 return Status::ErrorDataTooLarge();
366 buffer_size = data.byte_length() + tag_length_bytes;
368 // TODO(eroman): In theory the buffer allocated for the plain text should be
369 // sized as |data.byte_length() - tag_length_bytes|.
371 // However NSS has a bug whereby it will fail if the output buffer size is
372 // not at least as large as the ciphertext:
374 // https://bugzilla.mozilla.org/show_bug.cgi?id=%20853674
376 // From the analysis of that bug it looks like it might be safe to pass a
377 // correctly sized buffer but lie about its size. Since resizing the
378 // WebCryptoArrayBuffer is expensive that hack may be worth looking into.
379 buffer_size = data.byte_length();
382 buffer->resize(buffer_size);
383 unsigned char* buffer_data = Uint8VectorStart(buffer);
385 PK11_EncryptDecryptFunction func =
386 (mode == ENCRYPT) ? g_aes_gcm_support.Get().pk11_encrypt_func()
387 : g_aes_gcm_support.Get().pk11_decrypt_func();
389 unsigned int output_len = 0;
390 SECStatus result = func(key->key(),
399 if (result != SECSuccess)
400 return Status::OperationError();
402 // Unfortunately the buffer needs to be shrunk for decryption (see the NSS bug
404 buffer->resize(output_len);
406 return Status::Success();
409 CK_MECHANISM_TYPE WebCryptoAlgorithmToGenMechanism(
410 const blink::WebCryptoAlgorithm& algorithm) {
411 switch (algorithm.id()) {
412 case blink::WebCryptoAlgorithmIdAesCbc:
413 case blink::WebCryptoAlgorithmIdAesGcm:
414 case blink::WebCryptoAlgorithmIdAesKw:
415 return CKM_AES_KEY_GEN;
416 case blink::WebCryptoAlgorithmIdHmac:
417 return WebCryptoHashToHMACMechanism(algorithm.hmacKeyGenParams()->hash());
419 return CKM_INVALID_MECHANISM;
423 // Converts a (big-endian) WebCrypto BigInteger, with or without leading zeros,
425 bool BigIntegerToLong(const uint8* data,
426 unsigned int data_size,
427 unsigned long* result) {
428 // TODO(padolph): Is it correct to say that empty data is an error, or does it
429 // mean value 0? See https://www.w3.org/Bugs/Public/show_bug.cgi?id=23655
434 for (size_t i = 0; i < data_size; ++i) {
435 size_t reverse_i = data_size - i - 1;
437 if (reverse_i >= sizeof(unsigned long) && data[i])
438 return false; // Too large for a long.
440 *result |= data[i] << 8 * reverse_i;
445 bool IsAlgorithmRsa(const blink::WebCryptoAlgorithm& algorithm) {
446 return algorithm.id() == blink::WebCryptoAlgorithmIdRsaEsPkcs1v1_5 ||
447 algorithm.id() == blink::WebCryptoAlgorithmIdRsaOaep ||
448 algorithm.id() == blink::WebCryptoAlgorithmIdRsaSsaPkcs1v1_5;
451 bool CreatePublicKeyAlgorithm(const blink::WebCryptoAlgorithm& algorithm,
452 SECKEYPublicKey* key,
453 blink::WebCryptoKeyAlgorithm* key_algorithm) {
454 // TODO(eroman): What about other key types rsaPss, rsaOaep.
455 if (!key || key->keyType != rsaKey)
458 unsigned int modulus_length_bits = SECKEY_PublicKeyStrength(key) * 8;
459 CryptoData public_exponent(key->u.rsa.publicExponent.data,
460 key->u.rsa.publicExponent.len);
462 switch (algorithm.paramsType()) {
463 case blink::WebCryptoAlgorithmParamsTypeRsaHashedImportParams:
464 case blink::WebCryptoAlgorithmParamsTypeRsaHashedKeyGenParams:
465 *key_algorithm = blink::WebCryptoKeyAlgorithm::createRsaHashed(
468 public_exponent.bytes(),
469 public_exponent.byte_length(),
470 GetInnerHashAlgorithm(algorithm).id());
472 case blink::WebCryptoAlgorithmParamsTypeRsaKeyGenParams:
473 case blink::WebCryptoAlgorithmParamsTypeNone:
474 *key_algorithm = blink::WebCryptoKeyAlgorithm::createRsa(
477 public_exponent.bytes(),
478 public_exponent.byte_length());
485 bool CreatePrivateKeyAlgorithm(const blink::WebCryptoAlgorithm& algorithm,
486 SECKEYPrivateKey* key,
487 blink::WebCryptoKeyAlgorithm* key_algorithm) {
488 crypto::ScopedSECKEYPublicKey public_key(SECKEY_ConvertToPublicKey(key));
489 return CreatePublicKeyAlgorithm(algorithm, public_key.get(), key_algorithm);
492 // The Default IV for AES-KW. See http://www.ietf.org/rfc/rfc3394.txt
494 // TODO(padolph): Move to common place to be shared with OpenSSL implementation.
495 const unsigned char kAesIv[] = {0xA6, 0xA6, 0xA6, 0xA6, 0xA6, 0xA6, 0xA6, 0xA6};
497 // Sets NSS CK_MECHANISM_TYPE and CK_FLAGS corresponding to the input Web Crypto
499 Status WebCryptoAlgorithmToNssMechFlags(
500 const blink::WebCryptoAlgorithm& algorithm,
501 CK_MECHANISM_TYPE* mechanism,
503 // Flags are verified at the Blink layer; here the flags are set to all
504 // possible operations of a key for the input algorithm type.
505 switch (algorithm.id()) {
506 case blink::WebCryptoAlgorithmIdHmac: {
507 const blink::WebCryptoAlgorithm hash = GetInnerHashAlgorithm(algorithm);
508 *mechanism = WebCryptoHashToHMACMechanism(hash);
509 if (*mechanism == CKM_INVALID_MECHANISM)
510 return Status::ErrorUnsupported();
511 *flags = CKF_SIGN | CKF_VERIFY;
514 case blink::WebCryptoAlgorithmIdAesCbc: {
515 *mechanism = CKM_AES_CBC;
516 *flags = CKF_ENCRYPT | CKF_DECRYPT;
519 case blink::WebCryptoAlgorithmIdAesKw: {
520 *mechanism = CKM_NSS_AES_KEY_WRAP;
521 *flags = CKF_WRAP | CKF_WRAP;
524 case blink::WebCryptoAlgorithmIdAesGcm: {
525 if (!g_aes_gcm_support.Get().IsSupported())
526 return Status::ErrorUnsupported();
527 *mechanism = CKM_AES_GCM;
528 *flags = CKF_ENCRYPT | CKF_DECRYPT;
532 return Status::ErrorUnsupported();
534 return Status::Success();
537 Status DoUnwrapSymKeyAesKw(const CryptoData& wrapped_key_data,
538 SymKey* wrapping_key,
539 CK_MECHANISM_TYPE mechanism,
541 crypto::ScopedPK11SymKey* unwrapped_key) {
542 DCHECK_GE(wrapped_key_data.byte_length(), 24u);
543 DCHECK_EQ(wrapped_key_data.byte_length() % 8, 0u);
545 SECItem iv_item = MakeSECItemForBuffer(CryptoData(kAesIv, sizeof(kAesIv)));
546 crypto::ScopedSECItem param_item(
547 PK11_ParamFromIV(CKM_NSS_AES_KEY_WRAP, &iv_item));
549 return Status::ErrorUnexpected();
551 SECItem cipher_text = MakeSECItemForBuffer(wrapped_key_data);
553 // The plaintext length is always 64 bits less than the data size.
554 const unsigned int plaintext_length = wrapped_key_data.byte_length() - 8;
557 // Part of workaround for
558 // https://bugzilla.mozilla.org/show_bug.cgi?id=981170. See the explanation
559 // later in this function.
563 crypto::ScopedPK11SymKey new_key(
564 PK11_UnwrapSymKeyWithFlags(wrapping_key->key(),
565 CKM_NSS_AES_KEY_WRAP,
573 // TODO(padolph): Use NSS PORT_GetError() and friends to report a more
574 // accurate error, providing if doesn't leak any information to web pages
575 // about other web crypto users, key details, etc.
577 return Status::OperationError();
580 // Workaround for https://bugzilla.mozilla.org/show_bug.cgi?id=981170
581 // which was fixed in NSS 3.16.0.
582 // If unwrap fails, NSS nevertheless returns a valid-looking PK11SymKey,
583 // with a reasonable length but with key data pointing to uninitialized
585 // To understand this workaround see the fix for 981170:
586 // https://hg.mozilla.org/projects/nss/rev/753bb69e543c
587 if (!NSS_VersionCheck("3.16") && PORT_GetError() == SEC_ERROR_BAD_DATA)
588 return Status::OperationError();
591 *unwrapped_key = new_key.Pass();
592 return Status::Success();
595 void CopySECItemToVector(const SECItem& item, std::vector<uint8>* out) {
596 out->assign(item.data, item.data + item.len);
599 // The system NSS library doesn't have the new PK11_ExportDERPrivateKeyInfo
600 // function yet (https://bugzilla.mozilla.org/show_bug.cgi?id=519255). So we
601 // provide a fallback implementation.
603 // From PKCS#1 [http://tools.ietf.org/html/rfc3447]:
605 // RSAPrivateKey ::= SEQUENCE {
607 // modulus INTEGER, -- n
608 // publicExponent INTEGER, -- e
609 // privateExponent INTEGER, -- d
610 // prime1 INTEGER, -- p
611 // prime2 INTEGER, -- q
612 // exponent1 INTEGER, -- d mod (p-1)
613 // exponent2 INTEGER, -- d mod (q-1)
614 // coefficient INTEGER, -- (inverse of q) mod p
615 // otherPrimeInfos OtherPrimeInfos OPTIONAL
618 // Note that otherPrimeInfos is only applicable for version=1. Since NSS
619 // doesn't use multi-prime can safely use version=0.
620 struct RSAPrivateKey {
623 SECItem public_exponent;
624 SECItem private_exponent;
632 const SEC_ASN1Template RSAPrivateKeyTemplate[] = {
633 {SEC_ASN1_SEQUENCE, 0, NULL, sizeof(RSAPrivateKey)},
634 {SEC_ASN1_INTEGER, offsetof(RSAPrivateKey, version)},
635 {SEC_ASN1_INTEGER, offsetof(RSAPrivateKey, modulus)},
636 {SEC_ASN1_INTEGER, offsetof(RSAPrivateKey, public_exponent)},
637 {SEC_ASN1_INTEGER, offsetof(RSAPrivateKey, private_exponent)},
638 {SEC_ASN1_INTEGER, offsetof(RSAPrivateKey, prime1)},
639 {SEC_ASN1_INTEGER, offsetof(RSAPrivateKey, prime2)},
640 {SEC_ASN1_INTEGER, offsetof(RSAPrivateKey, exponent1)},
641 {SEC_ASN1_INTEGER, offsetof(RSAPrivateKey, exponent2)},
642 {SEC_ASN1_INTEGER, offsetof(RSAPrivateKey, coefficient)},
645 // On success |value| will be filled with data which must be freed by
646 // SECITEM_FreeItem(value, PR_FALSE);
647 bool ReadUint(SECKEYPrivateKey* key,
648 CK_ATTRIBUTE_TYPE attribute,
650 SECStatus rv = PK11_ReadRawAttribute(PK11_TypePrivKey, key, attribute, value);
652 // PK11_ReadRawAttribute() returns items of type siBuffer. However in order
653 // for the ASN.1 encoding to be correct, the items must be of type
654 // siUnsignedInteger.
655 value->type = siUnsignedInteger;
657 return rv == SECSuccess;
660 // Fills |out| with the RSA private key properties. Returns true on success.
661 // Regardless of the return value, the caller must invoke FreeRSAPrivateKey()
662 // to free up any allocated memory.
664 // The passed in RSAPrivateKey must be zero-initialized.
665 bool InitRSAPrivateKey(SECKEYPrivateKey* key, RSAPrivateKey* out) {
666 if (key->keyType != rsaKey)
669 // Everything should be zero-ed out. These are just some spot checks.
670 DCHECK(!out->version.data);
671 DCHECK(!out->version.len);
672 DCHECK(!out->modulus.data);
673 DCHECK(!out->modulus.len);
675 // Always use version=0 since not using multi-prime.
676 if (!SEC_ASN1EncodeInteger(NULL, &out->version, 0))
679 if (!ReadUint(key, CKA_MODULUS, &out->modulus))
681 if (!ReadUint(key, CKA_PUBLIC_EXPONENT, &out->public_exponent))
683 if (!ReadUint(key, CKA_PRIVATE_EXPONENT, &out->private_exponent))
685 if (!ReadUint(key, CKA_PRIME_1, &out->prime1))
687 if (!ReadUint(key, CKA_PRIME_2, &out->prime2))
689 if (!ReadUint(key, CKA_EXPONENT_1, &out->exponent1))
691 if (!ReadUint(key, CKA_EXPONENT_2, &out->exponent2))
693 if (!ReadUint(key, CKA_COEFFICIENT, &out->coefficient))
699 struct FreeRsaPrivateKey {
700 void operator()(RSAPrivateKey* out) {
701 SECITEM_FreeItem(&out->version, PR_FALSE);
702 SECITEM_FreeItem(&out->modulus, PR_FALSE);
703 SECITEM_FreeItem(&out->public_exponent, PR_FALSE);
704 SECITEM_FreeItem(&out->private_exponent, PR_FALSE);
705 SECITEM_FreeItem(&out->prime1, PR_FALSE);
706 SECITEM_FreeItem(&out->prime2, PR_FALSE);
707 SECITEM_FreeItem(&out->exponent1, PR_FALSE);
708 SECITEM_FreeItem(&out->exponent2, PR_FALSE);
709 SECITEM_FreeItem(&out->coefficient, PR_FALSE);
712 #endif // defined(USE_NSS)
716 class DigestorNSS : public blink::WebCryptoDigestor {
718 explicit DigestorNSS(blink::WebCryptoAlgorithmId algorithm_id)
719 : hash_context_(NULL), algorithm_id_(algorithm_id) {}
721 virtual ~DigestorNSS() {
725 HASH_Destroy(hash_context_);
726 hash_context_ = NULL;
729 virtual bool consume(const unsigned char* data, unsigned int size) {
730 return ConsumeWithStatus(data, size).IsSuccess();
733 Status ConsumeWithStatus(const unsigned char* data, unsigned int size) {
734 // Initialize everything if the object hasn't been initialized yet.
735 if (!hash_context_) {
736 Status error = Init();
737 if (!error.IsSuccess())
741 HASH_Update(hash_context_, data, size);
743 return Status::Success();
746 virtual bool finish(unsigned char*& result_data,
747 unsigned int& result_data_size) {
748 Status error = FinishInternal(result_, &result_data_size);
749 if (!error.IsSuccess())
751 result_data = result_;
755 Status FinishWithVectorAndStatus(std::vector<uint8>* result) {
757 return Status::ErrorUnexpected();
759 unsigned int result_length = HASH_ResultLenContext(hash_context_);
760 result->resize(result_length);
761 unsigned char* digest = Uint8VectorStart(result);
762 unsigned int digest_size; // ignored
763 return FinishInternal(digest, &digest_size);
768 HASH_HashType hash_type = WebCryptoAlgorithmToNSSHashType(algorithm_id_);
770 if (hash_type == HASH_AlgNULL)
771 return Status::ErrorUnsupported();
773 hash_context_ = HASH_Create(hash_type);
775 return Status::OperationError();
777 HASH_Begin(hash_context_);
779 return Status::Success();
782 Status FinishInternal(unsigned char* result, unsigned int* result_size) {
783 if (!hash_context_) {
784 Status error = Init();
785 if (!error.IsSuccess())
789 unsigned int hash_result_length = HASH_ResultLenContext(hash_context_);
790 DCHECK_LE(hash_result_length, static_cast<size_t>(HASH_LENGTH_MAX));
792 HASH_End(hash_context_, result, result_size, hash_result_length);
794 if (*result_size != hash_result_length)
795 return Status::ErrorUnexpected();
796 return Status::Success();
799 HASHContext* hash_context_;
800 blink::WebCryptoAlgorithmId algorithm_id_;
801 unsigned char result_[HASH_LENGTH_MAX];
804 Status ImportKeyRaw(const blink::WebCryptoAlgorithm& algorithm,
805 const CryptoData& key_data,
807 blink::WebCryptoKeyUsageMask usage_mask,
808 blink::WebCryptoKey* key) {
809 DCHECK(!algorithm.isNull());
811 CK_MECHANISM_TYPE mechanism;
814 WebCryptoAlgorithmToNssMechFlags(algorithm, &mechanism, &flags);
815 if (status.IsError())
818 SECItem key_item = MakeSECItemForBuffer(key_data);
820 crypto::ScopedPK11Slot slot(PK11_GetInternalSlot());
821 crypto::ScopedPK11SymKey pk11_sym_key(
822 PK11_ImportSymKeyWithFlags(slot.get(),
830 if (!pk11_sym_key.get())
831 return Status::OperationError();
833 blink::WebCryptoKeyAlgorithm key_algorithm;
834 if (!CreateSecretKeyAlgorithm(
835 algorithm, key_data.byte_length(), &key_algorithm))
836 return Status::ErrorUnexpected();
838 scoped_ptr<SymKey> key_handle;
839 status = SymKey::Create(pk11_sym_key.Pass(), &key_handle);
840 if (status.IsError())
843 *key = blink::WebCryptoKey::create(key_handle.release(),
844 blink::WebCryptoKeyTypeSecret,
848 return Status::Success();
851 Status ExportKeyRaw(SymKey* key, std::vector<uint8>* buffer) {
852 if (PK11_ExtractKeyValue(key->key()) != SECSuccess)
853 return Status::OperationError();
855 // http://crbug.com/366427: the spec does not define any other failures for
856 // exporting, so none of the subsequent errors are spec compliant.
857 const SECItem* key_data = PK11_GetKeyData(key->key());
859 return Status::OperationError();
861 buffer->assign(key_data->data, key_data->data + key_data->len);
863 return Status::Success();
868 typedef scoped_ptr<CERTSubjectPublicKeyInfo,
869 crypto::NSSDestroyer<CERTSubjectPublicKeyInfo,
870 SECKEY_DestroySubjectPublicKeyInfo> >
871 ScopedCERTSubjectPublicKeyInfo;
873 // Validates an NSS KeyType against a WebCrypto import algorithm.
874 bool ValidateNssKeyTypeAgainstInputAlgorithm(
876 const blink::WebCryptoAlgorithm& algorithm) {
879 return IsAlgorithmRsa(algorithm);
884 // TODO(padolph): Handle other key types.
894 Status ImportKeySpki(const blink::WebCryptoAlgorithm& algorithm,
895 const CryptoData& key_data,
897 blink::WebCryptoKeyUsageMask usage_mask,
898 blink::WebCryptoKey* key) {
901 if (!key_data.byte_length())
902 return Status::ErrorImportEmptyKeyData();
903 DCHECK(key_data.bytes());
905 // The binary blob 'key_data' is expected to be a DER-encoded ASN.1 Subject
906 // Public Key Info. Decode this to a CERTSubjectPublicKeyInfo.
907 SECItem spki_item = MakeSECItemForBuffer(key_data);
908 const ScopedCERTSubjectPublicKeyInfo spki(
909 SECKEY_DecodeDERSubjectPublicKeyInfo(&spki_item));
911 return Status::DataError();
913 crypto::ScopedSECKEYPublicKey sec_public_key(
914 SECKEY_ExtractPublicKey(spki.get()));
916 return Status::DataError();
918 const KeyType sec_key_type = SECKEY_GetPublicKeyType(sec_public_key.get());
919 if (!ValidateNssKeyTypeAgainstInputAlgorithm(sec_key_type, algorithm))
920 return Status::DataError();
922 blink::WebCryptoKeyAlgorithm key_algorithm;
923 if (!CreatePublicKeyAlgorithm(
924 algorithm, sec_public_key.get(), &key_algorithm))
925 return Status::ErrorUnexpected();
927 scoped_ptr<PublicKey> key_handle;
928 Status status = PublicKey::Create(sec_public_key.Pass(), &key_handle);
929 if (status.IsError())
932 *key = blink::WebCryptoKey::create(key_handle.release(),
933 blink::WebCryptoKeyTypePublic,
938 return Status::Success();
941 Status ExportKeySpki(PublicKey* key, std::vector<uint8>* buffer) {
942 const crypto::ScopedSECItem spki_der(
943 SECKEY_EncodeDERSubjectPublicKeyInfo(key->key()));
944 // http://crbug.com/366427: the spec does not define any other failures for
945 // exporting, so none of the subsequent errors are spec compliant.
947 return Status::OperationError();
949 DCHECK(spki_der->data);
950 DCHECK(spki_der->len);
952 buffer->assign(spki_der->data, spki_der->data + spki_der->len);
954 return Status::Success();
957 Status ExportRsaPublicKey(PublicKey* key,
958 std::vector<uint8>* modulus,
959 std::vector<uint8>* public_exponent) {
962 if (key->key()->keyType != rsaKey)
963 return Status::ErrorUnsupported();
964 CopySECItemToVector(key->key()->u.rsa.modulus, modulus);
965 CopySECItemToVector(key->key()->u.rsa.publicExponent, public_exponent);
966 if (modulus->empty() || public_exponent->empty())
967 return Status::ErrorUnexpected();
968 return Status::Success();
971 Status ExportKeyPkcs8(PrivateKey* key,
972 const blink::WebCryptoKeyAlgorithm& key_algorithm,
973 std::vector<uint8>* buffer) {
974 // TODO(eroman): Support other RSA key types as they are added to Blink.
975 if (key_algorithm.id() != blink::WebCryptoAlgorithmIdRsaEsPkcs1v1_5 &&
976 key_algorithm.id() != blink::WebCryptoAlgorithmIdRsaSsaPkcs1v1_5)
977 return Status::ErrorUnsupported();
980 // PK11_ExportDERPrivateKeyInfo isn't available. Use our fallback code.
981 const SECOidTag algorithm = SEC_OID_PKCS1_RSA_ENCRYPTION;
982 const int kPrivateKeyInfoVersion = 0;
984 SECKEYPrivateKeyInfo private_key_info = {};
985 RSAPrivateKey rsa_private_key = {};
986 scoped_ptr<RSAPrivateKey, FreeRsaPrivateKey> free_private_key(
989 // http://crbug.com/366427: the spec does not define any other failures for
990 // exporting, so none of the subsequent errors are spec compliant.
991 if (!InitRSAPrivateKey(key->key(), &rsa_private_key))
992 return Status::OperationError();
994 crypto::ScopedPLArenaPool arena(PORT_NewArena(DER_DEFAULT_CHUNKSIZE));
996 return Status::OperationError();
998 if (!SEC_ASN1EncodeItem(arena.get(),
999 &private_key_info.privateKey,
1001 RSAPrivateKeyTemplate))
1002 return Status::OperationError();
1005 SECOID_SetAlgorithmID(
1006 arena.get(), &private_key_info.algorithm, algorithm, NULL))
1007 return Status::OperationError();
1009 if (!SEC_ASN1EncodeInteger(
1010 arena.get(), &private_key_info.version, kPrivateKeyInfoVersion))
1011 return Status::OperationError();
1013 crypto::ScopedSECItem encoded_key(
1014 SEC_ASN1EncodeItem(NULL,
1017 SEC_ASN1_GET(SECKEY_PrivateKeyInfoTemplate)));
1018 #else // defined(USE_NSS)
1019 crypto::ScopedSECItem encoded_key(
1020 PK11_ExportDERPrivateKeyInfo(key->key(), NULL));
1021 #endif // defined(USE_NSS)
1023 if (!encoded_key.get())
1024 return Status::OperationError();
1026 buffer->assign(encoded_key->data, encoded_key->data + encoded_key->len);
1027 return Status::Success();
1030 Status ImportKeyPkcs8(const blink::WebCryptoAlgorithm& algorithm,
1031 const CryptoData& key_data,
1033 blink::WebCryptoKeyUsageMask usage_mask,
1034 blink::WebCryptoKey* key) {
1037 if (!key_data.byte_length())
1038 return Status::ErrorImportEmptyKeyData();
1039 DCHECK(key_data.bytes());
1041 // The binary blob 'key_data' is expected to be a DER-encoded ASN.1 PKCS#8
1042 // private key info object.
1043 SECItem pki_der = MakeSECItemForBuffer(key_data);
1045 SECKEYPrivateKey* seckey_private_key = NULL;
1046 crypto::ScopedPK11Slot slot(PK11_GetInternalSlot());
1047 if (PK11_ImportDERPrivateKeyInfoAndReturnKey(slot.get(),
1050 NULL, // publicValue
1054 &seckey_private_key,
1055 NULL) != SECSuccess) {
1056 return Status::DataError();
1058 DCHECK(seckey_private_key);
1059 crypto::ScopedSECKEYPrivateKey private_key(seckey_private_key);
1061 const KeyType sec_key_type = SECKEY_GetPrivateKeyType(private_key.get());
1062 if (!ValidateNssKeyTypeAgainstInputAlgorithm(sec_key_type, algorithm))
1063 return Status::DataError();
1065 blink::WebCryptoKeyAlgorithm key_algorithm;
1066 if (!CreatePrivateKeyAlgorithm(algorithm, private_key.get(), &key_algorithm))
1067 return Status::ErrorUnexpected();
1069 scoped_ptr<PrivateKey> key_handle;
1071 PrivateKey::Create(private_key.Pass(), key_algorithm, &key_handle);
1072 if (status.IsError())
1075 *key = blink::WebCryptoKey::create(key_handle.release(),
1076 blink::WebCryptoKeyTypePrivate,
1081 return Status::Success();
1084 // -----------------------------------
1086 // -----------------------------------
1088 Status SignHmac(SymKey* key,
1089 const blink::WebCryptoAlgorithm& hash,
1090 const CryptoData& data,
1091 std::vector<uint8>* buffer) {
1092 DCHECK_EQ(PK11_GetMechanism(key->key()), WebCryptoHashToHMACMechanism(hash));
1094 SECItem param_item = {siBuffer, NULL, 0};
1095 SECItem data_item = MakeSECItemForBuffer(data);
1096 // First call is to figure out the length.
1097 SECItem signature_item = {siBuffer, NULL, 0};
1099 if (PK11_SignWithSymKey(key->key(),
1100 PK11_GetMechanism(key->key()),
1103 &data_item) != SECSuccess) {
1104 return Status::OperationError();
1107 DCHECK_NE(0u, signature_item.len);
1109 buffer->resize(signature_item.len);
1110 signature_item.data = Uint8VectorStart(buffer);
1112 if (PK11_SignWithSymKey(key->key(),
1113 PK11_GetMechanism(key->key()),
1116 &data_item) != SECSuccess) {
1117 return Status::OperationError();
1120 DCHECK_EQ(buffer->size(), signature_item.len);
1121 return Status::Success();
1124 // -----------------------------------
1126 // -----------------------------------
1128 Status EncryptRsaEsPkcs1v1_5(PublicKey* key,
1129 const CryptoData& data,
1130 std::vector<uint8>* buffer) {
1131 const unsigned int encrypted_length_bytes =
1132 SECKEY_PublicKeyStrength(key->key());
1134 // RSAES can operate on messages up to a length of k - 11, where k is the
1135 // octet length of the RSA modulus.
1136 if (encrypted_length_bytes < 11 ||
1137 encrypted_length_bytes - 11 < data.byte_length())
1138 return Status::ErrorDataTooLarge();
1140 buffer->resize(encrypted_length_bytes);
1141 unsigned char* const buffer_data = Uint8VectorStart(buffer);
1143 if (PK11_PubEncryptPKCS1(key->key(),
1145 const_cast<unsigned char*>(data.bytes()),
1147 NULL) != SECSuccess) {
1148 return Status::OperationError();
1150 return Status::Success();
1153 Status DecryptRsaEsPkcs1v1_5(PrivateKey* key,
1154 const CryptoData& data,
1155 std::vector<uint8>* buffer) {
1156 const int modulus_length_bytes = PK11_GetPrivateModulusLen(key->key());
1157 if (modulus_length_bytes <= 0)
1158 return Status::ErrorUnexpected();
1159 const unsigned int max_output_length_bytes = modulus_length_bytes;
1161 buffer->resize(max_output_length_bytes);
1162 unsigned char* const buffer_data = Uint8VectorStart(buffer);
1164 unsigned int output_length_bytes = 0;
1165 if (PK11_PrivDecryptPKCS1(key->key(),
1167 &output_length_bytes,
1168 max_output_length_bytes,
1169 const_cast<unsigned char*>(data.bytes()),
1170 data.byte_length()) != SECSuccess) {
1171 return Status::OperationError();
1173 DCHECK_LE(output_length_bytes, max_output_length_bytes);
1174 buffer->resize(output_length_bytes);
1175 return Status::Success();
1178 // -----------------------------------
1180 // -----------------------------------
1182 Status SignRsaSsaPkcs1v1_5(PrivateKey* key,
1183 const blink::WebCryptoAlgorithm& hash,
1184 const CryptoData& data,
1185 std::vector<uint8>* buffer) {
1186 // Pick the NSS signing algorithm by combining RSA-SSA (RSA PKCS1) and the
1187 // inner hash of the input Web Crypto algorithm.
1188 SECOidTag sign_alg_tag;
1189 switch (hash.id()) {
1190 case blink::WebCryptoAlgorithmIdSha1:
1191 sign_alg_tag = SEC_OID_PKCS1_SHA1_WITH_RSA_ENCRYPTION;
1193 case blink::WebCryptoAlgorithmIdSha256:
1194 sign_alg_tag = SEC_OID_PKCS1_SHA256_WITH_RSA_ENCRYPTION;
1196 case blink::WebCryptoAlgorithmIdSha384:
1197 sign_alg_tag = SEC_OID_PKCS1_SHA384_WITH_RSA_ENCRYPTION;
1199 case blink::WebCryptoAlgorithmIdSha512:
1200 sign_alg_tag = SEC_OID_PKCS1_SHA512_WITH_RSA_ENCRYPTION;
1203 return Status::ErrorUnsupported();
1206 crypto::ScopedSECItem signature_item(SECITEM_AllocItem(NULL, NULL, 0));
1207 if (SEC_SignData(signature_item.get(),
1211 sign_alg_tag) != SECSuccess) {
1212 return Status::OperationError();
1215 buffer->assign(signature_item->data,
1216 signature_item->data + signature_item->len);
1217 return Status::Success();
1220 Status VerifyRsaSsaPkcs1v1_5(PublicKey* key,
1221 const blink::WebCryptoAlgorithm& hash,
1222 const CryptoData& signature,
1223 const CryptoData& data,
1224 bool* signature_match) {
1225 const SECItem signature_item = MakeSECItemForBuffer(signature);
1227 SECOidTag hash_alg_tag;
1228 switch (hash.id()) {
1229 case blink::WebCryptoAlgorithmIdSha1:
1230 hash_alg_tag = SEC_OID_SHA1;
1232 case blink::WebCryptoAlgorithmIdSha256:
1233 hash_alg_tag = SEC_OID_SHA256;
1235 case blink::WebCryptoAlgorithmIdSha384:
1236 hash_alg_tag = SEC_OID_SHA384;
1238 case blink::WebCryptoAlgorithmIdSha512:
1239 hash_alg_tag = SEC_OID_SHA512;
1242 return Status::ErrorUnsupported();
1246 SECSuccess == VFY_VerifyDataDirect(data.bytes(),
1250 SEC_OID_PKCS1_RSA_ENCRYPTION,
1254 return Status::Success();
1257 Status EncryptDecryptAesCbc(EncryptOrDecrypt mode,
1259 const CryptoData& data,
1260 const CryptoData& iv,
1261 std::vector<uint8>* buffer) {
1262 // TODO(eroman): Inline.
1263 return AesCbcEncryptDecrypt(mode, key, iv, data, buffer);
1266 Status EncryptDecryptAesGcm(EncryptOrDecrypt mode,
1268 const CryptoData& data,
1269 const CryptoData& iv,
1270 const CryptoData& additional_data,
1271 unsigned int tag_length_bits,
1272 std::vector<uint8>* buffer) {
1273 // TODO(eroman): Inline.
1274 return AesGcmEncryptDecrypt(
1275 mode, key, data, iv, additional_data, tag_length_bits, buffer);
1278 // -----------------------------------
1280 // -----------------------------------
1282 Status GenerateRsaKeyPair(const blink::WebCryptoAlgorithm& algorithm,
1284 blink::WebCryptoKeyUsageMask usage_mask,
1285 unsigned int modulus_length_bits,
1286 const CryptoData& public_exponent,
1287 const blink::WebCryptoAlgorithm& hash_or_null,
1288 blink::WebCryptoKey* public_key,
1289 blink::WebCryptoKey* private_key) {
1290 crypto::ScopedPK11Slot slot(PK11_GetInternalKeySlot());
1292 return Status::OperationError();
1294 unsigned long public_exponent_long;
1295 if (!BigIntegerToLong(public_exponent.bytes(),
1296 public_exponent.byte_length(),
1297 &public_exponent_long) ||
1298 !public_exponent_long) {
1299 return Status::ErrorGenerateKeyPublicExponent();
1302 PK11RSAGenParams rsa_gen_params;
1303 rsa_gen_params.keySizeInBits = modulus_length_bits;
1304 rsa_gen_params.pe = public_exponent_long;
1306 // Flags are verified at the Blink layer; here the flags are set to all
1307 // possible operations for the given key type.
1308 CK_FLAGS operation_flags;
1309 switch (algorithm.id()) {
1310 case blink::WebCryptoAlgorithmIdRsaEsPkcs1v1_5:
1311 case blink::WebCryptoAlgorithmIdRsaOaep:
1312 operation_flags = CKF_ENCRYPT | CKF_DECRYPT | CKF_WRAP | CKF_UNWRAP;
1314 case blink::WebCryptoAlgorithmIdRsaSsaPkcs1v1_5:
1315 operation_flags = CKF_SIGN | CKF_VERIFY;
1319 return Status::ErrorUnexpected();
1321 const CK_FLAGS operation_flags_mask =
1322 CKF_ENCRYPT | CKF_DECRYPT | CKF_SIGN | CKF_VERIFY | CKF_WRAP | CKF_UNWRAP;
1324 // The private key must be marked as insensitive and extractable, otherwise it
1325 // cannot later be exported in unencrypted form or structured-cloned.
1326 const PK11AttrFlags attribute_flags =
1327 PK11_ATTR_INSENSITIVE | PK11_ATTR_EXTRACTABLE;
1329 // Note: NSS does not generate an sec_public_key if the call below fails,
1330 // so there is no danger of a leaked sec_public_key.
1331 SECKEYPublicKey* sec_public_key;
1332 crypto::ScopedSECKEYPrivateKey scoped_sec_private_key(
1333 PK11_GenerateKeyPairWithOpFlags(slot.get(),
1334 CKM_RSA_PKCS_KEY_PAIR_GEN,
1339 operation_flags_mask,
1342 return Status::OperationError();
1344 blink::WebCryptoKeyAlgorithm key_algorithm;
1345 if (!CreatePublicKeyAlgorithm(algorithm, sec_public_key, &key_algorithm))
1346 return Status::ErrorUnexpected();
1348 scoped_ptr<PublicKey> public_key_handle;
1349 Status status = PublicKey::Create(
1350 crypto::ScopedSECKEYPublicKey(sec_public_key), &public_key_handle);
1351 if (status.IsError())
1354 scoped_ptr<PrivateKey> private_key_handle;
1355 status = PrivateKey::Create(
1356 scoped_sec_private_key.Pass(), key_algorithm, &private_key_handle);
1357 if (status.IsError())
1360 *public_key = blink::WebCryptoKey::create(public_key_handle.release(),
1361 blink::WebCryptoKeyTypePublic,
1365 *private_key = blink::WebCryptoKey::create(private_key_handle.release(),
1366 blink::WebCryptoKeyTypePrivate,
1371 return Status::Success();
1375 crypto::EnsureNSSInit();
1378 Status DigestSha(blink::WebCryptoAlgorithmId algorithm,
1379 const CryptoData& data,
1380 std::vector<uint8>* buffer) {
1381 DigestorNSS digestor(algorithm);
1382 Status error = digestor.ConsumeWithStatus(data.bytes(), data.byte_length());
1383 // http://crbug.com/366427: the spec does not define any other failures for
1384 // digest, so none of the subsequent errors are spec compliant.
1385 if (!error.IsSuccess())
1387 return digestor.FinishWithVectorAndStatus(buffer);
1390 scoped_ptr<blink::WebCryptoDigestor> CreateDigestor(
1391 blink::WebCryptoAlgorithmId algorithm_id) {
1392 return scoped_ptr<blink::WebCryptoDigestor>(new DigestorNSS(algorithm_id));
1395 Status GenerateSecretKey(const blink::WebCryptoAlgorithm& algorithm,
1397 blink::WebCryptoKeyUsageMask usage_mask,
1398 unsigned keylen_bytes,
1399 blink::WebCryptoKey* key) {
1400 CK_MECHANISM_TYPE mech = WebCryptoAlgorithmToGenMechanism(algorithm);
1401 blink::WebCryptoKeyType key_type = blink::WebCryptoKeyTypeSecret;
1403 if (mech == CKM_INVALID_MECHANISM)
1404 return Status::ErrorUnsupported();
1406 crypto::ScopedPK11Slot slot(PK11_GetInternalKeySlot());
1408 return Status::OperationError();
1410 crypto::ScopedPK11SymKey pk11_key(
1411 PK11_KeyGen(slot.get(), mech, NULL, keylen_bytes, NULL));
1414 return Status::OperationError();
1416 blink::WebCryptoKeyAlgorithm key_algorithm;
1417 if (!CreateSecretKeyAlgorithm(algorithm, keylen_bytes, &key_algorithm))
1418 return Status::ErrorUnexpected();
1420 scoped_ptr<SymKey> key_handle;
1421 Status status = SymKey::Create(pk11_key.Pass(), &key_handle);
1422 if (status.IsError())
1425 *key = blink::WebCryptoKey::create(
1426 key_handle.release(), key_type, extractable, key_algorithm, usage_mask);
1427 return Status::Success();
1430 Status ImportRsaPublicKey(const blink::WebCryptoAlgorithm& algorithm,
1432 blink::WebCryptoKeyUsageMask usage_mask,
1433 const CryptoData& modulus_data,
1434 const CryptoData& exponent_data,
1435 blink::WebCryptoKey* key) {
1436 if (!modulus_data.byte_length())
1437 return Status::ErrorImportRsaEmptyModulus();
1439 if (!exponent_data.byte_length())
1440 return Status::ErrorImportRsaEmptyExponent();
1442 DCHECK(modulus_data.bytes());
1443 DCHECK(exponent_data.bytes());
1445 // NSS does not provide a way to create an RSA public key directly from the
1446 // modulus and exponent values, but it can import an DER-encoded ASN.1 blob
1447 // with these values and create the public key from that. The code below
1448 // follows the recommendation described in
1449 // https://developer.mozilla.org/en-US/docs/NSS/NSS_Tech_Notes/nss_tech_note7
1451 // Pack the input values into a struct compatible with NSS ASN.1 encoding, and
1452 // set up an ASN.1 encoder template for it.
1453 struct RsaPublicKeyData {
1457 const RsaPublicKeyData pubkey_in = {
1458 {siUnsignedInteger, const_cast<unsigned char*>(modulus_data.bytes()),
1459 modulus_data.byte_length()},
1460 {siUnsignedInteger, const_cast<unsigned char*>(exponent_data.bytes()),
1461 exponent_data.byte_length()}};
1462 const SEC_ASN1Template rsa_public_key_template[] = {
1463 {SEC_ASN1_SEQUENCE, 0, NULL, sizeof(RsaPublicKeyData)},
1464 {SEC_ASN1_INTEGER, offsetof(RsaPublicKeyData, modulus), },
1465 {SEC_ASN1_INTEGER, offsetof(RsaPublicKeyData, exponent), },
1468 // DER-encode the public key.
1469 crypto::ScopedSECItem pubkey_der(
1470 SEC_ASN1EncodeItem(NULL, NULL, &pubkey_in, rsa_public_key_template));
1472 return Status::OperationError();
1474 // Import the DER-encoded public key to create an RSA SECKEYPublicKey.
1475 crypto::ScopedSECKEYPublicKey pubkey(
1476 SECKEY_ImportDERPublicKey(pubkey_der.get(), CKK_RSA));
1478 return Status::OperationError();
1480 blink::WebCryptoKeyAlgorithm key_algorithm;
1481 if (!CreatePublicKeyAlgorithm(algorithm, pubkey.get(), &key_algorithm))
1482 return Status::ErrorUnexpected();
1484 scoped_ptr<PublicKey> key_handle;
1485 Status status = PublicKey::Create(pubkey.Pass(), &key_handle);
1486 if (status.IsError())
1489 *key = blink::WebCryptoKey::create(key_handle.release(),
1490 blink::WebCryptoKeyTypePublic,
1494 return Status::Success();
1497 Status WrapSymKeyAesKw(SymKey* wrapping_key,
1499 std::vector<uint8>* buffer) {
1500 // The data size must be at least 16 bytes and a multiple of 8 bytes.
1501 // RFC 3394 does not specify a maximum allowed data length, but since only
1502 // keys are being wrapped in this application (which are small), a reasonable
1503 // max limit is whatever will fit into an unsigned. For the max size test,
1504 // note that AES Key Wrap always adds 8 bytes to the input data size.
1505 const unsigned int input_length = PK11_GetKeyLength(key->key());
1506 if (input_length < 16)
1507 return Status::ErrorDataTooSmall();
1508 if (input_length > UINT_MAX - 8)
1509 return Status::ErrorDataTooLarge();
1510 if (input_length % 8)
1511 return Status::ErrorInvalidAesKwDataLength();
1513 SECItem iv_item = MakeSECItemForBuffer(CryptoData(kAesIv, sizeof(kAesIv)));
1514 crypto::ScopedSECItem param_item(
1515 PK11_ParamFromIV(CKM_NSS_AES_KEY_WRAP, &iv_item));
1517 return Status::ErrorUnexpected();
1519 const unsigned int output_length = input_length + 8;
1520 buffer->resize(output_length);
1521 SECItem wrapped_key_item = MakeSECItemForBuffer(CryptoData(*buffer));
1523 if (SECSuccess != PK11_WrapSymKey(CKM_NSS_AES_KEY_WRAP,
1525 wrapping_key->key(),
1527 &wrapped_key_item)) {
1528 return Status::OperationError();
1530 if (output_length != wrapped_key_item.len)
1531 return Status::ErrorUnexpected();
1533 return Status::Success();
1536 Status UnwrapSymKeyAesKw(const CryptoData& wrapped_key_data,
1537 SymKey* wrapping_key,
1538 const blink::WebCryptoAlgorithm& algorithm,
1540 blink::WebCryptoKeyUsageMask usage_mask,
1541 blink::WebCryptoKey* key) {
1542 // Determine the proper NSS key properties from the input algorithm.
1543 CK_MECHANISM_TYPE mechanism;
1546 WebCryptoAlgorithmToNssMechFlags(algorithm, &mechanism, &flags);
1547 if (status.IsError())
1550 crypto::ScopedPK11SymKey unwrapped_key;
1551 status = DoUnwrapSymKeyAesKw(
1552 wrapped_key_data, wrapping_key, mechanism, flags, &unwrapped_key);
1553 if (status.IsError())
1556 blink::WebCryptoKeyAlgorithm key_algorithm;
1557 if (!CreateSecretKeyAlgorithm(
1558 algorithm, PK11_GetKeyLength(unwrapped_key.get()), &key_algorithm))
1559 return Status::ErrorUnexpected();
1561 scoped_ptr<SymKey> key_handle;
1562 status = SymKey::Create(unwrapped_key.Pass(), &key_handle);
1563 if (status.IsError())
1566 *key = blink::WebCryptoKey::create(key_handle.release(),
1567 blink::WebCryptoKeyTypeSecret,
1571 return Status::Success();
1574 Status DecryptAesKw(SymKey* wrapping_key,
1575 const CryptoData& data,
1576 std::vector<uint8>* buffer) {
1577 // Due to limitations in the NSS API for the AES-KW algorithm, |data| must be
1578 // temporarily viewed as a symmetric key to be unwrapped (decrypted).
1579 crypto::ScopedPK11SymKey decrypted;
1580 Status status = DoUnwrapSymKeyAesKw(
1581 data, wrapping_key, CKK_GENERIC_SECRET, 0, &decrypted);
1582 if (status.IsError())
1585 // Once the decrypt is complete, extract the resultant raw bytes from NSS and
1586 // return them to the caller.
1587 if (PK11_ExtractKeyValue(decrypted.get()) != SECSuccess)
1588 return Status::OperationError();
1589 const SECItem* const key_data = PK11_GetKeyData(decrypted.get());
1591 return Status::OperationError();
1592 buffer->assign(key_data->data, key_data->data + key_data->len);
1594 return Status::Success();
1597 Status WrapSymKeyRsaEs(PublicKey* wrapping_key,
1599 std::vector<uint8>* buffer) {
1600 // Check the raw length of the key to be wrapped against the max size allowed
1601 // by the RSA wrapping key. With PKCS#1 v1.5 padding used in this function,
1602 // the maximum data length that can be encrypted is the wrapping_key's modulus
1603 // byte length minus eleven bytes.
1604 const unsigned int input_length_bytes = PK11_GetKeyLength(key->key());
1605 const unsigned int modulus_length_bytes =
1606 SECKEY_PublicKeyStrength(wrapping_key->key());
1607 if (modulus_length_bytes < 11 ||
1608 modulus_length_bytes - 11 < input_length_bytes)
1609 return Status::ErrorDataTooLarge();
1611 buffer->resize(modulus_length_bytes);
1612 SECItem wrapped_key_item = MakeSECItemForBuffer(CryptoData(*buffer));
1616 CKM_RSA_PKCS, wrapping_key->key(), key->key(), &wrapped_key_item)) {
1617 return Status::OperationError();
1619 if (wrapped_key_item.len != modulus_length_bytes)
1620 return Status::ErrorUnexpected();
1622 return Status::Success();
1625 Status UnwrapSymKeyRsaEs(const CryptoData& wrapped_key_data,
1626 PrivateKey* wrapping_key,
1627 const blink::WebCryptoAlgorithm& algorithm,
1629 blink::WebCryptoKeyUsageMask usage_mask,
1630 blink::WebCryptoKey* key) {
1631 // Verify wrapped_key_data size does not exceed the modulus of the RSA key.
1632 const int modulus_length_bytes =
1633 PK11_GetPrivateModulusLen(wrapping_key->key());
1634 if (modulus_length_bytes <= 0)
1635 return Status::ErrorUnexpected();
1636 if (wrapped_key_data.byte_length() >
1637 static_cast<unsigned int>(modulus_length_bytes))
1638 return Status::ErrorDataTooLarge();
1640 // Determine the proper NSS key properties from the input algorithm.
1641 CK_MECHANISM_TYPE mechanism;
1644 WebCryptoAlgorithmToNssMechFlags(algorithm, &mechanism, &flags);
1645 if (status.IsError())
1648 SECItem wrapped_key_item = MakeSECItemForBuffer(wrapped_key_data);
1650 crypto::ScopedPK11SymKey unwrapped_key(
1651 PK11_PubUnwrapSymKeyWithFlagsPerm(wrapping_key->key(),
1659 return Status::OperationError();
1661 const unsigned int key_length = PK11_GetKeyLength(unwrapped_key.get());
1663 blink::WebCryptoKeyAlgorithm key_algorithm;
1664 if (!CreateSecretKeyAlgorithm(algorithm, key_length, &key_algorithm))
1665 return Status::ErrorUnexpected();
1667 scoped_ptr<SymKey> key_handle;
1668 status = SymKey::Create(unwrapped_key.Pass(), &key_handle);
1669 if (status.IsError())
1672 *key = blink::WebCryptoKey::create(key_handle.release(),
1673 blink::WebCryptoKeyTypeSecret,
1677 return Status::Success();
1680 } // namespace platform
1682 } // namespace webcrypto
1684 } // namespace content