3586240376ae77c2286a483d729c3ee6c49a5f36
[platform/framework/web/crosswalk.git] / src / content / child / webcrypto / shared_crypto_unittest.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/shared_crypto.h"
6
7 #include <algorithm>
8 #include <string>
9 #include <vector>
10
11 #include "base/basictypes.h"
12 #include "base/file_util.h"
13 #include "base/json/json_reader.h"
14 #include "base/json/json_writer.h"
15 #include "base/logging.h"
16 #include "base/memory/ref_counted.h"
17 #include "base/path_service.h"
18 #include "base/strings/string_number_conversions.h"
19 #include "base/strings/string_util.h"
20 #include "base/strings/stringprintf.h"
21 #include "content/child/webcrypto/crypto_data.h"
22 #include "content/child/webcrypto/status.h"
23 #include "content/child/webcrypto/webcrypto_util.h"
24 #include "content/public/common/content_paths.h"
25 #include "testing/gtest/include/gtest/gtest.h"
26 #include "third_party/WebKit/public/platform/WebCryptoAlgorithm.h"
27 #include "third_party/WebKit/public/platform/WebCryptoAlgorithmParams.h"
28 #include "third_party/WebKit/public/platform/WebCryptoKey.h"
29 #include "third_party/WebKit/public/platform/WebCryptoKeyAlgorithm.h"
30 #include "third_party/re2/re2/re2.h"
31
32 #if !defined(USE_OPENSSL)
33 #include <nss.h>
34 #include <pk11pub.h>
35
36 #include "crypto/scoped_nss_types.h"
37 #endif
38
39 // The OpenSSL implementation of WebCrypto is less complete, so don't run all of
40 // the tests: http://crbug.com/267888
41 #if defined(USE_OPENSSL)
42 #define MAYBE(test_name) DISABLED_##test_name
43 #else
44 #define MAYBE(test_name) test_name
45 #endif
46
47 #define EXPECT_BYTES_EQ(expected, actual) \
48   EXPECT_EQ(CryptoData(expected), CryptoData(actual))
49
50 #define EXPECT_BYTES_EQ_HEX(expected_hex, actual_bytes) \
51   EXPECT_BYTES_EQ(HexStringToBytes(expected_hex), actual_bytes)
52
53 namespace content {
54
55 namespace webcrypto {
56
57 // These functions are used by GTEST to support EXPECT_EQ() for
58 // webcrypto::Status and webcrypto::CryptoData
59
60 void PrintTo(const Status& status, ::std::ostream* os) {
61   if (status.IsSuccess())
62     *os << "Success";
63   else
64     *os << "Error type: " << status.error_type()
65         << " Error details: " << status.error_details();
66 }
67
68 bool operator==(const content::webcrypto::Status& a,
69                 const content::webcrypto::Status& b) {
70   if (a.IsSuccess() != b.IsSuccess())
71     return false;
72   if (a.IsSuccess())
73     return true;
74   return a.error_type() == b.error_type() &&
75          a.error_details() == b.error_details();
76 }
77
78 bool operator!=(const content::webcrypto::Status& a,
79                 const content::webcrypto::Status& b) {
80   return !(a == b);
81 }
82
83 void PrintTo(const CryptoData& data, ::std::ostream* os) {
84   *os << "[" << base::HexEncode(data.bytes(), data.byte_length()) << "]";
85 }
86
87 bool operator==(const content::webcrypto::CryptoData& a,
88                 const content::webcrypto::CryptoData& b) {
89   return a.byte_length() == b.byte_length() &&
90          memcmp(a.bytes(), b.bytes(), a.byte_length()) == 0;
91 }
92
93 bool operator!=(const content::webcrypto::CryptoData& a,
94                 const content::webcrypto::CryptoData& b) {
95   return !(a == b);
96 }
97
98 namespace {
99
100 // -----------------------------------------------------------------------------
101
102 // TODO(eroman): For Linux builds using system NSS, AES-GCM support is a
103 // runtime dependency. Test it by trying to import a key.
104 // TODO(padolph): Consider caching the result of the import key test.
105 bool SupportsAesGcm() {
106   std::vector<uint8> key_raw(16, 0);
107
108   blink::WebCryptoKey key = blink::WebCryptoKey::createNull();
109   Status status = ImportKey(blink::WebCryptoKeyFormatRaw,
110                             CryptoData(key_raw),
111                             CreateAlgorithm(blink::WebCryptoAlgorithmIdAesGcm),
112                             true,
113                             blink::WebCryptoKeyUsageEncrypt,
114                             &key);
115
116   if (status.IsError())
117     EXPECT_EQ(blink::WebCryptoErrorTypeNotSupported, status.error_type());
118   return status.IsSuccess();
119 }
120
121 bool SupportsRsaOaep() {
122 #if defined(USE_OPENSSL)
123   return false;
124 #else
125   // TODO(eroman): Exclude version test for OS_CHROMEOS
126 #if defined(USE_NSS)
127   if (!NSS_VersionCheck("3.16.2"))
128     return false;
129 #endif
130   crypto::ScopedPK11Slot slot(PK11_GetInternalKeySlot());
131   return !!PK11_DoesMechanism(slot.get(), CKM_RSA_PKCS_OAEP);
132 #endif
133 }
134
135 bool SupportsRsaKeyImport() {
136 // TODO(eroman): Exclude version test for OS_CHROMEOS
137 #if defined(USE_NSS)
138   if (!NSS_VersionCheck("3.16.2")) {
139     LOG(WARNING) << "RSA key import is not supported by this version of NSS. "
140                     "Skipping some tests";
141     return false;
142   }
143 #endif
144   return true;
145 }
146
147 blink::WebCryptoAlgorithm CreateRsaHashedKeyGenAlgorithm(
148     blink::WebCryptoAlgorithmId algorithm_id,
149     const blink::WebCryptoAlgorithmId hash_id,
150     unsigned int modulus_length,
151     const std::vector<uint8>& public_exponent) {
152   DCHECK(algorithm_id == blink::WebCryptoAlgorithmIdRsaSsaPkcs1v1_5 ||
153          algorithm_id == blink::WebCryptoAlgorithmIdRsaOaep);
154   DCHECK(blink::WebCryptoAlgorithm::isHash(hash_id));
155   return blink::WebCryptoAlgorithm::adoptParamsAndCreate(
156       algorithm_id,
157       new blink::WebCryptoRsaHashedKeyGenParams(
158           CreateAlgorithm(hash_id),
159           modulus_length,
160           webcrypto::Uint8VectorStart(public_exponent),
161           public_exponent.size()));
162 }
163
164 // Creates an RSA-OAEP algorithm
165 blink::WebCryptoAlgorithm CreateRsaOaepAlgorithm(
166     const std::vector<uint8>& label) {
167   return blink::WebCryptoAlgorithm::adoptParamsAndCreate(
168       blink::WebCryptoAlgorithmIdRsaOaep,
169       new blink::WebCryptoRsaOaepParams(
170           !label.empty(), Uint8VectorStart(label), label.size()));
171 }
172
173 // Creates an AES-CBC algorithm.
174 blink::WebCryptoAlgorithm CreateAesCbcAlgorithm(const std::vector<uint8>& iv) {
175   return blink::WebCryptoAlgorithm::adoptParamsAndCreate(
176       blink::WebCryptoAlgorithmIdAesCbc,
177       new blink::WebCryptoAesCbcParams(Uint8VectorStart(iv), iv.size()));
178 }
179
180 // Creates an AES-GCM algorithm.
181 blink::WebCryptoAlgorithm CreateAesGcmAlgorithm(
182     const std::vector<uint8>& iv,
183     const std::vector<uint8>& additional_data,
184     unsigned int tag_length_bits) {
185   EXPECT_TRUE(SupportsAesGcm());
186   return blink::WebCryptoAlgorithm::adoptParamsAndCreate(
187       blink::WebCryptoAlgorithmIdAesGcm,
188       new blink::WebCryptoAesGcmParams(Uint8VectorStart(iv),
189                                        iv.size(),
190                                        true,
191                                        Uint8VectorStart(additional_data),
192                                        additional_data.size(),
193                                        true,
194                                        tag_length_bits));
195 }
196
197 // Creates an HMAC algorithm whose parameters struct is compatible with key
198 // generation. It is an error to call this with a hash_id that is not a SHA*.
199 // The key_length_bits parameter is optional, with zero meaning unspecified.
200 blink::WebCryptoAlgorithm CreateHmacKeyGenAlgorithm(
201     blink::WebCryptoAlgorithmId hash_id,
202     unsigned int key_length_bits) {
203   DCHECK(blink::WebCryptoAlgorithm::isHash(hash_id));
204   // key_length_bytes == 0 means unspecified
205   return blink::WebCryptoAlgorithm::adoptParamsAndCreate(
206       blink::WebCryptoAlgorithmIdHmac,
207       new blink::WebCryptoHmacKeyGenParams(
208           CreateAlgorithm(hash_id), (key_length_bits != 0), key_length_bits));
209 }
210
211 // Returns a slightly modified version of the input vector.
212 //
213 //  - For non-empty inputs a single bit is inverted.
214 //  - For empty inputs, a byte is added.
215 std::vector<uint8> Corrupted(const std::vector<uint8>& input) {
216   std::vector<uint8> corrupted_data(input);
217   if (corrupted_data.empty())
218     corrupted_data.push_back(0);
219   corrupted_data[corrupted_data.size() / 2] ^= 0x01;
220   return corrupted_data;
221 }
222
223 std::vector<uint8> HexStringToBytes(const std::string& hex) {
224   std::vector<uint8> bytes;
225   base::HexStringToBytes(hex, &bytes);
226   return bytes;
227 }
228
229 std::vector<uint8> MakeJsonVector(const std::string& json_string) {
230   return std::vector<uint8>(json_string.begin(), json_string.end());
231 }
232
233 std::vector<uint8> MakeJsonVector(const base::DictionaryValue& dict) {
234   std::string json;
235   base::JSONWriter::Write(&dict, &json);
236   return MakeJsonVector(json);
237 }
238
239 // ----------------------------------------------------------------
240 // Helpers for working with JSON data files for test expectations.
241 // ----------------------------------------------------------------
242
243 // Reads a file in "src/content/test/data/webcrypto" to a base::Value.
244 // The file must be JSON, however it can also include C++ style comments.
245 ::testing::AssertionResult ReadJsonTestFile(const char* test_file_name,
246                                             scoped_ptr<base::Value>* value) {
247   base::FilePath test_data_dir;
248   if (!PathService::Get(DIR_TEST_DATA, &test_data_dir))
249     return ::testing::AssertionFailure() << "Couldn't retrieve test dir";
250
251   base::FilePath file_path =
252       test_data_dir.AppendASCII("webcrypto").AppendASCII(test_file_name);
253
254   std::string file_contents;
255   if (!base::ReadFileToString(file_path, &file_contents)) {
256     return ::testing::AssertionFailure()
257            << "Couldn't read test file: " << file_path.value();
258   }
259
260   // Strip C++ style comments out of the "json" file, otherwise it cannot be
261   // parsed.
262   re2::RE2::GlobalReplace(&file_contents, re2::RE2("\\s*//.*"), "");
263
264   // Parse the JSON to a dictionary.
265   value->reset(base::JSONReader::Read(file_contents));
266   if (!value->get()) {
267     return ::testing::AssertionFailure()
268            << "Couldn't parse test file JSON: " << file_path.value();
269   }
270
271   return ::testing::AssertionSuccess();
272 }
273
274 // Same as ReadJsonTestFile(), but return the value as a List.
275 ::testing::AssertionResult ReadJsonTestFileToList(
276     const char* test_file_name,
277     scoped_ptr<base::ListValue>* list) {
278   // Read the JSON.
279   scoped_ptr<base::Value> json;
280   ::testing::AssertionResult result = ReadJsonTestFile(test_file_name, &json);
281   if (!result)
282     return result;
283
284   // Cast to an ListValue.
285   base::ListValue* list_value = NULL;
286   if (!json->GetAsList(&list_value) || !list_value)
287     return ::testing::AssertionFailure() << "The JSON was not a list";
288
289   list->reset(list_value);
290   ignore_result(json.release());
291
292   return ::testing::AssertionSuccess();
293 }
294
295 // Read a string property from the dictionary with path |property_name|
296 // (which can include periods for nested dictionaries). Interprets the
297 // string as a hex encoded string and converts it to a bytes list.
298 //
299 // Returns empty vector on failure.
300 std::vector<uint8> GetBytesFromHexString(base::DictionaryValue* dict,
301                                          const char* property_name) {
302   std::string hex_string;
303   if (!dict->GetString(property_name, &hex_string)) {
304     EXPECT_TRUE(false) << "Couldn't get string property: " << property_name;
305     return std::vector<uint8>();
306   }
307
308   return HexStringToBytes(hex_string);
309 }
310
311 // Reads a string property with path "property_name" and converts it to a
312 // WebCryptoAlgorith. Returns null algorithm on failure.
313 blink::WebCryptoAlgorithm GetDigestAlgorithm(base::DictionaryValue* dict,
314                                              const char* property_name) {
315   std::string algorithm_name;
316   if (!dict->GetString(property_name, &algorithm_name)) {
317     EXPECT_TRUE(false) << "Couldn't get string property: " << property_name;
318     return blink::WebCryptoAlgorithm::createNull();
319   }
320
321   struct {
322     const char* name;
323     blink::WebCryptoAlgorithmId id;
324   } kDigestNameToId[] = {
325         {"sha-1", blink::WebCryptoAlgorithmIdSha1},
326         {"sha-256", blink::WebCryptoAlgorithmIdSha256},
327         {"sha-384", blink::WebCryptoAlgorithmIdSha384},
328         {"sha-512", blink::WebCryptoAlgorithmIdSha512},
329     };
330
331   for (size_t i = 0; i < ARRAYSIZE_UNSAFE(kDigestNameToId); ++i) {
332     if (kDigestNameToId[i].name == algorithm_name)
333       return CreateAlgorithm(kDigestNameToId[i].id);
334   }
335
336   return blink::WebCryptoAlgorithm::createNull();
337 }
338
339 // Helper for ImportJwkFailures and ImportJwkOctFailures. Restores the JWK JSON
340 // dictionary to a good state
341 void RestoreJwkOctDictionary(base::DictionaryValue* dict) {
342   dict->Clear();
343   dict->SetString("kty", "oct");
344   dict->SetString("alg", "A128CBC");
345   dict->SetString("use", "enc");
346   dict->SetBoolean("ext", false);
347   dict->SetString("k", "GADWrMRHwQfoNaXU5fZvTg==");
348 }
349
350 // Helper for ImportJwkRsaFailures. Restores the JWK JSON
351 // dictionary to a good state
352 void RestoreJwkRsaDictionary(base::DictionaryValue* dict) {
353   dict->Clear();
354   dict->SetString("kty", "RSA");
355   dict->SetString("alg", "RS256");
356   dict->SetString("use", "sig");
357   dict->SetBoolean("ext", false);
358   dict->SetString(
359       "n",
360       "qLOyhK-OtQs4cDSoYPFGxJGfMYdjzWxVmMiuSBGh4KvEx-CwgtaTpef87Wdc9GaFEncsDLxk"
361       "p0LGxjD1M8jMcvYq6DPEC_JYQumEu3i9v5fAEH1VvbZi9cTg-rmEXLUUjvc5LdOq_5OuHmtm"
362       "e7PUJHYW1PW6ENTP0ibeiNOfFvs");
363   dict->SetString("e", "AQAB");
364 }
365
366 // Returns true if any of the vectors in the input list have identical content.
367 // Dumb O(n^2) implementation but should be fast enough for the input sizes that
368 // are used.
369 bool CopiesExist(const std::vector<std::vector<uint8> >& bufs) {
370   for (size_t i = 0; i < bufs.size(); ++i) {
371     for (size_t j = i + 1; j < bufs.size(); ++j) {
372       if (CryptoData(bufs[i]) == CryptoData(bufs[j]))
373         return true;
374     }
375   }
376   return false;
377 }
378
379 blink::WebCryptoAlgorithm CreateAesKeyGenAlgorithm(
380     blink::WebCryptoAlgorithmId aes_alg_id,
381     unsigned short length) {
382   return blink::WebCryptoAlgorithm::adoptParamsAndCreate(
383       aes_alg_id, new blink::WebCryptoAesKeyGenParams(length));
384 }
385
386 blink::WebCryptoAlgorithm CreateAesCbcKeyGenAlgorithm(
387     unsigned short key_length_bits) {
388   return CreateAesKeyGenAlgorithm(blink::WebCryptoAlgorithmIdAesCbc,
389                                   key_length_bits);
390 }
391
392 blink::WebCryptoAlgorithm CreateAesGcmKeyGenAlgorithm(
393     unsigned short key_length_bits) {
394   EXPECT_TRUE(SupportsAesGcm());
395   return CreateAesKeyGenAlgorithm(blink::WebCryptoAlgorithmIdAesGcm,
396                                   key_length_bits);
397 }
398
399 blink::WebCryptoAlgorithm CreateAesKwKeyGenAlgorithm(
400     unsigned short key_length_bits) {
401   return CreateAesKeyGenAlgorithm(blink::WebCryptoAlgorithmIdAesKw,
402                                   key_length_bits);
403 }
404
405 // The following key pair is comprised of the SPKI (public key) and PKCS#8
406 // (private key) representations of the key pair provided in Example 1 of the
407 // NIST test vectors at
408 // ftp://ftp.rsa.com/pub/rsalabs/tmp/pkcs1v15sign-vectors.txt
409 const unsigned int kModulusLengthBits = 1024;
410 const char* const kPublicKeySpkiDerHex =
411     "30819f300d06092a864886f70d010101050003818d0030818902818100a5"
412     "6e4a0e701017589a5187dc7ea841d156f2ec0e36ad52a44dfeb1e61f7ad9"
413     "91d8c51056ffedb162b4c0f283a12a88a394dff526ab7291cbb307ceabfc"
414     "e0b1dfd5cd9508096d5b2b8b6df5d671ef6377c0921cb23c270a70e2598e"
415     "6ff89d19f105acc2d3f0cb35f29280e1386b6f64c4ef22e1e1f20d0ce8cf"
416     "fb2249bd9a21370203010001";
417 const char* const kPrivateKeyPkcs8DerHex =
418     "30820275020100300d06092a864886f70d01010105000482025f3082025b"
419     "02010002818100a56e4a0e701017589a5187dc7ea841d156f2ec0e36ad52"
420     "a44dfeb1e61f7ad991d8c51056ffedb162b4c0f283a12a88a394dff526ab"
421     "7291cbb307ceabfce0b1dfd5cd9508096d5b2b8b6df5d671ef6377c0921c"
422     "b23c270a70e2598e6ff89d19f105acc2d3f0cb35f29280e1386b6f64c4ef"
423     "22e1e1f20d0ce8cffb2249bd9a2137020301000102818033a5042a90b27d"
424     "4f5451ca9bbbd0b44771a101af884340aef9885f2a4bbe92e894a724ac3c"
425     "568c8f97853ad07c0266c8c6a3ca0929f1e8f11231884429fc4d9ae55fee"
426     "896a10ce707c3ed7e734e44727a39574501a532683109c2abacaba283c31"
427     "b4bd2f53c3ee37e352cee34f9e503bd80c0622ad79c6dcee883547c6a3b3"
428     "25024100e7e8942720a877517273a356053ea2a1bc0c94aa72d55c6e8629"
429     "6b2dfc967948c0a72cbccca7eacb35706e09a1df55a1535bd9b3cc34160b"
430     "3b6dcd3eda8e6443024100b69dca1cf7d4d7ec81e75b90fcca874abcde12"
431     "3fd2700180aa90479b6e48de8d67ed24f9f19d85ba275874f542cd20dc72"
432     "3e6963364a1f9425452b269a6799fd024028fa13938655be1f8a159cbaca"
433     "5a72ea190c30089e19cd274a556f36c4f6e19f554b34c077790427bbdd8d"
434     "d3ede2448328f385d81b30e8e43b2fffa02786197902401a8b38f398fa71"
435     "2049898d7fb79ee0a77668791299cdfa09efc0e507acb21ed74301ef5bfd"
436     "48be455eaeb6e1678255827580a8e4e8e14151d1510a82a3f2e729024027"
437     "156aba4126d24a81f3a528cbfb27f56886f840a9f6e86e17a44b94fe9319"
438     "584b8e22fdde1e5a2e3bd8aa5ba8d8584194eb2190acf832b847f13a3d24"
439     "a79f4d";
440 // The modulus and exponent (in hex) of kPublicKeySpkiDerHex
441 const char* const kPublicKeyModulusHex =
442     "A56E4A0E701017589A5187DC7EA841D156F2EC0E36AD52A44DFEB1E61F7AD991D8C51056"
443     "FFEDB162B4C0F283A12A88A394DFF526AB7291CBB307CEABFCE0B1DFD5CD9508096D5B2B"
444     "8B6DF5D671EF6377C0921CB23C270A70E2598E6FF89D19F105ACC2D3F0CB35F29280E138"
445     "6B6F64C4EF22E1E1F20D0CE8CFFB2249BD9A2137";
446 const char* const kPublicKeyExponentHex = "010001";
447
448 class SharedCryptoTest : public testing::Test {
449  protected:
450   virtual void SetUp() OVERRIDE { Init(); }
451 };
452
453 blink::WebCryptoKey ImportSecretKeyFromRaw(
454     const std::vector<uint8>& key_raw,
455     const blink::WebCryptoAlgorithm& algorithm,
456     blink::WebCryptoKeyUsageMask usage) {
457   blink::WebCryptoKey key = blink::WebCryptoKey::createNull();
458   bool extractable = true;
459   EXPECT_EQ(Status::Success(),
460             ImportKey(blink::WebCryptoKeyFormatRaw,
461                       CryptoData(key_raw),
462                       algorithm,
463                       extractable,
464                       usage,
465                       &key));
466
467   EXPECT_FALSE(key.isNull());
468   EXPECT_TRUE(key.handle());
469   EXPECT_EQ(blink::WebCryptoKeyTypeSecret, key.type());
470   EXPECT_EQ(algorithm.id(), key.algorithm().id());
471   EXPECT_EQ(extractable, key.extractable());
472   EXPECT_EQ(usage, key.usages());
473   return key;
474 }
475
476 void ImportRsaKeyPair(const std::vector<uint8>& spki_der,
477                       const std::vector<uint8>& pkcs8_der,
478                       const blink::WebCryptoAlgorithm& algorithm,
479                       bool extractable,
480                       blink::WebCryptoKeyUsageMask public_key_usage_mask,
481                       blink::WebCryptoKeyUsageMask private_key_usage_mask,
482                       blink::WebCryptoKey* public_key,
483                       blink::WebCryptoKey* private_key) {
484   ASSERT_EQ(Status::Success(),
485             ImportKey(blink::WebCryptoKeyFormatSpki,
486                       CryptoData(spki_der),
487                       algorithm,
488                       true,
489                       public_key_usage_mask,
490                       public_key));
491   EXPECT_FALSE(public_key->isNull());
492   EXPECT_TRUE(public_key->handle());
493   EXPECT_EQ(blink::WebCryptoKeyTypePublic, public_key->type());
494   EXPECT_EQ(algorithm.id(), public_key->algorithm().id());
495   EXPECT_TRUE(public_key->extractable());
496   EXPECT_EQ(public_key_usage_mask, public_key->usages());
497
498   ASSERT_EQ(Status::Success(),
499             ImportKey(blink::WebCryptoKeyFormatPkcs8,
500                       CryptoData(pkcs8_der),
501                       algorithm,
502                       extractable,
503                       private_key_usage_mask,
504                       private_key));
505   EXPECT_FALSE(private_key->isNull());
506   EXPECT_TRUE(private_key->handle());
507   EXPECT_EQ(blink::WebCryptoKeyTypePrivate, private_key->type());
508   EXPECT_EQ(algorithm.id(), private_key->algorithm().id());
509   EXPECT_EQ(extractable, private_key->extractable());
510   EXPECT_EQ(private_key_usage_mask, private_key->usages());
511 }
512
513 Status AesGcmEncrypt(const blink::WebCryptoKey& key,
514                      const std::vector<uint8>& iv,
515                      const std::vector<uint8>& additional_data,
516                      unsigned int tag_length_bits,
517                      const std::vector<uint8>& plain_text,
518                      std::vector<uint8>* cipher_text,
519                      std::vector<uint8>* authentication_tag) {
520   EXPECT_TRUE(SupportsAesGcm());
521   blink::WebCryptoAlgorithm algorithm =
522       CreateAesGcmAlgorithm(iv, additional_data, tag_length_bits);
523
524   std::vector<uint8> output;
525   Status status = Encrypt(algorithm, key, CryptoData(plain_text), &output);
526   if (status.IsError())
527     return status;
528
529   if ((tag_length_bits % 8) != 0) {
530     EXPECT_TRUE(false) << "Encrypt should have failed.";
531     return Status::OperationError();
532   }
533
534   size_t tag_length_bytes = tag_length_bits / 8;
535
536   if (tag_length_bytes > output.size()) {
537     EXPECT_TRUE(false) << "tag length is larger than output";
538     return Status::OperationError();
539   }
540
541   // The encryption result is cipher text with authentication tag appended.
542   cipher_text->assign(output.begin(),
543                       output.begin() + (output.size() - tag_length_bytes));
544   authentication_tag->assign(output.begin() + cipher_text->size(),
545                              output.end());
546
547   return Status::Success();
548 }
549
550 Status AesGcmDecrypt(const blink::WebCryptoKey& key,
551                      const std::vector<uint8>& iv,
552                      const std::vector<uint8>& additional_data,
553                      unsigned int tag_length_bits,
554                      const std::vector<uint8>& cipher_text,
555                      const std::vector<uint8>& authentication_tag,
556                      std::vector<uint8>* plain_text) {
557   EXPECT_TRUE(SupportsAesGcm());
558   blink::WebCryptoAlgorithm algorithm =
559       CreateAesGcmAlgorithm(iv, additional_data, tag_length_bits);
560
561   // Join cipher text and authentication tag.
562   std::vector<uint8> cipher_text_with_tag;
563   cipher_text_with_tag.reserve(cipher_text.size() + authentication_tag.size());
564   cipher_text_with_tag.insert(
565       cipher_text_with_tag.end(), cipher_text.begin(), cipher_text.end());
566   cipher_text_with_tag.insert(cipher_text_with_tag.end(),
567                               authentication_tag.begin(),
568                               authentication_tag.end());
569
570   return Decrypt(algorithm, key, CryptoData(cipher_text_with_tag), plain_text);
571 }
572
573 Status ImportKeyJwk(const CryptoData& key_data,
574                     const blink::WebCryptoAlgorithm& algorithm,
575                     bool extractable,
576                     blink::WebCryptoKeyUsageMask usage_mask,
577                     blink::WebCryptoKey* key) {
578   return ImportKey(blink::WebCryptoKeyFormatJwk,
579                    key_data,
580                    algorithm,
581                    extractable,
582                    usage_mask,
583                    key);
584 }
585
586 Status ImportKeyJwkFromDict(const base::DictionaryValue& dict,
587                             const blink::WebCryptoAlgorithm& algorithm,
588                             bool extractable,
589                             blink::WebCryptoKeyUsageMask usage_mask,
590                             blink::WebCryptoKey* key) {
591   return ImportKeyJwk(CryptoData(MakeJsonVector(dict)),
592                       algorithm,
593                       extractable,
594                       usage_mask,
595                       key);
596 }
597
598 // Parses a vector of JSON into a dictionary.
599 scoped_ptr<base::DictionaryValue> GetJwkDictionary(
600     const std::vector<uint8>& json) {
601   base::StringPiece json_string(
602       reinterpret_cast<const char*>(Uint8VectorStart(json)), json.size());
603   base::Value* value = base::JSONReader::Read(json_string);
604   EXPECT_TRUE(value);
605   base::DictionaryValue* dict_value = NULL;
606   value->GetAsDictionary(&dict_value);
607   return scoped_ptr<base::DictionaryValue>(dict_value);
608 }
609
610 // Verifies the input dictionary contains the expected values. Exact matches are
611 // required on the fields examined.
612 ::testing::AssertionResult VerifyJwk(
613     const scoped_ptr<base::DictionaryValue>& dict,
614     const std::string& kty_expected,
615     const std::string& alg_expected,
616     blink::WebCryptoKeyUsageMask use_mask_expected) {
617   // ---- kty
618   std::string value_string;
619   if (!dict->GetString("kty", &value_string))
620     return ::testing::AssertionFailure() << "Missing 'kty'";
621   if (value_string != kty_expected)
622     return ::testing::AssertionFailure() << "Expected 'kty' to be "
623                                          << kty_expected << "but found "
624                                          << value_string;
625
626   // ---- alg
627   if (!dict->GetString("alg", &value_string))
628     return ::testing::AssertionFailure() << "Missing 'alg'";
629   if (value_string != alg_expected)
630     return ::testing::AssertionFailure() << "Expected 'alg' to be "
631                                          << alg_expected << " but found "
632                                          << value_string;
633
634   // ---- ext
635   // always expect ext == true in this case
636   bool ext_value;
637   if (!dict->GetBoolean("ext", &ext_value))
638     return ::testing::AssertionFailure() << "Missing 'ext'";
639   if (!ext_value)
640     return ::testing::AssertionFailure()
641            << "Expected 'ext' to be true but found false";
642
643   // ---- key_ops
644   base::ListValue* key_ops;
645   if (!dict->GetList("key_ops", &key_ops))
646     return ::testing::AssertionFailure() << "Missing 'key_ops'";
647   blink::WebCryptoKeyUsageMask key_ops_mask = 0;
648   Status status = GetWebCryptoUsagesFromJwkKeyOps(key_ops, &key_ops_mask);
649   if (status.IsError())
650     return ::testing::AssertionFailure() << "Failure extracting 'key_ops'";
651   if (key_ops_mask != use_mask_expected)
652     return ::testing::AssertionFailure()
653            << "Expected 'key_ops' mask to be " << use_mask_expected
654            << " but found " << key_ops_mask << " (" << value_string << ")";
655
656   return ::testing::AssertionSuccess();
657 }
658
659 // Verifies that the JSON in the input vector contains the provided
660 // expected values. Exact matches are required on the fields examined.
661 ::testing::AssertionResult VerifySecretJwk(
662     const std::vector<uint8>& json,
663     const std::string& alg_expected,
664     const std::string& k_expected_hex,
665     blink::WebCryptoKeyUsageMask use_mask_expected) {
666   scoped_ptr<base::DictionaryValue> dict = GetJwkDictionary(json);
667   if (!dict.get() || dict->empty())
668     return ::testing::AssertionFailure() << "JSON parsing failed";
669
670   // ---- k
671   std::string value_string;
672   if (!dict->GetString("k", &value_string))
673     return ::testing::AssertionFailure() << "Missing 'k'";
674   std::string k_value;
675   if (!webcrypto::Base64DecodeUrlSafe(value_string, &k_value))
676     return ::testing::AssertionFailure() << "Base64DecodeUrlSafe(k) failed";
677   if (!LowerCaseEqualsASCII(base::HexEncode(k_value.data(), k_value.size()),
678                             k_expected_hex.c_str())) {
679     return ::testing::AssertionFailure() << "Expected 'k' to be "
680                                          << k_expected_hex
681                                          << " but found something different";
682   }
683
684   return VerifyJwk(dict, "oct", alg_expected, use_mask_expected);
685 }
686
687 // Verifies that the JSON in the input vector contains the provided
688 // expected values. Exact matches are required on the fields examined.
689 ::testing::AssertionResult VerifyPublicJwk(
690     const std::vector<uint8>& json,
691     const std::string& alg_expected,
692     const std::string& n_expected_hex,
693     const std::string& e_expected_hex,
694     blink::WebCryptoKeyUsageMask use_mask_expected) {
695   scoped_ptr<base::DictionaryValue> dict = GetJwkDictionary(json);
696   if (!dict.get() || dict->empty())
697     return ::testing::AssertionFailure() << "JSON parsing failed";
698
699   // ---- n
700   std::string value_string;
701   if (!dict->GetString("n", &value_string))
702     return ::testing::AssertionFailure() << "Missing 'n'";
703   std::string n_value;
704   if (!webcrypto::Base64DecodeUrlSafe(value_string, &n_value))
705     return ::testing::AssertionFailure() << "Base64DecodeUrlSafe(n) failed";
706   if (base::HexEncode(n_value.data(), n_value.size()) != n_expected_hex) {
707     return ::testing::AssertionFailure() << "'n' does not match the expected "
708                                             "value";
709   }
710   // TODO(padolph): LowerCaseEqualsASCII() does not work for above!
711
712   // ---- e
713   if (!dict->GetString("e", &value_string))
714     return ::testing::AssertionFailure() << "Missing 'e'";
715   std::string e_value;
716   if (!webcrypto::Base64DecodeUrlSafe(value_string, &e_value))
717     return ::testing::AssertionFailure() << "Base64DecodeUrlSafe(e) failed";
718   if (!LowerCaseEqualsASCII(base::HexEncode(e_value.data(), e_value.size()),
719                             e_expected_hex.c_str())) {
720     return ::testing::AssertionFailure() << "Expected 'e' to be "
721                                          << e_expected_hex
722                                          << " but found something different";
723   }
724
725   return VerifyJwk(dict, "RSA", alg_expected, use_mask_expected);
726 }
727
728 }  // namespace
729
730 TEST_F(SharedCryptoTest, CheckAesGcm) {
731   if (!SupportsAesGcm()) {
732     LOG(WARNING) << "AES GCM not supported on this platform, so some tests "
733                     "will be skipped. Consider upgrading local NSS libraries";
734     return;
735   }
736 }
737
738 // Tests several Status objects against their expected hard coded values, as
739 // well as ensuring that comparison of Status objects works.
740 // Comparison should take into account both the error details, as well as the
741 // error type.
742 TEST_F(SharedCryptoTest, Status) {
743   // Even though the error message is the same, these should not be considered
744   // the same by the tests because the error type is different.
745   EXPECT_NE(Status::DataError(), Status::OperationError());
746   EXPECT_NE(Status::Success(), Status::OperationError());
747
748   EXPECT_EQ(Status::Success(), Status::Success());
749   EXPECT_EQ(Status::ErrorJwkPropertyWrongType("kty", "string"),
750             Status::ErrorJwkPropertyWrongType("kty", "string"));
751
752   Status status = Status::Success();
753
754   EXPECT_FALSE(status.IsError());
755   EXPECT_EQ("", status.error_details());
756
757   status = Status::OperationError();
758   EXPECT_TRUE(status.IsError());
759   EXPECT_EQ("", status.error_details());
760   EXPECT_EQ(blink::WebCryptoErrorTypeOperation, status.error_type());
761
762   status = Status::DataError();
763   EXPECT_TRUE(status.IsError());
764   EXPECT_EQ("", status.error_details());
765   EXPECT_EQ(blink::WebCryptoErrorTypeData, status.error_type());
766
767   status = Status::ErrorUnsupported();
768   EXPECT_TRUE(status.IsError());
769   EXPECT_EQ("The requested operation is unsupported", status.error_details());
770   EXPECT_EQ(blink::WebCryptoErrorTypeNotSupported, status.error_type());
771
772   status = Status::ErrorJwkPropertyMissing("kty");
773   EXPECT_TRUE(status.IsError());
774   EXPECT_EQ("The required JWK property \"kty\" was missing",
775             status.error_details());
776   EXPECT_EQ(blink::WebCryptoErrorTypeData, status.error_type());
777
778   status = Status::ErrorJwkPropertyWrongType("kty", "string");
779   EXPECT_TRUE(status.IsError());
780   EXPECT_EQ("The JWK property \"kty\" must be a string",
781             status.error_details());
782   EXPECT_EQ(blink::WebCryptoErrorTypeData, status.error_type());
783
784   status = Status::ErrorJwkBase64Decode("n");
785   EXPECT_TRUE(status.IsError());
786   EXPECT_EQ("The JWK property \"n\" could not be base64 decoded",
787             status.error_details());
788   EXPECT_EQ(blink::WebCryptoErrorTypeData, status.error_type());
789 }
790
791 TEST_F(SharedCryptoTest, DigestSampleSets) {
792   scoped_ptr<base::ListValue> tests;
793   ASSERT_TRUE(ReadJsonTestFileToList("digest.json", &tests));
794
795   for (size_t test_index = 0; test_index < tests->GetSize(); ++test_index) {
796     SCOPED_TRACE(test_index);
797     base::DictionaryValue* test;
798     ASSERT_TRUE(tests->GetDictionary(test_index, &test));
799
800     blink::WebCryptoAlgorithm test_algorithm =
801         GetDigestAlgorithm(test, "algorithm");
802     std::vector<uint8> test_input = GetBytesFromHexString(test, "input");
803     std::vector<uint8> test_output = GetBytesFromHexString(test, "output");
804
805     std::vector<uint8> output;
806     ASSERT_EQ(Status::Success(),
807               Digest(test_algorithm, CryptoData(test_input), &output));
808     EXPECT_BYTES_EQ(test_output, output);
809   }
810 }
811
812 TEST_F(SharedCryptoTest, DigestSampleSetsInChunks) {
813   scoped_ptr<base::ListValue> tests;
814   ASSERT_TRUE(ReadJsonTestFileToList("digest.json", &tests));
815
816   for (size_t test_index = 0; test_index < tests->GetSize(); ++test_index) {
817     SCOPED_TRACE(test_index);
818     base::DictionaryValue* test;
819     ASSERT_TRUE(tests->GetDictionary(test_index, &test));
820
821     blink::WebCryptoAlgorithm test_algorithm =
822         GetDigestAlgorithm(test, "algorithm");
823     std::vector<uint8> test_input = GetBytesFromHexString(test, "input");
824     std::vector<uint8> test_output = GetBytesFromHexString(test, "output");
825
826     // Test the chunk version of the digest functions. Test with 129 byte chunks
827     // because the SHA-512 chunk size is 128 bytes.
828     unsigned char* output;
829     unsigned int output_length;
830     static const size_t kChunkSizeBytes = 129;
831     size_t length = test_input.size();
832     scoped_ptr<blink::WebCryptoDigestor> digestor(
833         CreateDigestor(test_algorithm.id()));
834     std::vector<uint8>::iterator begin = test_input.begin();
835     size_t chunk_index = 0;
836     while (begin != test_input.end()) {
837       size_t chunk_length = std::min(kChunkSizeBytes, length - chunk_index);
838       std::vector<uint8> chunk(begin, begin + chunk_length);
839       ASSERT_TRUE(chunk.size() > 0);
840       EXPECT_TRUE(digestor->consume(&chunk.front(), chunk.size()));
841       chunk_index = chunk_index + chunk_length;
842       begin = begin + chunk_length;
843     }
844     EXPECT_TRUE(digestor->finish(output, output_length));
845     EXPECT_BYTES_EQ(test_output, CryptoData(output, output_length));
846   }
847 }
848
849 TEST_F(SharedCryptoTest, HMACSampleSets) {
850   scoped_ptr<base::ListValue> tests;
851   ASSERT_TRUE(ReadJsonTestFileToList("hmac.json", &tests));
852   // TODO(padolph): Missing known answer tests for HMAC SHA384, and SHA512.
853   for (size_t test_index = 0; test_index < tests->GetSize(); ++test_index) {
854     SCOPED_TRACE(test_index);
855     base::DictionaryValue* test;
856     ASSERT_TRUE(tests->GetDictionary(test_index, &test));
857
858     blink::WebCryptoAlgorithm test_hash = GetDigestAlgorithm(test, "hash");
859     const std::vector<uint8> test_key = GetBytesFromHexString(test, "key");
860     const std::vector<uint8> test_message =
861         GetBytesFromHexString(test, "message");
862     const std::vector<uint8> test_mac = GetBytesFromHexString(test, "mac");
863
864     blink::WebCryptoAlgorithm algorithm =
865         CreateAlgorithm(blink::WebCryptoAlgorithmIdHmac);
866
867     blink::WebCryptoAlgorithm import_algorithm =
868         CreateHmacImportAlgorithm(test_hash.id());
869
870     blink::WebCryptoKey key = ImportSecretKeyFromRaw(
871         test_key,
872         import_algorithm,
873         blink::WebCryptoKeyUsageSign | blink::WebCryptoKeyUsageVerify);
874
875     EXPECT_EQ(test_hash.id(), key.algorithm().hmacParams()->hash().id());
876     EXPECT_EQ(test_key.size() * 8, key.algorithm().hmacParams()->lengthBits());
877
878     // Verify exported raw key is identical to the imported data
879     std::vector<uint8> raw_key;
880     EXPECT_EQ(Status::Success(),
881               ExportKey(blink::WebCryptoKeyFormatRaw, key, &raw_key));
882     EXPECT_BYTES_EQ(test_key, raw_key);
883
884     std::vector<uint8> output;
885
886     ASSERT_EQ(Status::Success(),
887               Sign(algorithm, key, CryptoData(test_message), &output));
888
889     EXPECT_BYTES_EQ(test_mac, output);
890
891     bool signature_match = false;
892     EXPECT_EQ(Status::Success(),
893               VerifySignature(algorithm,
894                               key,
895                               CryptoData(output),
896                               CryptoData(test_message),
897                               &signature_match));
898     EXPECT_TRUE(signature_match);
899
900     // Ensure truncated signature does not verify by passing one less byte.
901     EXPECT_EQ(
902         Status::Success(),
903         VerifySignature(algorithm,
904                         key,
905                         CryptoData(Uint8VectorStart(output), output.size() - 1),
906                         CryptoData(test_message),
907                         &signature_match));
908     EXPECT_FALSE(signature_match);
909
910     // Ensure truncated signature does not verify by passing no bytes.
911     EXPECT_EQ(Status::Success(),
912               VerifySignature(algorithm,
913                               key,
914                               CryptoData(),
915                               CryptoData(test_message),
916                               &signature_match));
917     EXPECT_FALSE(signature_match);
918
919     // Ensure extra long signature does not cause issues and fails.
920     const unsigned char kLongSignature[1024] = {0};
921     EXPECT_EQ(
922         Status::Success(),
923         VerifySignature(algorithm,
924                         key,
925                         CryptoData(kLongSignature, sizeof(kLongSignature)),
926                         CryptoData(test_message),
927                         &signature_match));
928     EXPECT_FALSE(signature_match);
929   }
930 }
931
932 TEST_F(SharedCryptoTest, AesCbcFailures) {
933   const std::string key_hex = "2b7e151628aed2a6abf7158809cf4f3c";
934   blink::WebCryptoKey key = ImportSecretKeyFromRaw(
935       HexStringToBytes(key_hex),
936       CreateAlgorithm(blink::WebCryptoAlgorithmIdAesCbc),
937       blink::WebCryptoKeyUsageEncrypt | blink::WebCryptoKeyUsageDecrypt);
938
939   // Verify exported raw key is identical to the imported data
940   std::vector<uint8> raw_key;
941   EXPECT_EQ(Status::Success(),
942             ExportKey(blink::WebCryptoKeyFormatRaw, key, &raw_key));
943   EXPECT_BYTES_EQ_HEX(key_hex, raw_key);
944
945   std::vector<uint8> output;
946
947   // Use an invalid |iv| (fewer than 16 bytes)
948   {
949     std::vector<uint8> input(32);
950     std::vector<uint8> iv;
951     EXPECT_EQ(Status::ErrorIncorrectSizeAesCbcIv(),
952               Encrypt(webcrypto::CreateAesCbcAlgorithm(iv),
953                       key,
954                       CryptoData(input),
955                       &output));
956     EXPECT_EQ(Status::ErrorIncorrectSizeAesCbcIv(),
957               Decrypt(webcrypto::CreateAesCbcAlgorithm(iv),
958                       key,
959                       CryptoData(input),
960                       &output));
961   }
962
963   // Use an invalid |iv| (more than 16 bytes)
964   {
965     std::vector<uint8> input(32);
966     std::vector<uint8> iv(17);
967     EXPECT_EQ(Status::ErrorIncorrectSizeAesCbcIv(),
968               Encrypt(webcrypto::CreateAesCbcAlgorithm(iv),
969                       key,
970                       CryptoData(input),
971                       &output));
972     EXPECT_EQ(Status::ErrorIncorrectSizeAesCbcIv(),
973               Decrypt(webcrypto::CreateAesCbcAlgorithm(iv),
974                       key,
975                       CryptoData(input),
976                       &output));
977   }
978
979   // Give an input that is too large (would cause integer overflow when
980   // narrowing to an int).
981   {
982     std::vector<uint8> iv(16);
983
984     // Pretend the input is large. Don't pass data pointer as NULL in case that
985     // is special cased; the implementation shouldn't actually dereference the
986     // data.
987     CryptoData input(&iv[0], INT_MAX - 3);
988
989     EXPECT_EQ(Status::ErrorDataTooLarge(),
990               Encrypt(CreateAesCbcAlgorithm(iv), key, input, &output));
991     EXPECT_EQ(Status::ErrorDataTooLarge(),
992               Decrypt(CreateAesCbcAlgorithm(iv), key, input, &output));
993   }
994
995   // Fail importing the key (too few bytes specified)
996   {
997     std::vector<uint8> key_raw(1);
998     std::vector<uint8> iv(16);
999
1000     blink::WebCryptoKey key = blink::WebCryptoKey::createNull();
1001     EXPECT_EQ(Status::ErrorImportAesKeyLength(),
1002               ImportKey(blink::WebCryptoKeyFormatRaw,
1003                         CryptoData(key_raw),
1004                         CreateAesCbcAlgorithm(iv),
1005                         true,
1006                         blink::WebCryptoKeyUsageEncrypt,
1007                         &key));
1008   }
1009
1010   // Fail exporting the key in SPKI and PKCS#8 formats (not allowed for secret
1011   // keys).
1012   EXPECT_EQ(Status::ErrorUnexpectedKeyType(),
1013             ExportKey(blink::WebCryptoKeyFormatSpki, key, &output));
1014   EXPECT_EQ(Status::ErrorUnexpectedKeyType(),
1015             ExportKey(blink::WebCryptoKeyFormatPkcs8, key, &output));
1016 }
1017
1018 TEST_F(SharedCryptoTest, MAYBE(AesCbcSampleSets)) {
1019   scoped_ptr<base::ListValue> tests;
1020   ASSERT_TRUE(ReadJsonTestFileToList("aes_cbc.json", &tests));
1021
1022   for (size_t test_index = 0; test_index < tests->GetSize(); ++test_index) {
1023     SCOPED_TRACE(test_index);
1024     base::DictionaryValue* test;
1025     ASSERT_TRUE(tests->GetDictionary(test_index, &test));
1026
1027     std::vector<uint8> test_key = GetBytesFromHexString(test, "key");
1028     std::vector<uint8> test_iv = GetBytesFromHexString(test, "iv");
1029     std::vector<uint8> test_plain_text =
1030         GetBytesFromHexString(test, "plain_text");
1031     std::vector<uint8> test_cipher_text =
1032         GetBytesFromHexString(test, "cipher_text");
1033
1034     blink::WebCryptoKey key = ImportSecretKeyFromRaw(
1035         test_key,
1036         CreateAlgorithm(blink::WebCryptoAlgorithmIdAesCbc),
1037         blink::WebCryptoKeyUsageEncrypt | blink::WebCryptoKeyUsageDecrypt);
1038
1039     EXPECT_EQ(test_key.size() * 8, key.algorithm().aesParams()->lengthBits());
1040
1041     // Verify exported raw key is identical to the imported data
1042     std::vector<uint8> raw_key;
1043     EXPECT_EQ(Status::Success(),
1044               ExportKey(blink::WebCryptoKeyFormatRaw, key, &raw_key));
1045     EXPECT_BYTES_EQ(test_key, raw_key);
1046
1047     std::vector<uint8> output;
1048
1049     // Test encryption.
1050     EXPECT_EQ(Status::Success(),
1051               Encrypt(webcrypto::CreateAesCbcAlgorithm(test_iv),
1052                       key,
1053                       CryptoData(test_plain_text),
1054                       &output));
1055     EXPECT_BYTES_EQ(test_cipher_text, output);
1056
1057     // Test decryption.
1058     EXPECT_EQ(Status::Success(),
1059               Decrypt(webcrypto::CreateAesCbcAlgorithm(test_iv),
1060                       key,
1061                       CryptoData(test_cipher_text),
1062                       &output));
1063     EXPECT_BYTES_EQ(test_plain_text, output);
1064
1065     const unsigned int kAesCbcBlockSize = 16;
1066
1067     // Decrypt with a padding error by stripping the last block. This also ends
1068     // up testing decryption over empty cipher text.
1069     if (test_cipher_text.size() >= kAesCbcBlockSize) {
1070       EXPECT_EQ(Status::OperationError(),
1071                 Decrypt(CreateAesCbcAlgorithm(test_iv),
1072                         key,
1073                         CryptoData(&test_cipher_text[0],
1074                                    test_cipher_text.size() - kAesCbcBlockSize),
1075                         &output));
1076     }
1077
1078     // Decrypt cipher text which is not a multiple of block size by stripping
1079     // a few bytes off the cipher text.
1080     if (test_cipher_text.size() > 3) {
1081       EXPECT_EQ(
1082           Status::OperationError(),
1083           Decrypt(CreateAesCbcAlgorithm(test_iv),
1084                   key,
1085                   CryptoData(&test_cipher_text[0], test_cipher_text.size() - 3),
1086                   &output));
1087     }
1088   }
1089 }
1090
1091 TEST_F(SharedCryptoTest, MAYBE(GenerateKeyAes)) {
1092   // Check key generation for each of AES-CBC, AES-GCM, and AES-KW, and for each
1093   // allowed key length.
1094   std::vector<blink::WebCryptoAlgorithm> algorithm;
1095   const unsigned short kKeyLength[] = {128, 256};
1096   for (size_t i = 0; i < ARRAYSIZE_UNSAFE(kKeyLength); ++i) {
1097     algorithm.push_back(CreateAesCbcKeyGenAlgorithm(kKeyLength[i]));
1098     algorithm.push_back(CreateAesKwKeyGenAlgorithm(kKeyLength[i]));
1099     if (SupportsAesGcm())
1100       algorithm.push_back(CreateAesGcmKeyGenAlgorithm(kKeyLength[i]));
1101   }
1102   blink::WebCryptoKey key = blink::WebCryptoKey::createNull();
1103   std::vector<std::vector<uint8> > keys;
1104   std::vector<uint8> key_bytes;
1105   for (size_t i = 0; i < algorithm.size(); ++i) {
1106     SCOPED_TRACE(i);
1107     // Generate a small sample of keys.
1108     keys.clear();
1109     for (int j = 0; j < 16; ++j) {
1110       ASSERT_EQ(Status::Success(),
1111                 GenerateSecretKey(algorithm[i], true, 0, &key));
1112       EXPECT_TRUE(key.handle());
1113       EXPECT_EQ(blink::WebCryptoKeyTypeSecret, key.type());
1114       ASSERT_EQ(Status::Success(),
1115                 ExportKey(blink::WebCryptoKeyFormatRaw, key, &key_bytes));
1116       EXPECT_EQ(key_bytes.size() * 8,
1117                 key.algorithm().aesParams()->lengthBits());
1118       keys.push_back(key_bytes);
1119     }
1120     // Ensure all entries in the key sample set are unique. This is a simplistic
1121     // estimate of whether the generated keys appear random.
1122     EXPECT_FALSE(CopiesExist(keys));
1123   }
1124 }
1125
1126 TEST_F(SharedCryptoTest, MAYBE(GenerateKeyAesBadLength)) {
1127   const unsigned short kKeyLen[] = {0, 127, 257};
1128   blink::WebCryptoKey key = blink::WebCryptoKey::createNull();
1129   for (size_t i = 0; i < ARRAYSIZE_UNSAFE(kKeyLen); ++i) {
1130     SCOPED_TRACE(i);
1131     EXPECT_EQ(Status::ErrorGenerateKeyLength(),
1132               GenerateSecretKey(
1133                   CreateAesCbcKeyGenAlgorithm(kKeyLen[i]), true, 0, &key));
1134     EXPECT_EQ(Status::ErrorGenerateKeyLength(),
1135               GenerateSecretKey(
1136                   CreateAesKwKeyGenAlgorithm(kKeyLen[i]), true, 0, &key));
1137     if (SupportsAesGcm()) {
1138       EXPECT_EQ(Status::ErrorGenerateKeyLength(),
1139                 GenerateSecretKey(
1140                     CreateAesGcmKeyGenAlgorithm(kKeyLen[i]), true, 0, &key));
1141     }
1142   }
1143 }
1144
1145 TEST_F(SharedCryptoTest, MAYBE(GenerateKeyHmac)) {
1146   // Generate a small sample of HMAC keys.
1147   std::vector<std::vector<uint8> > keys;
1148   for (int i = 0; i < 16; ++i) {
1149     std::vector<uint8> key_bytes;
1150     blink::WebCryptoKey key = blink::WebCryptoKey::createNull();
1151     blink::WebCryptoAlgorithm algorithm =
1152         CreateHmacKeyGenAlgorithm(blink::WebCryptoAlgorithmIdSha1, 512);
1153     ASSERT_EQ(Status::Success(), GenerateSecretKey(algorithm, true, 0, &key));
1154     EXPECT_FALSE(key.isNull());
1155     EXPECT_TRUE(key.handle());
1156     EXPECT_EQ(blink::WebCryptoKeyTypeSecret, key.type());
1157     EXPECT_EQ(blink::WebCryptoAlgorithmIdHmac, key.algorithm().id());
1158     EXPECT_EQ(blink::WebCryptoAlgorithmIdSha1,
1159               key.algorithm().hmacParams()->hash().id());
1160     EXPECT_EQ(512u, key.algorithm().hmacParams()->lengthBits());
1161
1162     std::vector<uint8> raw_key;
1163     ASSERT_EQ(Status::Success(),
1164               ExportKey(blink::WebCryptoKeyFormatRaw, key, &raw_key));
1165     EXPECT_EQ(64U, raw_key.size());
1166     keys.push_back(raw_key);
1167   }
1168   // Ensure all entries in the key sample set are unique. This is a simplistic
1169   // estimate of whether the generated keys appear random.
1170   EXPECT_FALSE(CopiesExist(keys));
1171 }
1172
1173 // If the key length is not provided, then the block size is used.
1174 TEST_F(SharedCryptoTest, MAYBE(GenerateKeyHmacNoLength)) {
1175   blink::WebCryptoKey key = blink::WebCryptoKey::createNull();
1176   blink::WebCryptoAlgorithm algorithm =
1177       CreateHmacKeyGenAlgorithm(blink::WebCryptoAlgorithmIdSha1, 0);
1178   ASSERT_EQ(Status::Success(), GenerateSecretKey(algorithm, true, 0, &key));
1179   EXPECT_TRUE(key.handle());
1180   EXPECT_EQ(blink::WebCryptoKeyTypeSecret, key.type());
1181   EXPECT_EQ(blink::WebCryptoAlgorithmIdHmac, key.algorithm().id());
1182   EXPECT_EQ(blink::WebCryptoAlgorithmIdSha1,
1183             key.algorithm().hmacParams()->hash().id());
1184   EXPECT_EQ(512u, key.algorithm().hmacParams()->lengthBits());
1185   std::vector<uint8> raw_key;
1186   ASSERT_EQ(Status::Success(),
1187             ExportKey(blink::WebCryptoKeyFormatRaw, key, &raw_key));
1188   EXPECT_EQ(64U, raw_key.size());
1189
1190   // The block size for HMAC SHA-512 is larger.
1191   algorithm = CreateHmacKeyGenAlgorithm(blink::WebCryptoAlgorithmIdSha512, 0);
1192   ASSERT_EQ(Status::Success(), GenerateSecretKey(algorithm, true, 0, &key));
1193   EXPECT_EQ(blink::WebCryptoAlgorithmIdHmac, key.algorithm().id());
1194   EXPECT_EQ(blink::WebCryptoAlgorithmIdSha512,
1195             key.algorithm().hmacParams()->hash().id());
1196   EXPECT_EQ(1024u, key.algorithm().hmacParams()->lengthBits());
1197   ASSERT_EQ(Status::Success(),
1198             ExportKey(blink::WebCryptoKeyFormatRaw, key, &raw_key));
1199   EXPECT_EQ(128U, raw_key.size());
1200 }
1201
1202 TEST_F(SharedCryptoTest, ImportJwkKeyUsage) {
1203   blink::WebCryptoKey key = blink::WebCryptoKey::createNull();
1204   base::DictionaryValue dict;
1205   dict.SetString("kty", "oct");
1206   dict.SetBoolean("ext", false);
1207   dict.SetString("k", "GADWrMRHwQfoNaXU5fZvTg==");
1208   const blink::WebCryptoAlgorithm aes_cbc_algorithm =
1209       webcrypto::CreateAlgorithm(blink::WebCryptoAlgorithmIdAesCbc);
1210   const blink::WebCryptoAlgorithm hmac_algorithm =
1211       webcrypto::CreateHmacImportAlgorithm(blink::WebCryptoAlgorithmIdSha256);
1212   const blink::WebCryptoAlgorithm aes_kw_algorithm =
1213       webcrypto::CreateAlgorithm(blink::WebCryptoAlgorithmIdAesKw);
1214
1215   // Test null usage.
1216   base::ListValue* key_ops = new base::ListValue;
1217   // Note: the following call makes dict assume ownership of key_ops.
1218   dict.Set("key_ops", key_ops);
1219   EXPECT_EQ(Status::Success(),
1220             ImportKeyJwkFromDict(dict, aes_cbc_algorithm, false, 0, &key));
1221   EXPECT_EQ(0, key.usages());
1222
1223   // Test each key_ops value translates to the correct Web Crypto value.
1224   struct TestCase {
1225     const char* jwk_key_op;
1226     const char* jwk_alg;
1227     const blink::WebCryptoAlgorithm algorithm;
1228     const blink::WebCryptoKeyUsage usage;
1229   };
1230   // TODO(padolph): Add 'deriveBits' key_ops value once it is supported.
1231   const TestCase test_case[] = {
1232       {"encrypt", "A128CBC", aes_cbc_algorithm,
1233        blink::WebCryptoKeyUsageEncrypt},
1234       {"decrypt", "A128CBC", aes_cbc_algorithm,
1235        blink::WebCryptoKeyUsageDecrypt},
1236       {"sign", "HS256", hmac_algorithm, blink::WebCryptoKeyUsageSign},
1237       {"verify", "HS256", hmac_algorithm, blink::WebCryptoKeyUsageVerify},
1238       {"wrapKey", "A128KW", aes_kw_algorithm, blink::WebCryptoKeyUsageWrapKey},
1239       {"unwrapKey", "A128KW", aes_kw_algorithm,
1240        blink::WebCryptoKeyUsageUnwrapKey}};
1241   for (size_t test_index = 0; test_index < ARRAYSIZE_UNSAFE(test_case);
1242        ++test_index) {
1243     SCOPED_TRACE(test_index);
1244     dict.SetString("alg", test_case[test_index].jwk_alg);
1245     key_ops->Clear();
1246     key_ops->AppendString(test_case[test_index].jwk_key_op);
1247     EXPECT_EQ(Status::Success(),
1248               ImportKeyJwkFromDict(dict,
1249                                    test_case[test_index].algorithm,
1250                                    false,
1251                                    test_case[test_index].usage,
1252                                    &key));
1253     EXPECT_EQ(test_case[test_index].usage, key.usages());
1254   }
1255
1256   // Test discrete multiple usages.
1257   dict.SetString("alg", "A128CBC");
1258   key_ops->Clear();
1259   key_ops->AppendString("encrypt");
1260   key_ops->AppendString("decrypt");
1261   EXPECT_EQ(Status::Success(),
1262             ImportKeyJwkFromDict(dict,
1263                                  aes_cbc_algorithm,
1264                                  false,
1265                                  blink::WebCryptoKeyUsageDecrypt |
1266                                      blink::WebCryptoKeyUsageEncrypt,
1267                                  &key));
1268   EXPECT_EQ(blink::WebCryptoKeyUsageDecrypt | blink::WebCryptoKeyUsageEncrypt,
1269             key.usages());
1270
1271   // Test constrained key usage (input usage is a subset of JWK usage).
1272   key_ops->Clear();
1273   key_ops->AppendString("encrypt");
1274   key_ops->AppendString("decrypt");
1275   EXPECT_EQ(Status::Success(),
1276             ImportKeyJwkFromDict(dict,
1277                                  aes_cbc_algorithm,
1278                                  false,
1279                                  blink::WebCryptoKeyUsageDecrypt,
1280                                  &key));
1281   EXPECT_EQ(blink::WebCryptoKeyUsageDecrypt, key.usages());
1282
1283   // Test failure if input usage is NOT a strict subset of the JWK usage.
1284   key_ops->Clear();
1285   key_ops->AppendString("encrypt");
1286   EXPECT_EQ(Status::ErrorJwkKeyopsInconsistent(),
1287             ImportKeyJwkFromDict(dict,
1288                                  aes_cbc_algorithm,
1289                                  false,
1290                                  blink::WebCryptoKeyUsageEncrypt |
1291                                      blink::WebCryptoKeyUsageDecrypt,
1292                                  &key));
1293
1294   // Test 'use' inconsistent with 'key_ops'.
1295   dict.SetString("alg", "HS256");
1296   dict.SetString("use", "sig");
1297   key_ops->AppendString("sign");
1298   key_ops->AppendString("verify");
1299   key_ops->AppendString("encrypt");
1300   EXPECT_EQ(Status::ErrorJwkUseAndKeyopsInconsistent(),
1301             ImportKeyJwkFromDict(
1302                 dict,
1303                 hmac_algorithm,
1304                 false,
1305                 blink::WebCryptoKeyUsageSign | blink::WebCryptoKeyUsageVerify,
1306                 &key));
1307
1308   // Test JWK composite 'sig' use
1309   dict.Remove("key_ops", NULL);
1310   dict.SetString("use", "sig");
1311   EXPECT_EQ(Status::Success(),
1312             ImportKeyJwkFromDict(
1313                 dict,
1314                 hmac_algorithm,
1315                 false,
1316                 blink::WebCryptoKeyUsageSign | blink::WebCryptoKeyUsageVerify,
1317                 &key));
1318   EXPECT_EQ(blink::WebCryptoKeyUsageSign | blink::WebCryptoKeyUsageVerify,
1319             key.usages());
1320
1321   // Test JWK composite use 'enc' usage
1322   dict.SetString("alg", "A128CBC");
1323   dict.SetString("use", "enc");
1324   EXPECT_EQ(Status::Success(),
1325             ImportKeyJwkFromDict(dict,
1326                                  aes_cbc_algorithm,
1327                                  false,
1328                                  blink::WebCryptoKeyUsageDecrypt |
1329                                      blink::WebCryptoKeyUsageEncrypt |
1330                                      blink::WebCryptoKeyUsageWrapKey |
1331                                      blink::WebCryptoKeyUsageUnwrapKey,
1332                                  &key));
1333   EXPECT_EQ(blink::WebCryptoKeyUsageDecrypt | blink::WebCryptoKeyUsageEncrypt |
1334                 blink::WebCryptoKeyUsageWrapKey |
1335                 blink::WebCryptoKeyUsageUnwrapKey,
1336             key.usages());
1337 }
1338
1339 TEST_F(SharedCryptoTest, ImportJwkFailures) {
1340   blink::WebCryptoKey key = blink::WebCryptoKey::createNull();
1341   blink::WebCryptoAlgorithm algorithm =
1342       CreateAlgorithm(blink::WebCryptoAlgorithmIdAesCbc);
1343   blink::WebCryptoKeyUsageMask usage_mask = blink::WebCryptoKeyUsageEncrypt;
1344
1345   // Baseline pass: each test below breaks a single item, so we start with a
1346   // passing case to make sure each failure is caused by the isolated break.
1347   // Each breaking subtest below resets the dictionary to this passing case when
1348   // complete.
1349   base::DictionaryValue dict;
1350   RestoreJwkOctDictionary(&dict);
1351   EXPECT_EQ(Status::Success(),
1352             ImportKeyJwkFromDict(dict, algorithm, false, usage_mask, &key));
1353
1354   // Fail on empty JSON.
1355   EXPECT_EQ(
1356       Status::ErrorImportEmptyKeyData(),
1357       ImportKeyJwk(
1358           CryptoData(MakeJsonVector("")), algorithm, false, usage_mask, &key));
1359
1360   // Fail on invalid JSON.
1361   const std::vector<uint8> bad_json_vec = MakeJsonVector(
1362       "{"
1363       "\"kty\"         : \"oct\","
1364       "\"alg\"         : \"HS256\","
1365       "\"use\"         : ");
1366   EXPECT_EQ(Status::ErrorJwkNotDictionary(),
1367             ImportKeyJwk(
1368                 CryptoData(bad_json_vec), algorithm, false, usage_mask, &key));
1369
1370   // Fail on JWK alg present but unrecognized.
1371   dict.SetString("alg", "A127CBC");
1372   EXPECT_EQ(Status::ErrorJwkUnrecognizedAlgorithm(),
1373             ImportKeyJwkFromDict(dict, algorithm, false, usage_mask, &key));
1374   RestoreJwkOctDictionary(&dict);
1375
1376   // Fail on invalid kty.
1377   dict.SetString("kty", "foo");
1378   EXPECT_EQ(Status::ErrorJwkUnrecognizedKty(),
1379             ImportKeyJwkFromDict(dict, algorithm, false, usage_mask, &key));
1380   RestoreJwkOctDictionary(&dict);
1381
1382   // Fail on missing kty.
1383   dict.Remove("kty", NULL);
1384   EXPECT_EQ(Status::ErrorJwkPropertyMissing("kty"),
1385             ImportKeyJwkFromDict(dict, algorithm, false, usage_mask, &key));
1386   RestoreJwkOctDictionary(&dict);
1387
1388   // Fail on kty wrong type.
1389   dict.SetDouble("kty", 0.1);
1390   EXPECT_EQ(Status::ErrorJwkPropertyWrongType("kty", "string"),
1391             ImportKeyJwkFromDict(dict, algorithm, false, usage_mask, &key));
1392   RestoreJwkOctDictionary(&dict);
1393
1394   // Fail on invalid use.
1395   dict.SetString("use", "foo");
1396   EXPECT_EQ(Status::ErrorJwkUnrecognizedUse(),
1397             ImportKeyJwkFromDict(dict, algorithm, false, usage_mask, &key));
1398   RestoreJwkOctDictionary(&dict);
1399
1400   // Fail on invalid use (wrong type).
1401   dict.SetBoolean("use", true);
1402   EXPECT_EQ(Status::ErrorJwkPropertyWrongType("use", "string"),
1403             ImportKeyJwkFromDict(dict, algorithm, false, usage_mask, &key));
1404   RestoreJwkOctDictionary(&dict);
1405
1406   // Fail on invalid extractable (wrong type).
1407   dict.SetInteger("ext", 0);
1408   EXPECT_EQ(Status::ErrorJwkPropertyWrongType("ext", "boolean"),
1409             ImportKeyJwkFromDict(dict, algorithm, false, usage_mask, &key));
1410   RestoreJwkOctDictionary(&dict);
1411
1412   // Fail on invalid key_ops (wrong type).
1413   dict.SetBoolean("key_ops", true);
1414   EXPECT_EQ(Status::ErrorJwkPropertyWrongType("key_ops", "list"),
1415             ImportKeyJwkFromDict(dict, algorithm, false, usage_mask, &key));
1416   RestoreJwkOctDictionary(&dict);
1417
1418   // Fail on inconsistent key_ops - asking for "encrypt" however JWK contains
1419   // only "foo".
1420   base::ListValue* key_ops = new base::ListValue;
1421   // Note: the following call makes dict assume ownership of key_ops.
1422   dict.Set("key_ops", key_ops);
1423   key_ops->AppendString("foo");
1424   EXPECT_EQ(Status::ErrorJwkKeyopsInconsistent(),
1425             ImportKeyJwkFromDict(dict, algorithm, false, usage_mask, &key));
1426   RestoreJwkOctDictionary(&dict);
1427 }
1428
1429 // Import a JWK with unrecognized values for "key_ops".
1430 TEST_F(SharedCryptoTest, ImportJwkUnrecognizedKeyOps) {
1431   blink::WebCryptoKey key = blink::WebCryptoKey::createNull();
1432   blink::WebCryptoAlgorithm algorithm =
1433       CreateAlgorithm(blink::WebCryptoAlgorithmIdAesCbc);
1434   blink::WebCryptoKeyUsageMask usage_mask = blink::WebCryptoKeyUsageEncrypt;
1435
1436   base::DictionaryValue dict;
1437   RestoreJwkOctDictionary(&dict);
1438
1439   base::ListValue* key_ops = new base::ListValue;
1440   dict.Set("key_ops", key_ops);
1441   key_ops->AppendString("foo");
1442   key_ops->AppendString("bar");
1443   key_ops->AppendString("baz");
1444   key_ops->AppendString("encrypt");
1445   EXPECT_EQ(Status::Success(),
1446             ImportKeyJwkFromDict(dict, algorithm, false, usage_mask, &key));
1447 }
1448
1449 // Import a JWK with a value in key_ops array that is not a string.
1450 TEST_F(SharedCryptoTest, ImportJwkNonStringKeyOp) {
1451   blink::WebCryptoKey key = blink::WebCryptoKey::createNull();
1452   blink::WebCryptoAlgorithm algorithm =
1453       CreateAlgorithm(blink::WebCryptoAlgorithmIdAesCbc);
1454   blink::WebCryptoKeyUsageMask usage_mask = blink::WebCryptoKeyUsageEncrypt;
1455
1456   base::DictionaryValue dict;
1457   RestoreJwkOctDictionary(&dict);
1458
1459   base::ListValue* key_ops = new base::ListValue;
1460   dict.Set("key_ops", key_ops);
1461   key_ops->AppendString("encrypt");
1462   key_ops->AppendInteger(3);
1463   EXPECT_EQ(Status::ErrorJwkPropertyWrongType("key_ops[1]", "string"),
1464             ImportKeyJwkFromDict(dict, algorithm, false, usage_mask, &key));
1465 }
1466
1467 TEST_F(SharedCryptoTest, ImportJwkOctFailures) {
1468   base::DictionaryValue dict;
1469   RestoreJwkOctDictionary(&dict);
1470   blink::WebCryptoAlgorithm algorithm =
1471       CreateAlgorithm(blink::WebCryptoAlgorithmIdAesCbc);
1472   blink::WebCryptoKeyUsageMask usage_mask = blink::WebCryptoKeyUsageEncrypt;
1473   blink::WebCryptoKey key = blink::WebCryptoKey::createNull();
1474
1475   // Baseline pass.
1476   EXPECT_EQ(Status::Success(),
1477             ImportKeyJwkFromDict(dict, algorithm, false, usage_mask, &key));
1478   EXPECT_EQ(algorithm.id(), key.algorithm().id());
1479   EXPECT_FALSE(key.extractable());
1480   EXPECT_EQ(blink::WebCryptoKeyUsageEncrypt, key.usages());
1481   EXPECT_EQ(blink::WebCryptoKeyTypeSecret, key.type());
1482
1483   // The following are specific failure cases for when kty = "oct".
1484
1485   // Fail on missing k.
1486   dict.Remove("k", NULL);
1487   EXPECT_EQ(Status::ErrorJwkPropertyMissing("k"),
1488             ImportKeyJwkFromDict(dict, algorithm, false, usage_mask, &key));
1489   RestoreJwkOctDictionary(&dict);
1490
1491   // Fail on bad b64 encoding for k.
1492   dict.SetString("k", "Qk3f0DsytU8lfza2au #$% Htaw2xpop9GYyTuH0p5GghxTI=");
1493   EXPECT_EQ(Status::ErrorJwkBase64Decode("k"),
1494             ImportKeyJwkFromDict(dict, algorithm, false, usage_mask, &key));
1495   RestoreJwkOctDictionary(&dict);
1496
1497   // Fail on empty k.
1498   dict.SetString("k", "");
1499   EXPECT_EQ(Status::ErrorJwkIncorrectKeyLength(),
1500             ImportKeyJwkFromDict(dict, algorithm, false, usage_mask, &key));
1501   RestoreJwkOctDictionary(&dict);
1502
1503   // Fail on k actual length (120 bits) inconsistent with the embedded JWK alg
1504   // value (128) for an AES key.
1505   dict.SetString("k", "AVj42h0Y5aqGtE3yluKL");
1506   EXPECT_EQ(Status::ErrorJwkIncorrectKeyLength(),
1507             ImportKeyJwkFromDict(dict, algorithm, false, usage_mask, &key));
1508   RestoreJwkOctDictionary(&dict);
1509
1510   // Fail on k actual length (192 bits) inconsistent with the embedded JWK alg
1511   // value (128) for an AES key.
1512   dict.SetString("k", "dGhpcyAgaXMgIDI0ICBieXRlcyBsb25n");
1513   EXPECT_EQ(Status::ErrorJwkIncorrectKeyLength(),
1514             ImportKeyJwkFromDict(dict, algorithm, false, usage_mask, &key));
1515   RestoreJwkOctDictionary(&dict);
1516 }
1517
1518 TEST_F(SharedCryptoTest, MAYBE(ImportExportJwkRsaPublicKey)) {
1519   if (!SupportsRsaKeyImport())
1520     return;
1521
1522   const bool supports_rsa_oaep = SupportsRsaOaep();
1523   if (!supports_rsa_oaep) {
1524     LOG(WARNING) << "RSA-OAEP not supported on this platform. Skipping some"
1525                  << "tests.";
1526   }
1527
1528   struct TestCase {
1529     const blink::WebCryptoAlgorithm algorithm;
1530     const blink::WebCryptoKeyUsageMask usage;
1531     const char* const jwk_alg;
1532   };
1533   const TestCase kTests[] = {
1534       // RSASSA-PKCS1-v1_5 SHA-1
1535       {CreateRsaHashedImportAlgorithm(
1536            blink::WebCryptoAlgorithmIdRsaSsaPkcs1v1_5,
1537            blink::WebCryptoAlgorithmIdSha1),
1538        blink::WebCryptoKeyUsageVerify, "RS1"},
1539       // RSASSA-PKCS1-v1_5 SHA-256
1540       {CreateRsaHashedImportAlgorithm(
1541            blink::WebCryptoAlgorithmIdRsaSsaPkcs1v1_5,
1542            blink::WebCryptoAlgorithmIdSha256),
1543        blink::WebCryptoKeyUsageVerify, "RS256"},
1544       // RSASSA-PKCS1-v1_5 SHA-384
1545       {CreateRsaHashedImportAlgorithm(
1546            blink::WebCryptoAlgorithmIdRsaSsaPkcs1v1_5,
1547            blink::WebCryptoAlgorithmIdSha384),
1548        blink::WebCryptoKeyUsageVerify, "RS384"},
1549       // RSASSA-PKCS1-v1_5 SHA-512
1550       {CreateRsaHashedImportAlgorithm(
1551            blink::WebCryptoAlgorithmIdRsaSsaPkcs1v1_5,
1552            blink::WebCryptoAlgorithmIdSha512),
1553        blink::WebCryptoKeyUsageVerify, "RS512"},
1554       // RSA-OAEP with SHA-1 and MGF-1 / SHA-1
1555       {CreateRsaHashedImportAlgorithm(blink::WebCryptoAlgorithmIdRsaOaep,
1556                                       blink::WebCryptoAlgorithmIdSha1),
1557        blink::WebCryptoKeyUsageEncrypt, "RSA-OAEP"},
1558       // RSA-OAEP with SHA-256 and MGF-1 / SHA-256
1559       {CreateRsaHashedImportAlgorithm(blink::WebCryptoAlgorithmIdRsaOaep,
1560                                       blink::WebCryptoAlgorithmIdSha256),
1561        blink::WebCryptoKeyUsageEncrypt, "RSA-OAEP-256"},
1562       // RSA-OAEP with SHA-384 and MGF-1 / SHA-384
1563       {CreateRsaHashedImportAlgorithm(blink::WebCryptoAlgorithmIdRsaOaep,
1564                                       blink::WebCryptoAlgorithmIdSha384),
1565        blink::WebCryptoKeyUsageEncrypt, "RSA-OAEP-384"},
1566       // RSA-OAEP with SHA-512 and MGF-1 / SHA-512
1567       {CreateRsaHashedImportAlgorithm(blink::WebCryptoAlgorithmIdRsaOaep,
1568                                       blink::WebCryptoAlgorithmIdSha512),
1569        blink::WebCryptoKeyUsageEncrypt, "RSA-OAEP-512"}};
1570
1571   for (size_t test_index = 0; test_index < ARRAYSIZE_UNSAFE(kTests);
1572        ++test_index) {
1573     SCOPED_TRACE(test_index);
1574     const TestCase& test = kTests[test_index];
1575     if (!supports_rsa_oaep &&
1576         test.algorithm.id() == blink::WebCryptoAlgorithmIdRsaOaep) {
1577       continue;
1578     }
1579
1580     // Import the spki to create a public key
1581     blink::WebCryptoKey public_key = blink::WebCryptoKey::createNull();
1582     ASSERT_EQ(Status::Success(),
1583               ImportKey(blink::WebCryptoKeyFormatSpki,
1584                         CryptoData(HexStringToBytes(kPublicKeySpkiDerHex)),
1585                         test.algorithm,
1586                         true,
1587                         test.usage,
1588                         &public_key));
1589
1590     // Export the public key as JWK and verify its contents
1591     std::vector<uint8> jwk;
1592     ASSERT_EQ(Status::Success(),
1593               ExportKey(blink::WebCryptoKeyFormatJwk, public_key, &jwk));
1594     EXPECT_TRUE(VerifyPublicJwk(jwk,
1595                                 test.jwk_alg,
1596                                 kPublicKeyModulusHex,
1597                                 kPublicKeyExponentHex,
1598                                 test.usage));
1599
1600     // Import the JWK back in to create a new key
1601     blink::WebCryptoKey public_key2 = blink::WebCryptoKey::createNull();
1602     ASSERT_EQ(
1603         Status::Success(),
1604         ImportKeyJwk(
1605             CryptoData(jwk), test.algorithm, true, test.usage, &public_key2));
1606     ASSERT_TRUE(public_key2.handle());
1607     EXPECT_EQ(blink::WebCryptoKeyTypePublic, public_key2.type());
1608     EXPECT_TRUE(public_key2.extractable());
1609     EXPECT_EQ(test.algorithm.id(), public_key2.algorithm().id());
1610
1611     // Only perform SPKI consistency test for RSA-SSA as its
1612     // export format is the same as kPublicKeySpkiDerHex
1613     if (test.algorithm.id() == blink::WebCryptoAlgorithmIdRsaSsaPkcs1v1_5) {
1614       // Export the new key as spki and compare to the original.
1615       std::vector<uint8> spki;
1616       ASSERT_EQ(Status::Success(),
1617                 ExportKey(blink::WebCryptoKeyFormatSpki, public_key2, &spki));
1618       EXPECT_BYTES_EQ_HEX(kPublicKeySpkiDerHex, CryptoData(spki));
1619     }
1620   }
1621 }
1622
1623 TEST_F(SharedCryptoTest, MAYBE(ImportJwkRsaFailures)) {
1624   base::DictionaryValue dict;
1625   RestoreJwkRsaDictionary(&dict);
1626   blink::WebCryptoAlgorithm algorithm =
1627       CreateRsaHashedImportAlgorithm(blink::WebCryptoAlgorithmIdRsaSsaPkcs1v1_5,
1628                                      blink::WebCryptoAlgorithmIdSha256);
1629   blink::WebCryptoKeyUsageMask usage_mask = blink::WebCryptoKeyUsageVerify;
1630   blink::WebCryptoKey key = blink::WebCryptoKey::createNull();
1631
1632   // An RSA public key JWK _must_ have an "n" (modulus) and an "e" (exponent)
1633   // entry, while an RSA private key must have those plus at least a "d"
1634   // (private exponent) entry.
1635   // See http://tools.ietf.org/html/draft-ietf-jose-json-web-algorithms-18,
1636   // section 6.3.
1637
1638   // Baseline pass.
1639   EXPECT_EQ(Status::Success(),
1640             ImportKeyJwkFromDict(dict, algorithm, false, usage_mask, &key));
1641   EXPECT_EQ(algorithm.id(), key.algorithm().id());
1642   EXPECT_FALSE(key.extractable());
1643   EXPECT_EQ(blink::WebCryptoKeyUsageVerify, key.usages());
1644   EXPECT_EQ(blink::WebCryptoKeyTypePublic, key.type());
1645
1646   // The following are specific failure cases for when kty = "RSA".
1647
1648   // Fail if either "n" or "e" is not present or malformed.
1649   const std::string kKtyParmName[] = {"n", "e"};
1650   for (size_t idx = 0; idx < ARRAYSIZE_UNSAFE(kKtyParmName); ++idx) {
1651     // Fail on missing parameter.
1652     dict.Remove(kKtyParmName[idx], NULL);
1653     EXPECT_NE(Status::Success(),
1654               ImportKeyJwkFromDict(dict, algorithm, false, usage_mask, &key));
1655     RestoreJwkRsaDictionary(&dict);
1656
1657     // Fail on bad b64 parameter encoding.
1658     dict.SetString(kKtyParmName[idx], "Qk3f0DsytU8lfza2au #$% Htaw2xpop9yTuH0");
1659     EXPECT_NE(Status::Success(),
1660               ImportKeyJwkFromDict(dict, algorithm, false, usage_mask, &key));
1661     RestoreJwkRsaDictionary(&dict);
1662
1663     // Fail on empty parameter.
1664     dict.SetString(kKtyParmName[idx], "");
1665     EXPECT_NE(Status::Success(),
1666               ImportKeyJwkFromDict(dict, algorithm, false, usage_mask, &key));
1667     RestoreJwkRsaDictionary(&dict);
1668   }
1669 }
1670
1671 TEST_F(SharedCryptoTest, MAYBE(ImportJwkInputConsistency)) {
1672   // The Web Crypto spec says that if a JWK value is present, but is
1673   // inconsistent with the input value, the operation must fail.
1674
1675   // Consistency rules when JWK value is not present: Inputs should be used.
1676   blink::WebCryptoKey key = blink::WebCryptoKey::createNull();
1677   bool extractable = false;
1678   blink::WebCryptoAlgorithm algorithm =
1679       CreateHmacImportAlgorithm(blink::WebCryptoAlgorithmIdSha256);
1680   blink::WebCryptoKeyUsageMask usage_mask = blink::WebCryptoKeyUsageVerify;
1681   base::DictionaryValue dict;
1682   dict.SetString("kty", "oct");
1683   dict.SetString("k", "l3nZEgZCeX8XRwJdWyK3rGB8qwjhdY8vOkbIvh4lxTuMao9Y_--hdg");
1684   std::vector<uint8> json_vec = MakeJsonVector(dict);
1685   EXPECT_EQ(
1686       Status::Success(),
1687       ImportKeyJwk(
1688           CryptoData(json_vec), algorithm, extractable, usage_mask, &key));
1689   EXPECT_TRUE(key.handle());
1690   EXPECT_EQ(blink::WebCryptoKeyTypeSecret, key.type());
1691   EXPECT_EQ(extractable, key.extractable());
1692   EXPECT_EQ(blink::WebCryptoAlgorithmIdHmac, key.algorithm().id());
1693   EXPECT_EQ(blink::WebCryptoAlgorithmIdSha256,
1694             key.algorithm().hmacParams()->hash().id());
1695   EXPECT_EQ(320u, key.algorithm().hmacParams()->lengthBits());
1696   EXPECT_EQ(blink::WebCryptoKeyUsageVerify, key.usages());
1697   key = blink::WebCryptoKey::createNull();
1698
1699   // Consistency rules when JWK value exists: Fail if inconsistency is found.
1700
1701   // Pass: All input values are consistent with the JWK values.
1702   dict.Clear();
1703   dict.SetString("kty", "oct");
1704   dict.SetString("alg", "HS256");
1705   dict.SetString("use", "sig");
1706   dict.SetBoolean("ext", false);
1707   dict.SetString("k", "l3nZEgZCeX8XRwJdWyK3rGB8qwjhdY8vOkbIvh4lxTuMao9Y_--hdg");
1708   json_vec = MakeJsonVector(dict);
1709   EXPECT_EQ(
1710       Status::Success(),
1711       ImportKeyJwk(
1712           CryptoData(json_vec), algorithm, extractable, usage_mask, &key));
1713
1714   // Extractable cases:
1715   // 1. input=T, JWK=F ==> fail (inconsistent)
1716   // 4. input=F, JWK=F ==> pass, result extractable is F
1717   // 2. input=T, JWK=T ==> pass, result extractable is T
1718   // 3. input=F, JWK=T ==> pass, result extractable is F
1719   EXPECT_EQ(
1720       Status::ErrorJwkExtInconsistent(),
1721       ImportKeyJwk(CryptoData(json_vec), algorithm, true, usage_mask, &key));
1722   EXPECT_EQ(
1723       Status::Success(),
1724       ImportKeyJwk(CryptoData(json_vec), algorithm, false, usage_mask, &key));
1725   EXPECT_FALSE(key.extractable());
1726   dict.SetBoolean("ext", true);
1727   EXPECT_EQ(Status::Success(),
1728             ImportKeyJwkFromDict(dict, algorithm, true, usage_mask, &key));
1729   EXPECT_TRUE(key.extractable());
1730   EXPECT_EQ(Status::Success(),
1731             ImportKeyJwkFromDict(dict, algorithm, false, usage_mask, &key));
1732   EXPECT_FALSE(key.extractable());
1733   dict.SetBoolean("ext", true);  // restore previous value
1734
1735   // Fail: Input algorithm (AES-CBC) is inconsistent with JWK value
1736   // (HMAC SHA256).
1737   EXPECT_EQ(Status::ErrorJwkAlgorithmInconsistent(),
1738             ImportKeyJwk(CryptoData(json_vec),
1739                          CreateAlgorithm(blink::WebCryptoAlgorithmIdAesCbc),
1740                          extractable,
1741                          blink::WebCryptoKeyUsageEncrypt,
1742                          &key));
1743
1744   // Fail: Input algorithm (HMAC SHA1) is inconsistent with JWK value
1745   // (HMAC SHA256).
1746   EXPECT_EQ(
1747       Status::ErrorJwkAlgorithmInconsistent(),
1748       ImportKeyJwk(CryptoData(json_vec),
1749                    CreateHmacImportAlgorithm(blink::WebCryptoAlgorithmIdSha1),
1750                    extractable,
1751                    usage_mask,
1752                    &key));
1753
1754   // Pass: JWK alg missing but input algorithm specified: use input value
1755   dict.Remove("alg", NULL);
1756   EXPECT_EQ(Status::Success(),
1757             ImportKeyJwkFromDict(
1758                 dict,
1759                 CreateHmacImportAlgorithm(blink::WebCryptoAlgorithmIdSha256),
1760                 extractable,
1761                 usage_mask,
1762                 &key));
1763   EXPECT_EQ(blink::WebCryptoAlgorithmIdHmac, algorithm.id());
1764   dict.SetString("alg", "HS256");
1765
1766   // Fail: Input usage_mask (encrypt) is not a subset of the JWK value
1767   // (sign|verify). Moreover "encrypt" is not a valid usage for HMAC.
1768   EXPECT_EQ(Status::ErrorCreateKeyBadUsages(),
1769             ImportKeyJwk(CryptoData(json_vec),
1770                          algorithm,
1771                          extractable,
1772                          blink::WebCryptoKeyUsageEncrypt,
1773                          &key));
1774
1775   // Fail: Input usage_mask (encrypt|sign|verify) is not a subset of the JWK
1776   // value (sign|verify). Moreover "encrypt" is not a valid usage for HMAC.
1777   usage_mask = blink::WebCryptoKeyUsageEncrypt | blink::WebCryptoKeyUsageSign |
1778                blink::WebCryptoKeyUsageVerify;
1779   EXPECT_EQ(
1780       Status::ErrorCreateKeyBadUsages(),
1781       ImportKeyJwk(
1782           CryptoData(json_vec), algorithm, extractable, usage_mask, &key));
1783
1784   // TODO(padolph): kty vs alg consistency tests: Depending on the kty value,
1785   // only certain alg values are permitted. For example, when kty = "RSA" alg
1786   // must be of the RSA family, or when kty = "oct" alg must be symmetric
1787   // algorithm.
1788
1789   // TODO(padolph): key_ops consistency tests
1790 }
1791
1792 TEST_F(SharedCryptoTest, MAYBE(ImportJwkHappy)) {
1793   // This test verifies the happy path of JWK import, including the application
1794   // of the imported key material.
1795
1796   blink::WebCryptoKey key = blink::WebCryptoKey::createNull();
1797   bool extractable = false;
1798   blink::WebCryptoAlgorithm algorithm =
1799       CreateHmacImportAlgorithm(blink::WebCryptoAlgorithmIdSha256);
1800   blink::WebCryptoKeyUsageMask usage_mask = blink::WebCryptoKeyUsageSign;
1801
1802   // Import a symmetric key JWK and HMAC-SHA256 sign()
1803   // Uses the first SHA256 test vector from the HMAC sample set above.
1804
1805   base::DictionaryValue dict;
1806   dict.SetString("kty", "oct");
1807   dict.SetString("alg", "HS256");
1808   dict.SetString("use", "sig");
1809   dict.SetBoolean("ext", false);
1810   dict.SetString("k", "l3nZEgZCeX8XRwJdWyK3rGB8qwjhdY8vOkbIvh4lxTuMao9Y_--hdg");
1811
1812   ASSERT_EQ(
1813       Status::Success(),
1814       ImportKeyJwkFromDict(dict, algorithm, extractable, usage_mask, &key));
1815
1816   EXPECT_EQ(blink::WebCryptoAlgorithmIdSha256,
1817             key.algorithm().hmacParams()->hash().id());
1818
1819   const std::vector<uint8> message_raw = HexStringToBytes(
1820       "b1689c2591eaf3c9e66070f8a77954ffb81749f1b00346f9dfe0b2ee905dcc288baf4a"
1821       "92de3f4001dd9f44c468c3d07d6c6ee82faceafc97c2fc0fc0601719d2dcd0aa2aec92"
1822       "d1b0ae933c65eb06a03c9c935c2bad0459810241347ab87e9f11adb30415424c6c7f5f"
1823       "22a003b8ab8de54f6ded0e3ab9245fa79568451dfa258e");
1824
1825   std::vector<uint8> output;
1826
1827   ASSERT_EQ(Status::Success(),
1828             Sign(CreateAlgorithm(blink::WebCryptoAlgorithmIdHmac),
1829                  key,
1830                  CryptoData(message_raw),
1831                  &output));
1832
1833   const std::string mac_raw =
1834       "769f00d3e6a6cc1fb426a14a4f76c6462e6149726e0dee0ec0cf97a16605ac8b";
1835
1836   EXPECT_BYTES_EQ_HEX(mac_raw, output);
1837
1838   // TODO(padolph): Import an RSA public key JWK and use it
1839 }
1840
1841 TEST_F(SharedCryptoTest, MAYBE(ImportExportJwkSymmetricKey)) {
1842   // Raw keys are generated by openssl:
1843   // % openssl rand -hex <key length bytes>
1844   const char* const key_hex_128 = "3f1e7cd4f6f8543f6b1e16002e688623";
1845   const char* const key_hex_256 =
1846       "bd08286b81a74783fd1ccf46b7e05af84ee25ae021210074159e0c4d9d907692";
1847   const char* const key_hex_384 =
1848       "a22c5441c8b185602283d64c7221de1d0951e706bfc09539435ec0e0ed614e1d406623f2"
1849       "b31d31819fec30993380dd82";
1850   const char* const key_hex_512 =
1851       "5834f639000d4cf82de124fbfd26fb88d463e99f839a76ba41ac88967c80a3f61e1239a4"
1852       "52e573dba0750e988152988576efd75b8d0229b7aca2ada2afd392ee";
1853   const blink::WebCryptoAlgorithm aes_cbc_alg =
1854       webcrypto::CreateAlgorithm(blink::WebCryptoAlgorithmIdAesCbc);
1855   const blink::WebCryptoAlgorithm aes_gcm_alg =
1856       webcrypto::CreateAlgorithm(blink::WebCryptoAlgorithmIdAesGcm);
1857   const blink::WebCryptoAlgorithm aes_kw_alg =
1858       webcrypto::CreateAlgorithm(blink::WebCryptoAlgorithmIdAesKw);
1859   const blink::WebCryptoAlgorithm hmac_sha_1_alg =
1860       webcrypto::CreateHmacImportAlgorithm(blink::WebCryptoAlgorithmIdSha1);
1861   const blink::WebCryptoAlgorithm hmac_sha_256_alg =
1862       webcrypto::CreateHmacImportAlgorithm(blink::WebCryptoAlgorithmIdSha256);
1863   const blink::WebCryptoAlgorithm hmac_sha_384_alg =
1864       webcrypto::CreateHmacImportAlgorithm(blink::WebCryptoAlgorithmIdSha384);
1865   const blink::WebCryptoAlgorithm hmac_sha_512_alg =
1866       webcrypto::CreateHmacImportAlgorithm(blink::WebCryptoAlgorithmIdSha512);
1867
1868   struct TestCase {
1869     const char* const key_hex;
1870     const blink::WebCryptoAlgorithm algorithm;
1871     const blink::WebCryptoKeyUsageMask usage;
1872     const char* const jwk_alg;
1873   };
1874
1875   // TODO(padolph): Test AES-CTR JWK export, once AES-CTR import works.
1876   const TestCase kTests[] = {
1877       // AES-CBC 128
1878       {key_hex_128, aes_cbc_alg,
1879        blink::WebCryptoKeyUsageEncrypt | blink::WebCryptoKeyUsageDecrypt,
1880        "A128CBC"},
1881       // AES-CBC 256
1882       {key_hex_256, aes_cbc_alg, blink::WebCryptoKeyUsageDecrypt, "A256CBC"},
1883       // AES-GCM 128
1884       {key_hex_128, aes_gcm_alg,
1885        blink::WebCryptoKeyUsageEncrypt | blink::WebCryptoKeyUsageDecrypt,
1886        "A128GCM"},
1887       // AES-GCM 256
1888       {key_hex_256, aes_gcm_alg, blink::WebCryptoKeyUsageDecrypt, "A256GCM"},
1889       // AES-KW 128
1890       {key_hex_128, aes_kw_alg,
1891        blink::WebCryptoKeyUsageWrapKey | blink::WebCryptoKeyUsageUnwrapKey,
1892        "A128KW"},
1893       // AES-KW 256
1894       {key_hex_256, aes_kw_alg,
1895        blink::WebCryptoKeyUsageWrapKey | blink::WebCryptoKeyUsageUnwrapKey,
1896        "A256KW"},
1897       // HMAC SHA-1
1898       {key_hex_256, hmac_sha_1_alg,
1899        blink::WebCryptoKeyUsageSign | blink::WebCryptoKeyUsageVerify, "HS1"},
1900       // HMAC SHA-384
1901       {key_hex_384, hmac_sha_384_alg, blink::WebCryptoKeyUsageSign, "HS384"},
1902       // HMAC SHA-512
1903       {key_hex_512, hmac_sha_512_alg, blink::WebCryptoKeyUsageVerify, "HS512"},
1904       // Large usage value
1905       {key_hex_256, aes_cbc_alg,
1906        blink::WebCryptoKeyUsageEncrypt | blink::WebCryptoKeyUsageDecrypt |
1907            blink::WebCryptoKeyUsageWrapKey | blink::WebCryptoKeyUsageUnwrapKey,
1908        "A256CBC"},
1909       // Zero usage value
1910       {key_hex_512, hmac_sha_512_alg, 0, "HS512"},
1911   };
1912
1913   // Round-trip import/export each key.
1914
1915   blink::WebCryptoKey key = blink::WebCryptoKey::createNull();
1916   std::vector<uint8> json;
1917   for (size_t test_index = 0; test_index < ARRAYSIZE_UNSAFE(kTests);
1918        ++test_index) {
1919     SCOPED_TRACE(test_index);
1920     const TestCase& test = kTests[test_index];
1921
1922     // Skip AES-GCM tests where not supported.
1923     if (test.algorithm.id() == blink::WebCryptoAlgorithmIdAesGcm &&
1924         !SupportsAesGcm()) {
1925       continue;
1926     }
1927
1928     // Import a raw key.
1929     key = ImportSecretKeyFromRaw(
1930         HexStringToBytes(test.key_hex), test.algorithm, test.usage);
1931
1932     // Export the key in JWK format and validate.
1933     ASSERT_EQ(Status::Success(),
1934               ExportKey(blink::WebCryptoKeyFormatJwk, key, &json));
1935     EXPECT_TRUE(VerifySecretJwk(json, test.jwk_alg, test.key_hex, test.usage));
1936
1937     // Import the JWK-formatted key.
1938     ASSERT_EQ(
1939         Status::Success(),
1940         ImportKeyJwk(CryptoData(json), test.algorithm, true, test.usage, &key));
1941     EXPECT_TRUE(key.handle());
1942     EXPECT_EQ(blink::WebCryptoKeyTypeSecret, key.type());
1943     EXPECT_EQ(test.algorithm.id(), key.algorithm().id());
1944     EXPECT_EQ(true, key.extractable());
1945     EXPECT_EQ(test.usage, key.usages());
1946
1947     // Export the key in raw format and compare to the original.
1948     std::vector<uint8> key_raw_out;
1949     ASSERT_EQ(Status::Success(),
1950               ExportKey(blink::WebCryptoKeyFormatRaw, key, &key_raw_out));
1951     EXPECT_BYTES_EQ_HEX(test.key_hex, key_raw_out);
1952   }
1953 }
1954
1955 TEST_F(SharedCryptoTest, MAYBE(ExportJwkEmptySymmetricKey)) {
1956   const blink::WebCryptoAlgorithm import_algorithm =
1957       webcrypto::CreateHmacImportAlgorithm(blink::WebCryptoAlgorithmIdSha1);
1958
1959   blink::WebCryptoKeyUsageMask usages = blink::WebCryptoKeyUsageSign;
1960   blink::WebCryptoKey key = blink::WebCryptoKey::createNull();
1961
1962   // Import a zero-byte HMAC key.
1963   const char key_data_hex[] = "";
1964   key = ImportSecretKeyFromRaw(
1965       HexStringToBytes(key_data_hex), import_algorithm, usages);
1966   EXPECT_EQ(0u, key.algorithm().hmacParams()->lengthBits());
1967
1968   // Export the key in JWK format and validate.
1969   std::vector<uint8> json;
1970   ASSERT_EQ(Status::Success(),
1971             ExportKey(blink::WebCryptoKeyFormatJwk, key, &json));
1972   EXPECT_TRUE(VerifySecretJwk(json, "HS1", key_data_hex, usages));
1973
1974   // Now try re-importing the JWK key.
1975   key = blink::WebCryptoKey::createNull();
1976   EXPECT_EQ(Status::Success(),
1977             ImportKey(blink::WebCryptoKeyFormatJwk,
1978                       CryptoData(json),
1979                       import_algorithm,
1980                       true,
1981                       usages,
1982                       &key));
1983
1984   EXPECT_EQ(blink::WebCryptoKeyTypeSecret, key.type());
1985   EXPECT_EQ(0u, key.algorithm().hmacParams()->lengthBits());
1986
1987   std::vector<uint8> exported_key_data;
1988   EXPECT_EQ(Status::Success(),
1989             ExportKey(blink::WebCryptoKeyFormatRaw, key, &exported_key_data));
1990
1991   EXPECT_EQ(0u, exported_key_data.size());
1992 }
1993
1994 TEST_F(SharedCryptoTest, MAYBE(ImportExportSpki)) {
1995   if (!SupportsRsaKeyImport())
1996     return;
1997
1998   // Passing case: Import a valid RSA key in SPKI format.
1999   blink::WebCryptoKey key = blink::WebCryptoKey::createNull();
2000   ASSERT_EQ(Status::Success(),
2001             ImportKey(blink::WebCryptoKeyFormatSpki,
2002                       CryptoData(HexStringToBytes(kPublicKeySpkiDerHex)),
2003                       CreateRsaHashedImportAlgorithm(
2004                           blink::WebCryptoAlgorithmIdRsaSsaPkcs1v1_5,
2005                           blink::WebCryptoAlgorithmIdSha256),
2006                       true,
2007                       blink::WebCryptoKeyUsageVerify,
2008                       &key));
2009   EXPECT_TRUE(key.handle());
2010   EXPECT_EQ(blink::WebCryptoKeyTypePublic, key.type());
2011   EXPECT_TRUE(key.extractable());
2012   EXPECT_EQ(blink::WebCryptoKeyUsageVerify, key.usages());
2013   EXPECT_EQ(kModulusLengthBits,
2014             key.algorithm().rsaHashedParams()->modulusLengthBits());
2015   EXPECT_BYTES_EQ_HEX(
2016       "010001",
2017       CryptoData(key.algorithm().rsaHashedParams()->publicExponent()));
2018
2019   // Failing case: Empty SPKI data
2020   EXPECT_EQ(
2021       Status::ErrorImportEmptyKeyData(),
2022       ImportKey(blink::WebCryptoKeyFormatSpki,
2023                 CryptoData(std::vector<uint8>()),
2024                 CreateAlgorithm(blink::WebCryptoAlgorithmIdRsaSsaPkcs1v1_5),
2025                 true,
2026                 blink::WebCryptoKeyUsageVerify,
2027                 &key));
2028
2029   // Failing case: Bad DER encoding.
2030   EXPECT_EQ(
2031       Status::DataError(),
2032       ImportKey(blink::WebCryptoKeyFormatSpki,
2033                 CryptoData(HexStringToBytes("618333c4cb")),
2034                 CreateAlgorithm(blink::WebCryptoAlgorithmIdRsaSsaPkcs1v1_5),
2035                 true,
2036                 blink::WebCryptoKeyUsageVerify,
2037                 &key));
2038
2039   // Failing case: Import RSA key but provide an inconsistent input algorithm.
2040   EXPECT_EQ(Status::DataError(),
2041             ImportKey(blink::WebCryptoKeyFormatSpki,
2042                       CryptoData(HexStringToBytes(kPublicKeySpkiDerHex)),
2043                       CreateAlgorithm(blink::WebCryptoAlgorithmIdAesCbc),
2044                       true,
2045                       blink::WebCryptoKeyUsageEncrypt,
2046                       &key));
2047
2048   // Passing case: Export a previously imported RSA public key in SPKI format
2049   // and compare to original data.
2050   std::vector<uint8> output;
2051   ASSERT_EQ(Status::Success(),
2052             ExportKey(blink::WebCryptoKeyFormatSpki, key, &output));
2053   EXPECT_BYTES_EQ_HEX(kPublicKeySpkiDerHex, output);
2054
2055   // Failing case: Try to export a previously imported RSA public key in raw
2056   // format (not allowed for a public key).
2057   EXPECT_EQ(Status::ErrorUnexpectedKeyType(),
2058             ExportKey(blink::WebCryptoKeyFormatRaw, key, &output));
2059
2060   // Failing case: Try to export a non-extractable key
2061   ASSERT_EQ(Status::Success(),
2062             ImportKey(blink::WebCryptoKeyFormatSpki,
2063                       CryptoData(HexStringToBytes(kPublicKeySpkiDerHex)),
2064                       CreateRsaHashedImportAlgorithm(
2065                           blink::WebCryptoAlgorithmIdRsaSsaPkcs1v1_5,
2066                           blink::WebCryptoAlgorithmIdSha256),
2067                       false,
2068                       blink::WebCryptoKeyUsageVerify,
2069                       &key));
2070   EXPECT_TRUE(key.handle());
2071   EXPECT_FALSE(key.extractable());
2072   EXPECT_EQ(Status::ErrorKeyNotExtractable(),
2073             ExportKey(blink::WebCryptoKeyFormatSpki, key, &output));
2074
2075   // TODO(eroman): Failing test: Import a SPKI with an unrecognized hash OID
2076   // TODO(eroman): Failing test: Import a SPKI with invalid algorithm params
2077   // TODO(eroman): Failing test: Import a SPKI with inconsistent parameters
2078   // (e.g. SHA-1 in OID, SHA-256 in params)
2079   // TODO(eroman): Failing test: Import a SPKI for RSA-SSA, but with params
2080   // as OAEP/PSS
2081 }
2082
2083 TEST_F(SharedCryptoTest, MAYBE(ImportExportPkcs8)) {
2084   if (!SupportsRsaKeyImport())
2085     return;
2086
2087   // Passing case: Import a valid RSA key in PKCS#8 format.
2088   blink::WebCryptoKey key = blink::WebCryptoKey::createNull();
2089   ASSERT_EQ(Status::Success(),
2090             ImportKey(blink::WebCryptoKeyFormatPkcs8,
2091                       CryptoData(HexStringToBytes(kPrivateKeyPkcs8DerHex)),
2092                       CreateRsaHashedImportAlgorithm(
2093                           blink::WebCryptoAlgorithmIdRsaSsaPkcs1v1_5,
2094                           blink::WebCryptoAlgorithmIdSha1),
2095                       true,
2096                       blink::WebCryptoKeyUsageSign,
2097                       &key));
2098   EXPECT_TRUE(key.handle());
2099   EXPECT_EQ(blink::WebCryptoKeyTypePrivate, key.type());
2100   EXPECT_TRUE(key.extractable());
2101   EXPECT_EQ(blink::WebCryptoKeyUsageSign, key.usages());
2102   EXPECT_EQ(blink::WebCryptoAlgorithmIdSha1,
2103             key.algorithm().rsaHashedParams()->hash().id());
2104   EXPECT_EQ(kModulusLengthBits,
2105             key.algorithm().rsaHashedParams()->modulusLengthBits());
2106   EXPECT_BYTES_EQ_HEX(
2107       "010001",
2108       CryptoData(key.algorithm().rsaHashedParams()->publicExponent()));
2109
2110   std::vector<uint8> exported_key;
2111   ASSERT_EQ(Status::Success(),
2112             ExportKey(blink::WebCryptoKeyFormatPkcs8, key, &exported_key));
2113   EXPECT_BYTES_EQ_HEX(kPrivateKeyPkcs8DerHex, exported_key);
2114
2115   // Failing case: Empty PKCS#8 data
2116   EXPECT_EQ(Status::ErrorImportEmptyKeyData(),
2117             ImportKey(blink::WebCryptoKeyFormatPkcs8,
2118                       CryptoData(std::vector<uint8>()),
2119                       CreateRsaHashedImportAlgorithm(
2120                           blink::WebCryptoAlgorithmIdRsaSsaPkcs1v1_5,
2121                           blink::WebCryptoAlgorithmIdSha1),
2122                       true,
2123                       blink::WebCryptoKeyUsageSign,
2124                       &key));
2125
2126   // Failing case: Bad DER encoding.
2127   EXPECT_EQ(
2128       Status::DataError(),
2129       ImportKey(blink::WebCryptoKeyFormatPkcs8,
2130                 CryptoData(HexStringToBytes("618333c4cb")),
2131                 CreateAlgorithm(blink::WebCryptoAlgorithmIdRsaSsaPkcs1v1_5),
2132                 true,
2133                 blink::WebCryptoKeyUsageSign,
2134                 &key));
2135
2136   // Failing case: Import RSA key but provide an inconsistent input algorithm
2137   // and usage. Several issues here:
2138   //   * AES-CBC doesn't support PKCS8 key format
2139   //   * AES-CBC doesn't support "sign" usage
2140   EXPECT_EQ(Status::ErrorCreateKeyBadUsages(),
2141             ImportKey(blink::WebCryptoKeyFormatPkcs8,
2142                       CryptoData(HexStringToBytes(kPrivateKeyPkcs8DerHex)),
2143                       CreateAlgorithm(blink::WebCryptoAlgorithmIdAesCbc),
2144                       true,
2145                       blink::WebCryptoKeyUsageSign,
2146                       &key));
2147 }
2148
2149 // Tests JWK import and export by doing a roundtrip key conversion and ensuring
2150 // it was lossless:
2151 //
2152 //   PKCS8 --> JWK --> PKCS8
2153 TEST_F(SharedCryptoTest, MAYBE(ImportRsaPrivateKeyJwkToPkcs8RoundTrip)) {
2154   if (!SupportsRsaKeyImport())
2155     return;
2156
2157   blink::WebCryptoKey key = blink::WebCryptoKey::createNull();
2158   ASSERT_EQ(Status::Success(),
2159             ImportKey(blink::WebCryptoKeyFormatPkcs8,
2160                       CryptoData(HexStringToBytes(kPrivateKeyPkcs8DerHex)),
2161                       CreateRsaHashedImportAlgorithm(
2162                           blink::WebCryptoAlgorithmIdRsaSsaPkcs1v1_5,
2163                           blink::WebCryptoAlgorithmIdSha1),
2164                       true,
2165                       blink::WebCryptoKeyUsageSign,
2166                       &key));
2167
2168   std::vector<uint8> exported_key_jwk;
2169   ASSERT_EQ(Status::Success(),
2170             ExportKey(blink::WebCryptoKeyFormatJwk, key, &exported_key_jwk));
2171
2172   // All of the optional parameters (p, q, dp, dq, qi) should be present in the
2173   // output.
2174   const char* expected_jwk =
2175       "{\"alg\":\"RS1\",\"d\":\"M6UEKpCyfU9UUcqbu9C0R3GhAa-IQ0Cu-YhfKku-"
2176       "kuiUpySsPFaMj5eFOtB8AmbIxqPKCSnx6PESMYhEKfxNmuVf7olqEM5wfD7X5zTkRyejlXRQ"
2177       "GlMmgxCcKrrKuig8MbS9L1PD7jfjUs7jT55QO9gMBiKtecbc7og1R8ajsyU\",\"dp\":"
2178       "\"KPoTk4ZVvh-"
2179       "KFZy6ylpy6hkMMAieGc0nSlVvNsT24Z9VSzTAd3kEJ7vdjdPt4kSDKPOF2Bsw6OQ7L_-"
2180       "gJ4YZeQ\",\"dq\":\"Gos485j6cSBJiY1_t57gp3ZoeRKZzfoJ78DlB6yyHtdDAe9b_Ui-"
2181       "RV6utuFnglWCdYCo5OjhQVHRUQqCo_LnKQ\",\"e\":\"AQAB\",\"ext\":true,\"key_"
2182       "ops\":[\"sign\"],\"kty\":\"RSA\",\"n\":"
2183       "\"pW5KDnAQF1iaUYfcfqhB0Vby7A42rVKkTf6x5h962ZHYxRBW_-2xYrTA8oOhKoijlN_"
2184       "1JqtykcuzB86r_OCx39XNlQgJbVsri2311nHvY3fAkhyyPCcKcOJZjm_4nRnxBazC0_"
2185       "DLNfKSgOE4a29kxO8i4eHyDQzoz_siSb2aITc\",\"p\":\"5-"
2186       "iUJyCod1Fyc6NWBT6iobwMlKpy1VxuhilrLfyWeUjApyy8zKfqyzVwbgmh31WhU1vZs8w0Fg"
2187       "s7bc0-2o5kQw\",\"q\":\"tp3KHPfU1-yB51uQ_MqHSrzeEj_"
2188       "ScAGAqpBHm25I3o1n7ST58Z2FuidYdPVCzSDccj5pYzZKH5QlRSsmmmeZ_Q\",\"qi\":"
2189       "\"JxVqukEm0kqB86Uoy_sn9WiG-"
2190       "ECp9uhuF6RLlP6TGVhLjiL93h5aLjvYqluo2FhBlOshkKz4MrhH8To9JKefTQ\"}";
2191
2192   ASSERT_EQ(CryptoData(std::string(expected_jwk)),
2193             CryptoData(exported_key_jwk));
2194
2195   ASSERT_EQ(Status::Success(),
2196             ImportKey(blink::WebCryptoKeyFormatJwk,
2197                       CryptoData(exported_key_jwk),
2198                       CreateRsaHashedImportAlgorithm(
2199                           blink::WebCryptoAlgorithmIdRsaSsaPkcs1v1_5,
2200                           blink::WebCryptoAlgorithmIdSha1),
2201                       true,
2202                       blink::WebCryptoKeyUsageSign,
2203                       &key));
2204
2205   std::vector<uint8> exported_key_pkcs8;
2206   ASSERT_EQ(
2207       Status::Success(),
2208       ExportKey(blink::WebCryptoKeyFormatPkcs8, key, &exported_key_pkcs8));
2209
2210   ASSERT_EQ(CryptoData(HexStringToBytes(kPrivateKeyPkcs8DerHex)),
2211             CryptoData(exported_key_pkcs8));
2212 }
2213
2214 // Tests importing multiple RSA private keys from JWK, and then exporting to
2215 // PKCS8.
2216 //
2217 // This is a regression test for http://crbug.com/378315, for which importing
2218 // a sequence of keys from JWK could yield the wrong key. The first key would
2219 // be imported correctly, however every key after that would actually import
2220 // the first key.
2221 TEST_F(SharedCryptoTest, MAYBE(ImportMultipleRSAPrivateKeysJwk)) {
2222   if (!SupportsRsaKeyImport())
2223     return;
2224
2225   scoped_ptr<base::ListValue> key_list;
2226   ASSERT_TRUE(ReadJsonTestFileToList("rsa_private_keys.json", &key_list));
2227
2228   // For this test to be meaningful the keys MUST be kept alive before importing
2229   // new keys.
2230   std::vector<blink::WebCryptoKey> live_keys;
2231
2232   for (size_t key_index = 0; key_index < key_list->GetSize(); ++key_index) {
2233     SCOPED_TRACE(key_index);
2234
2235     base::DictionaryValue* key_values;
2236     ASSERT_TRUE(key_list->GetDictionary(key_index, &key_values));
2237
2238     // Get the JWK representation of the key.
2239     base::DictionaryValue* key_jwk;
2240     ASSERT_TRUE(key_values->GetDictionary("jwk", &key_jwk));
2241
2242     // Get the PKCS8 representation of the key.
2243     std::string pkcs8_hex_string;
2244     ASSERT_TRUE(key_values->GetString("pkcs8", &pkcs8_hex_string));
2245     std::vector<uint8> pkcs8_bytes = HexStringToBytes(pkcs8_hex_string);
2246
2247     // Get the modulus length for the key.
2248     int modulus_length_bits = 0;
2249     ASSERT_TRUE(key_values->GetInteger("modulusLength", &modulus_length_bits));
2250
2251     blink::WebCryptoKey private_key = blink::WebCryptoKey::createNull();
2252
2253     // Import the key from JWK.
2254     ASSERT_EQ(
2255         Status::Success(),
2256         ImportKeyJwkFromDict(*key_jwk,
2257                              CreateRsaHashedImportAlgorithm(
2258                                  blink::WebCryptoAlgorithmIdRsaSsaPkcs1v1_5,
2259                                  blink::WebCryptoAlgorithmIdSha256),
2260                              true,
2261                              blink::WebCryptoKeyUsageSign,
2262                              &private_key));
2263
2264     live_keys.push_back(private_key);
2265
2266     EXPECT_EQ(
2267         modulus_length_bits,
2268         static_cast<int>(
2269             private_key.algorithm().rsaHashedParams()->modulusLengthBits()));
2270
2271     // Export to PKCS8 and verify that it matches expectation.
2272     std::vector<uint8> exported_key_pkcs8;
2273     ASSERT_EQ(
2274         Status::Success(),
2275         ExportKey(
2276             blink::WebCryptoKeyFormatPkcs8, private_key, &exported_key_pkcs8));
2277
2278     EXPECT_BYTES_EQ(pkcs8_bytes, exported_key_pkcs8);
2279   }
2280 }
2281
2282 // Import an RSA private key using JWK. Next import a JWK containing the same
2283 // modulus, but mismatched parameters for the rest. It should NOT be possible
2284 // that the second import retrieves the first key. See http://crbug.com/378315
2285 // for how that could happen.
2286 TEST_F(SharedCryptoTest, MAYBE(ImportJwkExistingModulusAndInvalid)) {
2287 #if defined(USE_NSS)
2288   if (!NSS_VersionCheck("3.16.2")) {
2289     LOG(WARNING) << "Skipping test because lacks NSS support";
2290     return;
2291   }
2292 #endif
2293
2294   scoped_ptr<base::ListValue> key_list;
2295   ASSERT_TRUE(ReadJsonTestFileToList("rsa_private_keys.json", &key_list));
2296
2297   // Import a 1024-bit private key.
2298   base::DictionaryValue* key1_props;
2299   ASSERT_TRUE(key_list->GetDictionary(1, &key1_props));
2300   base::DictionaryValue* key1_jwk;
2301   ASSERT_TRUE(key1_props->GetDictionary("jwk", &key1_jwk));
2302
2303   blink::WebCryptoKey key1 = blink::WebCryptoKey::createNull();
2304   ASSERT_EQ(Status::Success(),
2305             ImportKeyJwkFromDict(*key1_jwk,
2306                                  CreateRsaHashedImportAlgorithm(
2307                                      blink::WebCryptoAlgorithmIdRsaSsaPkcs1v1_5,
2308                                      blink::WebCryptoAlgorithmIdSha256),
2309                                  true,
2310                                  blink::WebCryptoKeyUsageSign,
2311                                  &key1));
2312
2313   ASSERT_EQ(1024u, key1.algorithm().rsaHashedParams()->modulusLengthBits());
2314
2315   // Construct a JWK using the modulus of key1, but all the other fields from
2316   // another key (also a 1024-bit private key).
2317   base::DictionaryValue* key2_props;
2318   ASSERT_TRUE(key_list->GetDictionary(5, &key2_props));
2319   base::DictionaryValue* key2_jwk;
2320   ASSERT_TRUE(key2_props->GetDictionary("jwk", &key2_jwk));
2321   std::string modulus;
2322   key1_jwk->GetString("n", &modulus);
2323   key2_jwk->SetString("n", modulus);
2324
2325   // This should fail, as the n,e,d parameters are not consistent. It MUST NOT
2326   // somehow return the key created earlier.
2327   blink::WebCryptoKey key2 = blink::WebCryptoKey::createNull();
2328   ASSERT_EQ(Status::OperationError(),
2329             ImportKeyJwkFromDict(*key2_jwk,
2330                                  CreateRsaHashedImportAlgorithm(
2331                                      blink::WebCryptoAlgorithmIdRsaSsaPkcs1v1_5,
2332                                      blink::WebCryptoAlgorithmIdSha256),
2333                                  true,
2334                                  blink::WebCryptoKeyUsageSign,
2335                                  &key2));
2336 }
2337
2338 // Import a JWK RSA private key with some optional parameters missing (q, dp,
2339 // dq, qi).
2340 //
2341 // The only optional parameter included is "p".
2342 //
2343 // This fails because JWA says that producers must include either ALL optional
2344 // parameters or NONE.
2345 TEST_F(SharedCryptoTest, MAYBE(ImportRsaPrivateKeyJwkMissingOptionalParams)) {
2346   blink::WebCryptoKey key = blink::WebCryptoKey::createNull();
2347
2348   base::DictionaryValue dict;
2349   dict.SetString("kty", "RSA");
2350   dict.SetString("alg", "RS1");
2351
2352   dict.SetString(
2353       "n",
2354       "pW5KDnAQF1iaUYfcfqhB0Vby7A42rVKkTf6x5h962ZHYxRBW_-2xYrTA8oOhKoijlN_"
2355       "1JqtykcuzB86r_OCx39XNlQgJbVsri2311nHvY3fAkhyyPCcKcOJZjm_4nRnxBazC0_"
2356       "DLNfKSgOE4a29kxO8i4eHyDQzoz_siSb2aITc");
2357   dict.SetString("e", "AQAB");
2358   dict.SetString(
2359       "d",
2360       "M6UEKpCyfU9UUcqbu9C0R3GhAa-IQ0Cu-YhfKku-"
2361       "kuiUpySsPFaMj5eFOtB8AmbIxqPKCSnx6PESMYhEKfxNmuVf7olqEM5wfD7X5zTkRyejlXRQ"
2362       "GlMmgxCcKrrKuig8MbS9L1PD7jfjUs7jT55QO9gMBiKtecbc7og1R8ajsyU");
2363
2364   dict.SetString("p",
2365                  "5-"
2366                  "iUJyCod1Fyc6NWBT6iobwMlKpy1VxuhilrLfyWeUjApyy8zKfqyzVwbgmh31W"
2367                  "hU1vZs8w0Fgs7bc0-2o5kQw");
2368
2369   ASSERT_EQ(Status::ErrorJwkIncompleteOptionalRsaPrivateKey(),
2370             ImportKeyJwkFromDict(dict,
2371                                  CreateRsaHashedImportAlgorithm(
2372                                      blink::WebCryptoAlgorithmIdRsaSsaPkcs1v1_5,
2373                                      blink::WebCryptoAlgorithmIdSha1),
2374                                  true,
2375                                  blink::WebCryptoKeyUsageSign,
2376                                  &key));
2377 }
2378
2379 // Import a JWK RSA private key, without any of the optional parameters.
2380 //
2381 // This is expected to work, however based on the current NSS implementation it
2382 // does not.
2383 //
2384 // TODO(eroman): http://crbug/com/374927
2385 TEST_F(SharedCryptoTest, MAYBE(ImportRsaPrivateKeyJwkIncorrectOptionalEmpty)) {
2386   if (!SupportsRsaKeyImport())
2387     return;
2388
2389   blink::WebCryptoKey key = blink::WebCryptoKey::createNull();
2390
2391   base::DictionaryValue dict;
2392   dict.SetString("kty", "RSA");
2393   dict.SetString("alg", "RS1");
2394
2395   dict.SetString(
2396       "n",
2397       "pW5KDnAQF1iaUYfcfqhB0Vby7A42rVKkTf6x5h962ZHYxRBW_-2xYrTA8oOhKoijlN_"
2398       "1JqtykcuzB86r_OCx39XNlQgJbVsri2311nHvY3fAkhyyPCcKcOJZjm_4nRnxBazC0_"
2399       "DLNfKSgOE4a29kxO8i4eHyDQzoz_siSb2aITc");
2400   dict.SetString("e", "AQAB");
2401   dict.SetString(
2402       "d",
2403       "M6UEKpCyfU9UUcqbu9C0R3GhAa-IQ0Cu-YhfKku-"
2404       "kuiUpySsPFaMj5eFOtB8AmbIxqPKCSnx6PESMYhEKfxNmuVf7olqEM5wfD7X5zTkRyejlXRQ"
2405       "GlMmgxCcKrrKuig8MbS9L1PD7jfjUs7jT55QO9gMBiKtecbc7og1R8ajsyU");
2406
2407   // TODO(eroman): This should pass, see: http://crbug/com/374927
2408   //
2409   // Technically it is OK to fail since JWA says that consumer are not required
2410   // to support lack of the optional parameters.
2411   ASSERT_EQ(Status::OperationError(),
2412             ImportKeyJwkFromDict(dict,
2413                                  CreateRsaHashedImportAlgorithm(
2414                                      blink::WebCryptoAlgorithmIdRsaSsaPkcs1v1_5,
2415                                      blink::WebCryptoAlgorithmIdSha1),
2416                                  true,
2417                                  blink::WebCryptoKeyUsageSign,
2418                                  &key));
2419
2420 }
2421
2422 TEST_F(SharedCryptoTest, MAYBE(GenerateKeyPairRsa)) {
2423   // Note: using unrealistic short key lengths here to avoid bogging down tests.
2424
2425   // Successful WebCryptoAlgorithmIdRsaSsaPkcs1v1_5 key generation (sha256)
2426   const unsigned int modulus_length = 256;
2427   const std::vector<uint8> public_exponent = HexStringToBytes("010001");
2428   blink::WebCryptoAlgorithm algorithm =
2429       CreateRsaHashedKeyGenAlgorithm(blink::WebCryptoAlgorithmIdRsaSsaPkcs1v1_5,
2430                                      blink::WebCryptoAlgorithmIdSha256,
2431                                      modulus_length,
2432                                      public_exponent);
2433   bool extractable = true;
2434   const blink::WebCryptoKeyUsageMask usage_mask = 0;
2435   blink::WebCryptoKey public_key = blink::WebCryptoKey::createNull();
2436   blink::WebCryptoKey private_key = blink::WebCryptoKey::createNull();
2437
2438   EXPECT_EQ(Status::Success(),
2439             GenerateKeyPair(
2440                 algorithm, extractable, usage_mask, &public_key, &private_key));
2441   EXPECT_FALSE(public_key.isNull());
2442   EXPECT_FALSE(private_key.isNull());
2443   EXPECT_EQ(blink::WebCryptoKeyTypePublic, public_key.type());
2444   EXPECT_EQ(blink::WebCryptoKeyTypePrivate, private_key.type());
2445   EXPECT_EQ(modulus_length,
2446             public_key.algorithm().rsaHashedParams()->modulusLengthBits());
2447   EXPECT_EQ(modulus_length,
2448             private_key.algorithm().rsaHashedParams()->modulusLengthBits());
2449   EXPECT_EQ(blink::WebCryptoAlgorithmIdSha256,
2450             public_key.algorithm().rsaHashedParams()->hash().id());
2451   EXPECT_EQ(blink::WebCryptoAlgorithmIdSha256,
2452             private_key.algorithm().rsaHashedParams()->hash().id());
2453   EXPECT_TRUE(public_key.extractable());
2454   EXPECT_EQ(extractable, private_key.extractable());
2455   EXPECT_EQ(usage_mask, public_key.usages());
2456   EXPECT_EQ(usage_mask, private_key.usages());
2457
2458   // Try exporting the generated key pair, and then re-importing to verify that
2459   // the exported data was valid.
2460   std::vector<uint8> public_key_spki;
2461   EXPECT_EQ(
2462       Status::Success(),
2463       ExportKey(blink::WebCryptoKeyFormatSpki, public_key, &public_key_spki));
2464
2465   if (SupportsRsaKeyImport()) {
2466     public_key = blink::WebCryptoKey::createNull();
2467     EXPECT_EQ(Status::Success(),
2468               ImportKey(blink::WebCryptoKeyFormatSpki,
2469                         CryptoData(public_key_spki),
2470                         CreateRsaHashedImportAlgorithm(
2471                             blink::WebCryptoAlgorithmIdRsaSsaPkcs1v1_5,
2472                             blink::WebCryptoAlgorithmIdSha256),
2473                         true,
2474                         usage_mask,
2475                         &public_key));
2476     EXPECT_EQ(modulus_length,
2477               public_key.algorithm().rsaHashedParams()->modulusLengthBits());
2478
2479     std::vector<uint8> private_key_pkcs8;
2480     EXPECT_EQ(
2481         Status::Success(),
2482         ExportKey(
2483             blink::WebCryptoKeyFormatPkcs8, private_key, &private_key_pkcs8));
2484     private_key = blink::WebCryptoKey::createNull();
2485     EXPECT_EQ(Status::Success(),
2486               ImportKey(blink::WebCryptoKeyFormatPkcs8,
2487                         CryptoData(private_key_pkcs8),
2488                         CreateRsaHashedImportAlgorithm(
2489                             blink::WebCryptoAlgorithmIdRsaSsaPkcs1v1_5,
2490                             blink::WebCryptoAlgorithmIdSha256),
2491                         true,
2492                         usage_mask,
2493                         &private_key));
2494     EXPECT_EQ(modulus_length,
2495               private_key.algorithm().rsaHashedParams()->modulusLengthBits());
2496   }
2497
2498   // Fail with bad modulus.
2499   algorithm =
2500       CreateRsaHashedKeyGenAlgorithm(blink::WebCryptoAlgorithmIdRsaSsaPkcs1v1_5,
2501                                      blink::WebCryptoAlgorithmIdSha256,
2502                                      0,
2503                                      public_exponent);
2504   EXPECT_EQ(Status::ErrorGenerateRsaZeroModulus(),
2505             GenerateKeyPair(
2506                 algorithm, extractable, usage_mask, &public_key, &private_key));
2507
2508   // Fail with bad exponent: larger than unsigned long.
2509   unsigned int exponent_length = sizeof(unsigned long) + 1;  // NOLINT
2510   const std::vector<uint8> long_exponent(exponent_length, 0x01);
2511   algorithm =
2512       CreateRsaHashedKeyGenAlgorithm(blink::WebCryptoAlgorithmIdRsaSsaPkcs1v1_5,
2513                                      blink::WebCryptoAlgorithmIdSha256,
2514                                      modulus_length,
2515                                      long_exponent);
2516   EXPECT_EQ(Status::ErrorGenerateKeyPublicExponent(),
2517             GenerateKeyPair(
2518                 algorithm, extractable, usage_mask, &public_key, &private_key));
2519
2520   // Fail with bad exponent: empty.
2521   const std::vector<uint8> empty_exponent;
2522   algorithm =
2523       CreateRsaHashedKeyGenAlgorithm(blink::WebCryptoAlgorithmIdRsaSsaPkcs1v1_5,
2524                                      blink::WebCryptoAlgorithmIdSha256,
2525                                      modulus_length,
2526                                      empty_exponent);
2527   EXPECT_EQ(Status::ErrorGenerateKeyPublicExponent(),
2528             GenerateKeyPair(
2529                 algorithm, extractable, usage_mask, &public_key, &private_key));
2530
2531   // Fail with bad exponent: all zeros.
2532   std::vector<uint8> exponent_with_leading_zeros(15, 0x00);
2533   algorithm =
2534       CreateRsaHashedKeyGenAlgorithm(blink::WebCryptoAlgorithmIdRsaSsaPkcs1v1_5,
2535                                      blink::WebCryptoAlgorithmIdSha256,
2536                                      modulus_length,
2537                                      exponent_with_leading_zeros);
2538   EXPECT_EQ(Status::ErrorGenerateKeyPublicExponent(),
2539             GenerateKeyPair(
2540                 algorithm, extractable, usage_mask, &public_key, &private_key));
2541
2542   // Key generation success using exponent with leading zeros.
2543   exponent_with_leading_zeros.insert(exponent_with_leading_zeros.end(),
2544                                      public_exponent.begin(),
2545                                      public_exponent.end());
2546   algorithm =
2547       CreateRsaHashedKeyGenAlgorithm(blink::WebCryptoAlgorithmIdRsaSsaPkcs1v1_5,
2548                                      blink::WebCryptoAlgorithmIdSha256,
2549                                      modulus_length,
2550                                      exponent_with_leading_zeros);
2551   EXPECT_EQ(Status::Success(),
2552             GenerateKeyPair(
2553                 algorithm, extractable, usage_mask, &public_key, &private_key));
2554   EXPECT_FALSE(public_key.isNull());
2555   EXPECT_FALSE(private_key.isNull());
2556   EXPECT_EQ(blink::WebCryptoKeyTypePublic, public_key.type());
2557   EXPECT_EQ(blink::WebCryptoKeyTypePrivate, private_key.type());
2558   EXPECT_TRUE(public_key.extractable());
2559   EXPECT_EQ(extractable, private_key.extractable());
2560   EXPECT_EQ(usage_mask, public_key.usages());
2561   EXPECT_EQ(usage_mask, private_key.usages());
2562
2563   // Successful WebCryptoAlgorithmIdRsaSsaPkcs1v1_5 key generation (sha1)
2564   algorithm =
2565       CreateRsaHashedKeyGenAlgorithm(blink::WebCryptoAlgorithmIdRsaSsaPkcs1v1_5,
2566                                      blink::WebCryptoAlgorithmIdSha1,
2567                                      modulus_length,
2568                                      public_exponent);
2569   EXPECT_EQ(
2570       Status::Success(),
2571       GenerateKeyPair(algorithm, false, usage_mask, &public_key, &private_key));
2572   EXPECT_FALSE(public_key.isNull());
2573   EXPECT_FALSE(private_key.isNull());
2574   EXPECT_EQ(blink::WebCryptoKeyTypePublic, public_key.type());
2575   EXPECT_EQ(blink::WebCryptoKeyTypePrivate, private_key.type());
2576   EXPECT_EQ(modulus_length,
2577             public_key.algorithm().rsaHashedParams()->modulusLengthBits());
2578   EXPECT_EQ(modulus_length,
2579             private_key.algorithm().rsaHashedParams()->modulusLengthBits());
2580   EXPECT_EQ(blink::WebCryptoAlgorithmIdSha1,
2581             public_key.algorithm().rsaHashedParams()->hash().id());
2582   EXPECT_EQ(blink::WebCryptoAlgorithmIdSha1,
2583             private_key.algorithm().rsaHashedParams()->hash().id());
2584   // Even though "extractable" was set to false, the public key remains
2585   // extractable.
2586   EXPECT_TRUE(public_key.extractable());
2587   EXPECT_FALSE(private_key.extractable());
2588   EXPECT_EQ(usage_mask, public_key.usages());
2589   EXPECT_EQ(usage_mask, private_key.usages());
2590
2591   // Exporting a private key as SPKI format doesn't make sense. However this
2592   // will first fail because the key is not extractable.
2593   std::vector<uint8> output;
2594   EXPECT_EQ(Status::ErrorKeyNotExtractable(),
2595             ExportKey(blink::WebCryptoKeyFormatSpki, private_key, &output));
2596
2597   // Re-generate an extractable private_key and try to export it as SPKI format.
2598   // This should fail since spki is for public keys.
2599   EXPECT_EQ(
2600       Status::Success(),
2601       GenerateKeyPair(algorithm, true, usage_mask, &public_key, &private_key));
2602   EXPECT_EQ(Status::ErrorUnexpectedKeyType(),
2603             ExportKey(blink::WebCryptoKeyFormatSpki, private_key, &output));
2604 }
2605
2606 // Try generating RSA key pairs using unsupported public exponents. Only
2607 // exponents of 3 and 65537 are supported. While both OpenSSL and NSS can
2608 // support other values, OpenSSL hangs when given invalid exponents, so use a
2609 // whitelist to validate the parameters.
2610 TEST_F(SharedCryptoTest, MAYBE(GenerateKeyPairRsaBadExponent)) {
2611   const unsigned int modulus_length = 1024;
2612
2613   const char* const kPublicExponents[] = {
2614       "11",  // 17 - This is a valid public exponent, but currently disallowed.
2615       "00",
2616       "01",
2617       "02",
2618       "010000",  // 65536
2619   };
2620
2621   for (size_t i = 0; i < arraysize(kPublicExponents); ++i) {
2622     SCOPED_TRACE(i);
2623     blink::WebCryptoAlgorithm algorithm = CreateRsaHashedKeyGenAlgorithm(
2624         blink::WebCryptoAlgorithmIdRsaSsaPkcs1v1_5,
2625         blink::WebCryptoAlgorithmIdSha256,
2626         modulus_length,
2627         HexStringToBytes(kPublicExponents[i]));
2628
2629     blink::WebCryptoKey public_key = blink::WebCryptoKey::createNull();
2630     blink::WebCryptoKey private_key = blink::WebCryptoKey::createNull();
2631
2632     EXPECT_EQ(Status::ErrorGenerateKeyPublicExponent(),
2633               GenerateKeyPair(
2634                   algorithm, true, 0, &public_key, &private_key));
2635   }
2636 }
2637
2638 TEST_F(SharedCryptoTest, MAYBE(RsaSsaSignVerifyFailures)) {
2639   if (!SupportsRsaKeyImport())
2640     return;
2641
2642   // Import a key pair.
2643   blink::WebCryptoAlgorithm import_algorithm =
2644       CreateRsaHashedImportAlgorithm(blink::WebCryptoAlgorithmIdRsaSsaPkcs1v1_5,
2645                                      blink::WebCryptoAlgorithmIdSha1);
2646   blink::WebCryptoKey public_key = blink::WebCryptoKey::createNull();
2647   blink::WebCryptoKey private_key = blink::WebCryptoKey::createNull();
2648   ASSERT_NO_FATAL_FAILURE(
2649       ImportRsaKeyPair(HexStringToBytes(kPublicKeySpkiDerHex),
2650                        HexStringToBytes(kPrivateKeyPkcs8DerHex),
2651                        import_algorithm,
2652                        false,
2653                        blink::WebCryptoKeyUsageVerify,
2654                        blink::WebCryptoKeyUsageSign,
2655                        &public_key,
2656                        &private_key));
2657
2658   blink::WebCryptoAlgorithm algorithm =
2659       CreateAlgorithm(blink::WebCryptoAlgorithmIdRsaSsaPkcs1v1_5);
2660
2661   std::vector<uint8> signature;
2662   bool signature_match;
2663
2664   // Compute a signature.
2665   const std::vector<uint8> data = HexStringToBytes("010203040506070809");
2666   ASSERT_EQ(Status::Success(),
2667             Sign(algorithm, private_key, CryptoData(data), &signature));
2668
2669   // Ensure truncated signature does not verify by passing one less byte.
2670   EXPECT_EQ(Status::Success(),
2671             VerifySignature(
2672                 algorithm,
2673                 public_key,
2674                 CryptoData(Uint8VectorStart(signature), signature.size() - 1),
2675                 CryptoData(data),
2676                 &signature_match));
2677   EXPECT_FALSE(signature_match);
2678
2679   // Ensure truncated signature does not verify by passing no bytes.
2680   EXPECT_EQ(Status::Success(),
2681             VerifySignature(algorithm,
2682                             public_key,
2683                             CryptoData(),
2684                             CryptoData(data),
2685                             &signature_match));
2686   EXPECT_FALSE(signature_match);
2687
2688   // Ensure corrupted signature does not verify.
2689   std::vector<uint8> corrupt_sig = signature;
2690   corrupt_sig[corrupt_sig.size() / 2] ^= 0x1;
2691   EXPECT_EQ(Status::Success(),
2692             VerifySignature(algorithm,
2693                             public_key,
2694                             CryptoData(corrupt_sig),
2695                             CryptoData(data),
2696                             &signature_match));
2697   EXPECT_FALSE(signature_match);
2698
2699   // Ensure signatures that are greater than the modulus size fail.
2700   const unsigned int long_message_size_bytes = 1024;
2701   DCHECK_GT(long_message_size_bytes, kModulusLengthBits / 8);
2702   const unsigned char kLongSignature[long_message_size_bytes] = {0};
2703   EXPECT_EQ(Status::Success(),
2704             VerifySignature(algorithm,
2705                             public_key,
2706                             CryptoData(kLongSignature, sizeof(kLongSignature)),
2707                             CryptoData(data),
2708                             &signature_match));
2709   EXPECT_FALSE(signature_match);
2710
2711   // Ensure that signing and verifying with an incompatible algorithm fails.
2712   algorithm = CreateAlgorithm(blink::WebCryptoAlgorithmIdRsaOaep);
2713
2714   EXPECT_EQ(Status::ErrorUnexpected(),
2715             Sign(algorithm, private_key, CryptoData(data), &signature));
2716   EXPECT_EQ(Status::ErrorUnexpected(),
2717             VerifySignature(algorithm,
2718                             public_key,
2719                             CryptoData(signature),
2720                             CryptoData(data),
2721                             &signature_match));
2722
2723   // Some crypto libraries (NSS) can automatically select the RSA SSA inner hash
2724   // based solely on the contents of the input signature data. In the Web Crypto
2725   // implementation, the inner hash should be specified uniquely by the key
2726   // algorithm parameter. To validate this behavior, call Verify with a computed
2727   // signature that used one hash type (SHA-1), but pass in a key with a
2728   // different inner hash type (SHA-256). If the hash type is determined by the
2729   // signature itself (undesired), the verify will pass, while if the hash type
2730   // is specified by the key algorithm (desired), the verify will fail.
2731
2732   // Compute a signature using SHA-1 as the inner hash.
2733   EXPECT_EQ(Status::Success(),
2734             Sign(CreateAlgorithm(blink::WebCryptoAlgorithmIdRsaSsaPkcs1v1_5),
2735                  private_key,
2736                  CryptoData(data),
2737                  &signature));
2738
2739   blink::WebCryptoKey public_key_256 = blink::WebCryptoKey::createNull();
2740   EXPECT_EQ(Status::Success(),
2741             ImportKey(blink::WebCryptoKeyFormatSpki,
2742                       CryptoData(HexStringToBytes(kPublicKeySpkiDerHex)),
2743                       CreateRsaHashedImportAlgorithm(
2744                           blink::WebCryptoAlgorithmIdRsaSsaPkcs1v1_5,
2745                           blink::WebCryptoAlgorithmIdSha256),
2746                       true,
2747                       blink::WebCryptoKeyUsageVerify,
2748                       &public_key_256));
2749
2750   // Now verify using an algorithm whose inner hash is SHA-256, not SHA-1. The
2751   // signature should not verify.
2752   // NOTE: public_key was produced by generateKey, and so its associated
2753   // algorithm has WebCryptoRsaKeyGenParams and not WebCryptoRsaSsaParams. Thus
2754   // it has no inner hash to conflict with the input algorithm.
2755   EXPECT_EQ(blink::WebCryptoAlgorithmIdSha1,
2756             private_key.algorithm().rsaHashedParams()->hash().id());
2757   EXPECT_EQ(blink::WebCryptoAlgorithmIdSha256,
2758             public_key_256.algorithm().rsaHashedParams()->hash().id());
2759
2760   bool is_match;
2761   EXPECT_EQ(Status::Success(),
2762             VerifySignature(
2763                 CreateAlgorithm(blink::WebCryptoAlgorithmIdRsaSsaPkcs1v1_5),
2764                 public_key_256,
2765                 CryptoData(signature),
2766                 CryptoData(data),
2767                 &is_match));
2768   EXPECT_FALSE(is_match);
2769 }
2770
2771 TEST_F(SharedCryptoTest, MAYBE(RsaSignVerifyKnownAnswer)) {
2772   if (!SupportsRsaKeyImport())
2773     return;
2774
2775   scoped_ptr<base::ListValue> tests;
2776   ASSERT_TRUE(ReadJsonTestFileToList("pkcs1v15_sign.json", &tests));
2777
2778   // Import the key pair.
2779   blink::WebCryptoAlgorithm import_algorithm =
2780       CreateRsaHashedImportAlgorithm(blink::WebCryptoAlgorithmIdRsaSsaPkcs1v1_5,
2781                                      blink::WebCryptoAlgorithmIdSha1);
2782   blink::WebCryptoKey public_key = blink::WebCryptoKey::createNull();
2783   blink::WebCryptoKey private_key = blink::WebCryptoKey::createNull();
2784   ASSERT_NO_FATAL_FAILURE(
2785       ImportRsaKeyPair(HexStringToBytes(kPublicKeySpkiDerHex),
2786                        HexStringToBytes(kPrivateKeyPkcs8DerHex),
2787                        import_algorithm,
2788                        false,
2789                        blink::WebCryptoKeyUsageVerify,
2790                        blink::WebCryptoKeyUsageSign,
2791                        &public_key,
2792                        &private_key));
2793
2794   blink::WebCryptoAlgorithm algorithm =
2795       CreateAlgorithm(blink::WebCryptoAlgorithmIdRsaSsaPkcs1v1_5);
2796
2797   // Validate the signatures are computed and verified as expected.
2798   std::vector<uint8> signature;
2799   for (size_t test_index = 0; test_index < tests->GetSize(); ++test_index) {
2800     SCOPED_TRACE(test_index);
2801
2802     base::DictionaryValue* test;
2803     ASSERT_TRUE(tests->GetDictionary(test_index, &test));
2804
2805     std::vector<uint8> test_message =
2806         GetBytesFromHexString(test, "message_hex");
2807     std::vector<uint8> test_signature =
2808         GetBytesFromHexString(test, "signature_hex");
2809
2810     signature.clear();
2811     ASSERT_EQ(
2812         Status::Success(),
2813         Sign(algorithm, private_key, CryptoData(test_message), &signature));
2814     EXPECT_BYTES_EQ(test_signature, signature);
2815
2816     bool is_match = false;
2817     ASSERT_EQ(Status::Success(),
2818               VerifySignature(algorithm,
2819                               public_key,
2820                               CryptoData(test_signature),
2821                               CryptoData(test_message),
2822                               &is_match));
2823     EXPECT_TRUE(is_match);
2824   }
2825 }
2826
2827 TEST_F(SharedCryptoTest, MAYBE(AesKwKeyImport)) {
2828   blink::WebCryptoKey key = blink::WebCryptoKey::createNull();
2829   blink::WebCryptoAlgorithm algorithm =
2830       CreateAlgorithm(blink::WebCryptoAlgorithmIdAesKw);
2831
2832   // Import a 128-bit Key Encryption Key (KEK)
2833   std::string key_raw_hex_in = "025a8cf3f08b4f6c5f33bbc76a471939";
2834   ASSERT_EQ(Status::Success(),
2835             ImportKey(blink::WebCryptoKeyFormatRaw,
2836                       CryptoData(HexStringToBytes(key_raw_hex_in)),
2837                       algorithm,
2838                       true,
2839                       blink::WebCryptoKeyUsageWrapKey,
2840                       &key));
2841   std::vector<uint8> key_raw_out;
2842   EXPECT_EQ(Status::Success(),
2843             ExportKey(blink::WebCryptoKeyFormatRaw, key, &key_raw_out));
2844   EXPECT_BYTES_EQ_HEX(key_raw_hex_in, key_raw_out);
2845
2846   // Import a 192-bit KEK
2847   key_raw_hex_in = "c0192c6466b2370decbb62b2cfef4384544ffeb4d2fbc103";
2848   ASSERT_EQ(Status::ErrorAes192BitUnsupported(),
2849             ImportKey(blink::WebCryptoKeyFormatRaw,
2850                       CryptoData(HexStringToBytes(key_raw_hex_in)),
2851                       algorithm,
2852                       true,
2853                       blink::WebCryptoKeyUsageWrapKey,
2854                       &key));
2855
2856   // Import a 256-bit Key Encryption Key (KEK)
2857   key_raw_hex_in =
2858       "e11fe66380d90fa9ebefb74e0478e78f95664d0c67ca20ce4a0b5842863ac46f";
2859   ASSERT_EQ(Status::Success(),
2860             ImportKey(blink::WebCryptoKeyFormatRaw,
2861                       CryptoData(HexStringToBytes(key_raw_hex_in)),
2862                       algorithm,
2863                       true,
2864                       blink::WebCryptoKeyUsageWrapKey,
2865                       &key));
2866   EXPECT_EQ(Status::Success(),
2867             ExportKey(blink::WebCryptoKeyFormatRaw, key, &key_raw_out));
2868   EXPECT_BYTES_EQ_HEX(key_raw_hex_in, key_raw_out);
2869
2870   // Fail import of 0 length key
2871   EXPECT_EQ(Status::ErrorImportAesKeyLength(),
2872             ImportKey(blink::WebCryptoKeyFormatRaw,
2873                       CryptoData(HexStringToBytes("")),
2874                       algorithm,
2875                       true,
2876                       blink::WebCryptoKeyUsageWrapKey,
2877                       &key));
2878
2879   // Fail import of 124-bit KEK
2880   key_raw_hex_in = "3e4566a2bdaa10cb68134fa66c15ddb";
2881   EXPECT_EQ(Status::ErrorImportAesKeyLength(),
2882             ImportKey(blink::WebCryptoKeyFormatRaw,
2883                       CryptoData(HexStringToBytes(key_raw_hex_in)),
2884                       algorithm,
2885                       true,
2886                       blink::WebCryptoKeyUsageWrapKey,
2887                       &key));
2888
2889   // Fail import of 200-bit KEK
2890   key_raw_hex_in = "0a1d88608a5ad9fec64f1ada269ebab4baa2feeb8d95638c0e";
2891   EXPECT_EQ(Status::ErrorImportAesKeyLength(),
2892             ImportKey(blink::WebCryptoKeyFormatRaw,
2893                       CryptoData(HexStringToBytes(key_raw_hex_in)),
2894                       algorithm,
2895                       true,
2896                       blink::WebCryptoKeyUsageWrapKey,
2897                       &key));
2898
2899   // Fail import of 260-bit KEK
2900   key_raw_hex_in =
2901       "72d4e475ff34215416c9ad9c8281247a4d730c5f275ac23f376e73e3bce8d7d5a";
2902   EXPECT_EQ(Status::ErrorImportAesKeyLength(),
2903             ImportKey(blink::WebCryptoKeyFormatRaw,
2904                       CryptoData(HexStringToBytes(key_raw_hex_in)),
2905                       algorithm,
2906                       true,
2907                       blink::WebCryptoKeyUsageWrapKey,
2908                       &key));
2909 }
2910
2911 TEST_F(SharedCryptoTest, MAYBE(UnwrapFailures)) {
2912   // This test exercises the code path common to all unwrap operations.
2913   scoped_ptr<base::ListValue> tests;
2914   ASSERT_TRUE(ReadJsonTestFileToList("aes_kw.json", &tests));
2915   base::DictionaryValue* test;
2916   ASSERT_TRUE(tests->GetDictionary(0, &test));
2917   const std::vector<uint8> test_kek = GetBytesFromHexString(test, "kek");
2918   const std::vector<uint8> test_ciphertext =
2919       GetBytesFromHexString(test, "ciphertext");
2920
2921   blink::WebCryptoKey unwrapped_key = blink::WebCryptoKey::createNull();
2922
2923   // Using a wrapping algorithm that does not match the wrapping key algorithm
2924   // should fail.
2925   blink::WebCryptoKey wrapping_key = ImportSecretKeyFromRaw(
2926       test_kek,
2927       webcrypto::CreateAlgorithm(blink::WebCryptoAlgorithmIdAesKw),
2928       blink::WebCryptoKeyUsageUnwrapKey);
2929   EXPECT_EQ(
2930       Status::ErrorUnexpected(),
2931       UnwrapKey(blink::WebCryptoKeyFormatRaw,
2932                 CryptoData(test_ciphertext),
2933                 wrapping_key,
2934                 webcrypto::CreateAlgorithm(blink::WebCryptoAlgorithmIdAesCbc),
2935                 webcrypto::CreateAlgorithm(blink::WebCryptoAlgorithmIdAesCbc),
2936                 true,
2937                 blink::WebCryptoKeyUsageEncrypt,
2938                 &unwrapped_key));
2939 }
2940
2941 TEST_F(SharedCryptoTest, MAYBE(AesKwRawSymkeyWrapUnwrapKnownAnswer)) {
2942   scoped_ptr<base::ListValue> tests;
2943   ASSERT_TRUE(ReadJsonTestFileToList("aes_kw.json", &tests));
2944
2945   for (size_t test_index = 0; test_index < tests->GetSize(); ++test_index) {
2946     SCOPED_TRACE(test_index);
2947     base::DictionaryValue* test;
2948     ASSERT_TRUE(tests->GetDictionary(test_index, &test));
2949     const std::vector<uint8> test_kek = GetBytesFromHexString(test, "kek");
2950     const std::vector<uint8> test_key = GetBytesFromHexString(test, "key");
2951     const std::vector<uint8> test_ciphertext =
2952         GetBytesFromHexString(test, "ciphertext");
2953     const blink::WebCryptoAlgorithm wrapping_algorithm =
2954         webcrypto::CreateAlgorithm(blink::WebCryptoAlgorithmIdAesKw);
2955
2956     // Import the wrapping key.
2957     blink::WebCryptoKey wrapping_key = ImportSecretKeyFromRaw(
2958         test_kek,
2959         wrapping_algorithm,
2960         blink::WebCryptoKeyUsageWrapKey | blink::WebCryptoKeyUsageUnwrapKey);
2961
2962     // Import the key to be wrapped.
2963     blink::WebCryptoKey key = ImportSecretKeyFromRaw(
2964         test_key,
2965         CreateHmacImportAlgorithm(blink::WebCryptoAlgorithmIdSha1),
2966         blink::WebCryptoKeyUsageSign);
2967
2968     // Wrap the key and verify the ciphertext result against the known answer.
2969     std::vector<uint8> wrapped_key;
2970     ASSERT_EQ(Status::Success(),
2971               WrapKey(blink::WebCryptoKeyFormatRaw,
2972                       key,
2973                       wrapping_key,
2974                       wrapping_algorithm,
2975                       &wrapped_key));
2976     EXPECT_BYTES_EQ(test_ciphertext, wrapped_key);
2977
2978     // Unwrap the known ciphertext to get a new test_key.
2979     blink::WebCryptoKey unwrapped_key = blink::WebCryptoKey::createNull();
2980     ASSERT_EQ(
2981         Status::Success(),
2982         UnwrapKey(blink::WebCryptoKeyFormatRaw,
2983                   CryptoData(test_ciphertext),
2984                   wrapping_key,
2985                   wrapping_algorithm,
2986                   CreateHmacImportAlgorithm(blink::WebCryptoAlgorithmIdSha1),
2987                   true,
2988                   blink::WebCryptoKeyUsageSign,
2989                   &unwrapped_key));
2990     EXPECT_FALSE(key.isNull());
2991     EXPECT_TRUE(key.handle());
2992     EXPECT_EQ(blink::WebCryptoKeyTypeSecret, key.type());
2993     EXPECT_EQ(blink::WebCryptoAlgorithmIdHmac, key.algorithm().id());
2994     EXPECT_EQ(true, key.extractable());
2995     EXPECT_EQ(blink::WebCryptoKeyUsageSign, key.usages());
2996
2997     // Export the new key and compare its raw bytes with the original known key.
2998     std::vector<uint8> raw_key;
2999     EXPECT_EQ(Status::Success(),
3000               ExportKey(blink::WebCryptoKeyFormatRaw, unwrapped_key, &raw_key));
3001     EXPECT_BYTES_EQ(test_key, raw_key);
3002   }
3003 }
3004
3005 // Unwrap a HMAC key using AES-KW, and then try doing a sign/verify with the
3006 // unwrapped key
3007 TEST_F(SharedCryptoTest, MAYBE(AesKwRawSymkeyUnwrapSignVerifyHmac)) {
3008   scoped_ptr<base::ListValue> tests;
3009   ASSERT_TRUE(ReadJsonTestFileToList("aes_kw.json", &tests));
3010
3011   base::DictionaryValue* test;
3012   ASSERT_TRUE(tests->GetDictionary(0, &test));
3013   const std::vector<uint8> test_kek = GetBytesFromHexString(test, "kek");
3014   const std::vector<uint8> test_ciphertext =
3015       GetBytesFromHexString(test, "ciphertext");
3016   const blink::WebCryptoAlgorithm wrapping_algorithm =
3017       CreateAlgorithm(blink::WebCryptoAlgorithmIdAesKw);
3018
3019   // Import the wrapping key.
3020   blink::WebCryptoKey wrapping_key = ImportSecretKeyFromRaw(
3021       test_kek, wrapping_algorithm, blink::WebCryptoKeyUsageUnwrapKey);
3022
3023   // Unwrap the known ciphertext.
3024   blink::WebCryptoKey key = blink::WebCryptoKey::createNull();
3025   ASSERT_EQ(
3026       Status::Success(),
3027       UnwrapKey(blink::WebCryptoKeyFormatRaw,
3028                 CryptoData(test_ciphertext),
3029                 wrapping_key,
3030                 wrapping_algorithm,
3031                 CreateHmacImportAlgorithm(blink::WebCryptoAlgorithmIdSha1),
3032                 false,
3033                 blink::WebCryptoKeyUsageSign | blink::WebCryptoKeyUsageVerify,
3034                 &key));
3035
3036   EXPECT_EQ(blink::WebCryptoKeyTypeSecret, key.type());
3037   EXPECT_EQ(blink::WebCryptoAlgorithmIdHmac, key.algorithm().id());
3038   EXPECT_FALSE(key.extractable());
3039   EXPECT_EQ(blink::WebCryptoKeyUsageSign | blink::WebCryptoKeyUsageVerify,
3040             key.usages());
3041
3042   // Sign an empty message and ensure it is verified.
3043   std::vector<uint8> test_message;
3044   std::vector<uint8> signature;
3045
3046   ASSERT_EQ(Status::Success(),
3047             Sign(CreateAlgorithm(blink::WebCryptoAlgorithmIdHmac),
3048                  key,
3049                  CryptoData(test_message),
3050                  &signature));
3051
3052   EXPECT_GT(signature.size(), 0u);
3053
3054   bool verify_result;
3055   ASSERT_EQ(Status::Success(),
3056             VerifySignature(CreateAlgorithm(blink::WebCryptoAlgorithmIdHmac),
3057                             key,
3058                             CryptoData(signature),
3059                             CryptoData(test_message),
3060                             &verify_result));
3061 }
3062
3063 TEST_F(SharedCryptoTest, MAYBE(AesKwRawSymkeyWrapUnwrapErrors)) {
3064   scoped_ptr<base::ListValue> tests;
3065   ASSERT_TRUE(ReadJsonTestFileToList("aes_kw.json", &tests));
3066   base::DictionaryValue* test;
3067   // Use 256 bits of data with a 256-bit KEK
3068   ASSERT_TRUE(tests->GetDictionary(3, &test));
3069   const std::vector<uint8> test_kek = GetBytesFromHexString(test, "kek");
3070   const std::vector<uint8> test_key = GetBytesFromHexString(test, "key");
3071   const std::vector<uint8> test_ciphertext =
3072       GetBytesFromHexString(test, "ciphertext");
3073   const blink::WebCryptoAlgorithm wrapping_algorithm =
3074       webcrypto::CreateAlgorithm(blink::WebCryptoAlgorithmIdAesKw);
3075   const blink::WebCryptoAlgorithm key_algorithm =
3076       webcrypto::CreateAlgorithm(blink::WebCryptoAlgorithmIdAesCbc);
3077   // Import the wrapping key.
3078   blink::WebCryptoKey wrapping_key = ImportSecretKeyFromRaw(
3079       test_kek,
3080       wrapping_algorithm,
3081       blink::WebCryptoKeyUsageWrapKey | blink::WebCryptoKeyUsageUnwrapKey);
3082   // Import the key to be wrapped.
3083   blink::WebCryptoKey key = ImportSecretKeyFromRaw(
3084       test_key,
3085       webcrypto::CreateAlgorithm(blink::WebCryptoAlgorithmIdAesCbc),
3086       blink::WebCryptoKeyUsageEncrypt);
3087
3088   // Unwrap with wrapped data too small must fail.
3089   const std::vector<uint8> small_data(test_ciphertext.begin(),
3090                                       test_ciphertext.begin() + 23);
3091   blink::WebCryptoKey unwrapped_key = blink::WebCryptoKey::createNull();
3092   EXPECT_EQ(Status::ErrorDataTooSmall(),
3093             UnwrapKey(blink::WebCryptoKeyFormatRaw,
3094                       CryptoData(small_data),
3095                       wrapping_key,
3096                       wrapping_algorithm,
3097                       key_algorithm,
3098                       true,
3099                       blink::WebCryptoKeyUsageEncrypt,
3100                       &unwrapped_key));
3101
3102   // Unwrap with wrapped data size not a multiple of 8 bytes must fail.
3103   const std::vector<uint8> unaligned_data(test_ciphertext.begin(),
3104                                           test_ciphertext.end() - 2);
3105   EXPECT_EQ(Status::ErrorInvalidAesKwDataLength(),
3106             UnwrapKey(blink::WebCryptoKeyFormatRaw,
3107                       CryptoData(unaligned_data),
3108                       wrapping_key,
3109                       wrapping_algorithm,
3110                       key_algorithm,
3111                       true,
3112                       blink::WebCryptoKeyUsageEncrypt,
3113                       &unwrapped_key));
3114 }
3115
3116 TEST_F(SharedCryptoTest, MAYBE(AesKwRawSymkeyUnwrapCorruptData)) {
3117   scoped_ptr<base::ListValue> tests;
3118   ASSERT_TRUE(ReadJsonTestFileToList("aes_kw.json", &tests));
3119   base::DictionaryValue* test;
3120   // Use 256 bits of data with a 256-bit KEK
3121   ASSERT_TRUE(tests->GetDictionary(3, &test));
3122   const std::vector<uint8> test_kek = GetBytesFromHexString(test, "kek");
3123   const std::vector<uint8> test_key = GetBytesFromHexString(test, "key");
3124   const std::vector<uint8> test_ciphertext =
3125       GetBytesFromHexString(test, "ciphertext");
3126   const blink::WebCryptoAlgorithm wrapping_algorithm =
3127       webcrypto::CreateAlgorithm(blink::WebCryptoAlgorithmIdAesKw);
3128
3129   // Import the wrapping key.
3130   blink::WebCryptoKey wrapping_key = ImportSecretKeyFromRaw(
3131       test_kek,
3132       wrapping_algorithm,
3133       blink::WebCryptoKeyUsageWrapKey | blink::WebCryptoKeyUsageUnwrapKey);
3134
3135   // Unwrap of a corrupted version of the known ciphertext should fail, due to
3136   // AES-KW's built-in integrity check.
3137   blink::WebCryptoKey unwrapped_key = blink::WebCryptoKey::createNull();
3138   EXPECT_EQ(
3139       Status::OperationError(),
3140       UnwrapKey(blink::WebCryptoKeyFormatRaw,
3141                 CryptoData(Corrupted(test_ciphertext)),
3142                 wrapping_key,
3143                 wrapping_algorithm,
3144                 webcrypto::CreateAlgorithm(blink::WebCryptoAlgorithmIdAesCbc),
3145                 true,
3146                 blink::WebCryptoKeyUsageEncrypt,
3147                 &unwrapped_key));
3148 }
3149
3150 TEST_F(SharedCryptoTest, MAYBE(AesKwJwkSymkeyUnwrapKnownData)) {
3151   // The following data lists a known HMAC SHA-256 key, then a JWK
3152   // representation of this key which was encrypted ("wrapped") using AES-KW and
3153   // the following wrapping key.
3154   // For reference, the intermediate clear JWK is
3155   // {"alg":"HS256","ext":true,"k":<b64urlKey>,"key_ops":["verify"],"kty":"oct"}
3156   // (Not shown is space padding to ensure the cleartext meets the size
3157   // requirements of the AES-KW algorithm.)
3158   const std::vector<uint8> key_data = HexStringToBytes(
3159       "000102030405060708090A0B0C0D0E0F000102030405060708090A0B0C0D0E0F");
3160   const std::vector<uint8> wrapped_key_data = HexStringToBytes(
3161       "14E6380B35FDC5B72E1994764B6CB7BFDD64E7832894356AAEE6C3768FC3D0F115E6B0"
3162       "6729756225F999AA99FDF81FD6A359F1576D3D23DE6CB69C3937054EB497AC1E8C38D5"
3163       "5E01B9783A20C8D930020932CF25926103002213D0FC37279888154FEBCEDF31832158"
3164       "97938C5CFE5B10B4254D0C399F39D0");
3165   const std::vector<uint8> wrapping_key_data =
3166       HexStringToBytes("000102030405060708090A0B0C0D0E0F");
3167   const blink::WebCryptoAlgorithm wrapping_algorithm =
3168       webcrypto::CreateAlgorithm(blink::WebCryptoAlgorithmIdAesKw);
3169
3170   // Import the wrapping key.
3171   blink::WebCryptoKey wrapping_key = ImportSecretKeyFromRaw(
3172       wrapping_key_data, wrapping_algorithm, blink::WebCryptoKeyUsageUnwrapKey);
3173
3174   // Unwrap the known wrapped key data to produce a new key
3175   blink::WebCryptoKey unwrapped_key = blink::WebCryptoKey::createNull();
3176   ASSERT_EQ(
3177       Status::Success(),
3178       UnwrapKey(blink::WebCryptoKeyFormatJwk,
3179                 CryptoData(wrapped_key_data),
3180                 wrapping_key,
3181                 wrapping_algorithm,
3182                 CreateHmacImportAlgorithm(blink::WebCryptoAlgorithmIdSha256),
3183                 true,
3184                 blink::WebCryptoKeyUsageVerify,
3185                 &unwrapped_key));
3186
3187   // Validate the new key's attributes.
3188   EXPECT_FALSE(unwrapped_key.isNull());
3189   EXPECT_TRUE(unwrapped_key.handle());
3190   EXPECT_EQ(blink::WebCryptoKeyTypeSecret, unwrapped_key.type());
3191   EXPECT_EQ(blink::WebCryptoAlgorithmIdHmac, unwrapped_key.algorithm().id());
3192   EXPECT_EQ(blink::WebCryptoAlgorithmIdSha256,
3193             unwrapped_key.algorithm().hmacParams()->hash().id());
3194   EXPECT_EQ(256u, unwrapped_key.algorithm().hmacParams()->lengthBits());
3195   EXPECT_EQ(true, unwrapped_key.extractable());
3196   EXPECT_EQ(blink::WebCryptoKeyUsageVerify, unwrapped_key.usages());
3197
3198   // Export the new key's raw data and compare to the known original.
3199   std::vector<uint8> raw_key;
3200   EXPECT_EQ(Status::Success(),
3201             ExportKey(blink::WebCryptoKeyFormatRaw, unwrapped_key, &raw_key));
3202   EXPECT_BYTES_EQ(key_data, raw_key);
3203 }
3204
3205 // TODO(eroman):
3206 //   * Test decryption when the tag length exceeds input size
3207 //   * Test decryption with empty input
3208 //   * Test decryption with tag length of 0.
3209 TEST_F(SharedCryptoTest, MAYBE(AesGcmSampleSets)) {
3210   // Some Linux test runners may not have a new enough version of NSS.
3211   if (!SupportsAesGcm()) {
3212     LOG(WARNING) << "AES GCM not supported, skipping tests";
3213     return;
3214   }
3215
3216   scoped_ptr<base::ListValue> tests;
3217   ASSERT_TRUE(ReadJsonTestFileToList("aes_gcm.json", &tests));
3218
3219   // Note that WebCrypto appends the authentication tag to the ciphertext.
3220   for (size_t test_index = 0; test_index < tests->GetSize(); ++test_index) {
3221     SCOPED_TRACE(test_index);
3222     base::DictionaryValue* test;
3223     ASSERT_TRUE(tests->GetDictionary(test_index, &test));
3224
3225     const std::vector<uint8> test_key = GetBytesFromHexString(test, "key");
3226     const std::vector<uint8> test_iv = GetBytesFromHexString(test, "iv");
3227     const std::vector<uint8> test_additional_data =
3228         GetBytesFromHexString(test, "additional_data");
3229     const std::vector<uint8> test_plain_text =
3230         GetBytesFromHexString(test, "plain_text");
3231     const std::vector<uint8> test_authentication_tag =
3232         GetBytesFromHexString(test, "authentication_tag");
3233     const unsigned int test_tag_size_bits = test_authentication_tag.size() * 8;
3234     const std::vector<uint8> test_cipher_text =
3235         GetBytesFromHexString(test, "cipher_text");
3236
3237     blink::WebCryptoKey key = ImportSecretKeyFromRaw(
3238         test_key,
3239         CreateAlgorithm(blink::WebCryptoAlgorithmIdAesGcm),
3240         blink::WebCryptoKeyUsageEncrypt | blink::WebCryptoKeyUsageDecrypt);
3241
3242     // Verify exported raw key is identical to the imported data
3243     std::vector<uint8> raw_key;
3244     EXPECT_EQ(Status::Success(),
3245               ExportKey(blink::WebCryptoKeyFormatRaw, key, &raw_key));
3246
3247     EXPECT_BYTES_EQ(test_key, raw_key);
3248
3249     // Test encryption.
3250     std::vector<uint8> cipher_text;
3251     std::vector<uint8> authentication_tag;
3252     EXPECT_EQ(Status::Success(),
3253               AesGcmEncrypt(key,
3254                             test_iv,
3255                             test_additional_data,
3256                             test_tag_size_bits,
3257                             test_plain_text,
3258                             &cipher_text,
3259                             &authentication_tag));
3260
3261     EXPECT_BYTES_EQ(test_cipher_text, cipher_text);
3262     EXPECT_BYTES_EQ(test_authentication_tag, authentication_tag);
3263
3264     // Test decryption.
3265     std::vector<uint8> plain_text;
3266     EXPECT_EQ(Status::Success(),
3267               AesGcmDecrypt(key,
3268                             test_iv,
3269                             test_additional_data,
3270                             test_tag_size_bits,
3271                             test_cipher_text,
3272                             test_authentication_tag,
3273                             &plain_text));
3274     EXPECT_BYTES_EQ(test_plain_text, plain_text);
3275
3276     // Decryption should fail if any of the inputs are tampered with.
3277     EXPECT_EQ(Status::OperationError(),
3278               AesGcmDecrypt(key,
3279                             Corrupted(test_iv),
3280                             test_additional_data,
3281                             test_tag_size_bits,
3282                             test_cipher_text,
3283                             test_authentication_tag,
3284                             &plain_text));
3285     EXPECT_EQ(Status::OperationError(),
3286               AesGcmDecrypt(key,
3287                             test_iv,
3288                             Corrupted(test_additional_data),
3289                             test_tag_size_bits,
3290                             test_cipher_text,
3291                             test_authentication_tag,
3292                             &plain_text));
3293     EXPECT_EQ(Status::OperationError(),
3294               AesGcmDecrypt(key,
3295                             test_iv,
3296                             test_additional_data,
3297                             test_tag_size_bits,
3298                             Corrupted(test_cipher_text),
3299                             test_authentication_tag,
3300                             &plain_text));
3301     EXPECT_EQ(Status::OperationError(),
3302               AesGcmDecrypt(key,
3303                             test_iv,
3304                             test_additional_data,
3305                             test_tag_size_bits,
3306                             test_cipher_text,
3307                             Corrupted(test_authentication_tag),
3308                             &plain_text));
3309
3310     // Try different incorrect tag lengths
3311     uint8 kAlternateTagLengths[] = {0, 8, 96, 120, 128, 160, 255};
3312     for (size_t tag_i = 0; tag_i < arraysize(kAlternateTagLengths); ++tag_i) {
3313       unsigned int wrong_tag_size_bits = kAlternateTagLengths[tag_i];
3314       if (test_tag_size_bits == wrong_tag_size_bits)
3315         continue;
3316       EXPECT_NE(Status::Success(),
3317                 AesGcmDecrypt(key,
3318                               test_iv,
3319                               test_additional_data,
3320                               wrong_tag_size_bits,
3321                               test_cipher_text,
3322                               test_authentication_tag,
3323                               &plain_text));
3324     }
3325   }
3326 }
3327
3328 // AES 192-bit is not allowed: http://crbug.com/381829
3329 TEST_F(SharedCryptoTest, MAYBE(ImportAesCbc192Raw)) {
3330   std::vector<uint8> key_raw(24, 0);
3331   blink::WebCryptoKey key = blink::WebCryptoKey::createNull();
3332   Status status = ImportKey(blink::WebCryptoKeyFormatRaw,
3333                             CryptoData(key_raw),
3334                             CreateAlgorithm(blink::WebCryptoAlgorithmIdAesCbc),
3335                             true,
3336                             blink::WebCryptoKeyUsageEncrypt,
3337                             &key);
3338   ASSERT_EQ(Status::ErrorAes192BitUnsupported(), status);
3339 }
3340
3341 // AES 192-bit is not allowed: http://crbug.com/381829
3342 TEST_F(SharedCryptoTest, MAYBE(ImportAesCbc192Jwk)) {
3343   blink::WebCryptoKey key = blink::WebCryptoKey::createNull();
3344
3345   base::DictionaryValue dict;
3346   dict.SetString("kty", "oct");
3347   dict.SetString("alg", "A192CBC");
3348   dict.SetString("k", "YWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFh");
3349
3350   EXPECT_EQ(
3351       Status::ErrorAes192BitUnsupported(),
3352       ImportKeyJwkFromDict(dict,
3353                            CreateAlgorithm(blink::WebCryptoAlgorithmIdAesCbc),
3354                            false,
3355                            blink::WebCryptoKeyUsageEncrypt,
3356                            &key));
3357 }
3358
3359 // AES 192-bit is not allowed: http://crbug.com/381829
3360 TEST_F(SharedCryptoTest, MAYBE(GenerateAesCbc192)) {
3361   blink::WebCryptoKey key = blink::WebCryptoKey::createNull();
3362   Status status = GenerateSecretKey(CreateAesCbcKeyGenAlgorithm(192),
3363                                     true,
3364                                     blink::WebCryptoKeyUsageEncrypt,
3365                                     &key);
3366   ASSERT_EQ(Status::ErrorAes192BitUnsupported(), status);
3367 }
3368
3369 // AES 192-bit is not allowed: http://crbug.com/381829
3370 TEST_F(SharedCryptoTest, MAYBE(UnwrapAesCbc192)) {
3371   std::vector<uint8> wrapping_key_data(16, 0);
3372   std::vector<uint8> wrapped_key = HexStringToBytes(
3373       "1A07ACAB6C906E50883173C29441DB1DE91D34F45C435B5F99C822867FB3956F");
3374
3375   blink::WebCryptoKey wrapping_key =
3376       ImportSecretKeyFromRaw(wrapping_key_data,
3377                              CreateAlgorithm(blink::WebCryptoAlgorithmIdAesKw),
3378                              blink::WebCryptoKeyUsageUnwrapKey);
3379
3380   blink::WebCryptoKey unwrapped_key = blink::WebCryptoKey::createNull();
3381       ASSERT_EQ(Status::ErrorAes192BitUnsupported(),
3382                 UnwrapKey(blink::WebCryptoKeyFormatRaw,
3383                           CryptoData(wrapped_key),
3384                           wrapping_key,
3385                           CreateAlgorithm(blink::WebCryptoAlgorithmIdAesKw),
3386                           CreateAlgorithm(blink::WebCryptoAlgorithmIdAesCbc),
3387                           true,
3388                           blink::WebCryptoKeyUsageEncrypt,
3389                           &unwrapped_key));
3390 }
3391
3392 class SharedCryptoRsaOaepTest : public ::testing::Test {
3393  public:
3394   SharedCryptoRsaOaepTest() { Init(); }
3395
3396   scoped_ptr<base::DictionaryValue> CreatePublicKeyJwkDict() {
3397     scoped_ptr<base::DictionaryValue> jwk(new base::DictionaryValue());
3398     jwk->SetString("kty", "RSA");
3399     jwk->SetString("n",
3400                    Base64EncodeUrlSafe(HexStringToBytes(kPublicKeyModulusHex)));
3401     jwk->SetString(
3402         "e", Base64EncodeUrlSafe(HexStringToBytes(kPublicKeyExponentHex)));
3403     return jwk.Pass();
3404   }
3405 };
3406
3407 // Import a PKCS#8 private key that uses RSAPrivateKey with the
3408 // id-rsaEncryption OID.
3409 TEST_F(SharedCryptoRsaOaepTest, ImportPkcs8WithRsaEncryption) {
3410   if (!SupportsRsaOaep()) {
3411     LOG(WARNING) << "RSA-OAEP support not present; skipping.";
3412     return;
3413   }
3414
3415   blink::WebCryptoKey private_key = blink::WebCryptoKey::createNull();
3416   ASSERT_EQ(Status::Success(),
3417             ImportKey(blink::WebCryptoKeyFormatPkcs8,
3418                       CryptoData(HexStringToBytes(kPrivateKeyPkcs8DerHex)),
3419                       CreateRsaHashedImportAlgorithm(
3420                           blink::WebCryptoAlgorithmIdRsaOaep,
3421                           blink::WebCryptoAlgorithmIdSha1),
3422                       true,
3423                       blink::WebCryptoKeyUsageDecrypt,
3424                       &private_key));
3425 }
3426
3427 TEST_F(SharedCryptoRsaOaepTest, ImportPublicJwkWithNoAlg) {
3428   if (!SupportsRsaOaep()) {
3429     LOG(WARNING) << "RSA-OAEP support not present; skipping.";
3430     return;
3431   }
3432
3433   scoped_ptr<base::DictionaryValue> jwk(CreatePublicKeyJwkDict());
3434
3435   blink::WebCryptoKey public_key = blink::WebCryptoKey::createNull();
3436   ASSERT_EQ(Status::Success(),
3437             ImportKeyJwkFromDict(*jwk.get(),
3438                                  CreateRsaHashedImportAlgorithm(
3439                                      blink::WebCryptoAlgorithmIdRsaOaep,
3440                                      blink::WebCryptoAlgorithmIdSha1),
3441                                  true,
3442                                  blink::WebCryptoKeyUsageEncrypt,
3443                                  &public_key));
3444 }
3445
3446 TEST_F(SharedCryptoRsaOaepTest, ImportPublicJwkWithMatchingAlg) {
3447   if (!SupportsRsaOaep()) {
3448     LOG(WARNING) << "RSA-OAEP support not present; skipping.";
3449     return;
3450   }
3451
3452   scoped_ptr<base::DictionaryValue> jwk(CreatePublicKeyJwkDict());
3453   jwk->SetString("alg", "RSA-OAEP");
3454
3455   blink::WebCryptoKey public_key = blink::WebCryptoKey::createNull();
3456   ASSERT_EQ(Status::Success(),
3457             ImportKeyJwkFromDict(*jwk.get(),
3458                                  CreateRsaHashedImportAlgorithm(
3459                                      blink::WebCryptoAlgorithmIdRsaOaep,
3460                                      blink::WebCryptoAlgorithmIdSha1),
3461                                  true,
3462                                  blink::WebCryptoKeyUsageEncrypt,
3463                                  &public_key));
3464 }
3465
3466 TEST_F(SharedCryptoRsaOaepTest, ImportPublicJwkWithMismatchedAlgFails) {
3467   if (!SupportsRsaOaep()) {
3468     LOG(WARNING) << "RSA-OAEP support not present; skipping.";
3469     return;
3470   }
3471
3472   scoped_ptr<base::DictionaryValue> jwk(CreatePublicKeyJwkDict());
3473   jwk->SetString("alg", "RSA-OAEP-512");
3474
3475   blink::WebCryptoKey public_key = blink::WebCryptoKey::createNull();
3476   ASSERT_EQ(Status::ErrorJwkAlgorithmInconsistent(),
3477             ImportKeyJwkFromDict(*jwk.get(),
3478                                  CreateRsaHashedImportAlgorithm(
3479                                      blink::WebCryptoAlgorithmIdRsaOaep,
3480                                      blink::WebCryptoAlgorithmIdSha1),
3481                                  true,
3482                                  blink::WebCryptoKeyUsageEncrypt,
3483                                  &public_key));
3484 }
3485
3486 TEST_F(SharedCryptoRsaOaepTest, ImportPublicJwkWithMismatchedTypeFails) {
3487   if (!SupportsRsaOaep()) {
3488     LOG(WARNING) << "RSA-OAEP support not present; skipping.";
3489     return;
3490   }
3491
3492   scoped_ptr<base::DictionaryValue> jwk(CreatePublicKeyJwkDict());
3493   jwk->SetString("kty", "oct");
3494   jwk->SetString("alg", "RSA-OAEP");
3495
3496   blink::WebCryptoKey public_key = blink::WebCryptoKey::createNull();
3497   ASSERT_EQ(Status::ErrorJwkPropertyMissing("k"),
3498             ImportKeyJwkFromDict(*jwk.get(),
3499                                  CreateRsaHashedImportAlgorithm(
3500                                      blink::WebCryptoAlgorithmIdRsaOaep,
3501                                      blink::WebCryptoAlgorithmIdSha1),
3502                                  true,
3503                                  blink::WebCryptoKeyUsageEncrypt,
3504                                  &public_key));
3505 }
3506
3507 TEST_F(SharedCryptoRsaOaepTest, ExportPublicJwk) {
3508   if (!SupportsRsaOaep()) {
3509     LOG(WARNING) << "RSA-OAEP support not present; skipping.";
3510     return;
3511   }
3512
3513   struct TestData {
3514     blink::WebCryptoAlgorithmId hash_alg;
3515     const char* expected_jwk_alg;
3516   } kTestData[] = {{blink::WebCryptoAlgorithmIdSha1, "RSA-OAEP"},
3517                    {blink::WebCryptoAlgorithmIdSha256, "RSA-OAEP-256"},
3518                    {blink::WebCryptoAlgorithmIdSha384, "RSA-OAEP-384"},
3519                    {blink::WebCryptoAlgorithmIdSha512, "RSA-OAEP-512"}};
3520   for (size_t i = 0; i < ARRAYSIZE_UNSAFE(kTestData); ++i) {
3521     const TestData& test_data = kTestData[i];
3522     SCOPED_TRACE(test_data.expected_jwk_alg);
3523
3524     scoped_ptr<base::DictionaryValue> jwk(CreatePublicKeyJwkDict());
3525     jwk->SetString("alg", test_data.expected_jwk_alg);
3526
3527     // Import the key in a known-good format
3528     blink::WebCryptoKey public_key = blink::WebCryptoKey::createNull();
3529     ASSERT_EQ(Status::Success(),
3530               ImportKeyJwkFromDict(
3531                   *jwk.get(),
3532                   CreateRsaHashedImportAlgorithm(
3533                       blink::WebCryptoAlgorithmIdRsaOaep, test_data.hash_alg),
3534                   true,
3535                   blink::WebCryptoKeyUsageEncrypt,
3536                   &public_key));
3537
3538     // Now export the key as JWK and verify its contents
3539     std::vector<uint8> jwk_data;
3540     ASSERT_EQ(Status::Success(),
3541               ExportKey(blink::WebCryptoKeyFormatJwk, public_key, &jwk_data));
3542     EXPECT_TRUE(VerifyPublicJwk(jwk_data,
3543                                 test_data.expected_jwk_alg,
3544                                 kPublicKeyModulusHex,
3545                                 kPublicKeyExponentHex,
3546                                 blink::WebCryptoKeyUsageEncrypt));
3547   }
3548 }
3549
3550 TEST_F(SharedCryptoRsaOaepTest, EncryptDecryptKnownAnswerTest) {
3551   if (!SupportsRsaOaep()) {
3552     LOG(WARNING) << "RSA-OAEP support not present; skipping.";
3553     return;
3554   }
3555
3556   scoped_ptr<base::ListValue> tests;
3557   ASSERT_TRUE(ReadJsonTestFileToList("rsa_oaep.json", &tests));
3558
3559   for (size_t test_index = 0; test_index < tests->GetSize(); ++test_index) {
3560     SCOPED_TRACE(test_index);
3561
3562     base::DictionaryValue* test = NULL;
3563     ASSERT_TRUE(tests->GetDictionary(test_index, &test));
3564
3565     blink::WebCryptoAlgorithm digest_algorithm =
3566         GetDigestAlgorithm(test, "hash");
3567     ASSERT_FALSE(digest_algorithm.isNull());
3568     std::vector<uint8> public_key_der =
3569         GetBytesFromHexString(test, "public_key");
3570     std::vector<uint8> private_key_der =
3571         GetBytesFromHexString(test, "private_key");
3572     std::vector<uint8> ciphertext = GetBytesFromHexString(test, "ciphertext");
3573     std::vector<uint8> plaintext = GetBytesFromHexString(test, "plaintext");
3574     std::vector<uint8> label = GetBytesFromHexString(test, "label");
3575
3576     blink::WebCryptoAlgorithm import_algorithm = CreateRsaHashedImportAlgorithm(
3577         blink::WebCryptoAlgorithmIdRsaOaep, digest_algorithm.id());
3578     blink::WebCryptoKey public_key = blink::WebCryptoKey::createNull();
3579     blink::WebCryptoKey private_key = blink::WebCryptoKey::createNull();
3580
3581     ASSERT_NO_FATAL_FAILURE(ImportRsaKeyPair(public_key_der,
3582                                              private_key_der,
3583                                              import_algorithm,
3584                                              false,
3585                                              blink::WebCryptoKeyUsageEncrypt,
3586                                              blink::WebCryptoKeyUsageDecrypt,
3587                                              &public_key,
3588                                              &private_key));
3589
3590     blink::WebCryptoAlgorithm op_algorithm = CreateRsaOaepAlgorithm(label);
3591     std::vector<uint8> decrypted_data;
3592     ASSERT_EQ(Status::Success(),
3593               Decrypt(op_algorithm,
3594                       private_key,
3595                       CryptoData(ciphertext),
3596                       &decrypted_data));
3597     EXPECT_BYTES_EQ(plaintext, decrypted_data);
3598     std::vector<uint8> encrypted_data;
3599     ASSERT_EQ(
3600         Status::Success(),
3601         Encrypt(
3602             op_algorithm, public_key, CryptoData(plaintext), &encrypted_data));
3603     std::vector<uint8> redecrypted_data;
3604     ASSERT_EQ(Status::Success(),
3605               Decrypt(op_algorithm,
3606                       private_key,
3607                       CryptoData(encrypted_data),
3608                       &redecrypted_data));
3609     EXPECT_BYTES_EQ(plaintext, redecrypted_data);
3610   }
3611 }
3612
3613 TEST_F(SharedCryptoRsaOaepTest, EncryptWithLargeMessageFails) {
3614   if (!SupportsRsaOaep()) {
3615     LOG(WARNING) << "RSA-OAEP support not present; skipping.";
3616     return;
3617   }
3618
3619   const blink::WebCryptoAlgorithmId kHash = blink::WebCryptoAlgorithmIdSha1;
3620   const size_t kHashSize = 20;
3621
3622   scoped_ptr<base::DictionaryValue> jwk(CreatePublicKeyJwkDict());
3623
3624   blink::WebCryptoKey public_key = blink::WebCryptoKey::createNull();
3625   ASSERT_EQ(Status::Success(),
3626             ImportKeyJwkFromDict(*jwk.get(),
3627                                  CreateRsaHashedImportAlgorithm(
3628                                      blink::WebCryptoAlgorithmIdRsaOaep, kHash),
3629                                  true,
3630                                  blink::WebCryptoKeyUsageEncrypt,
3631                                  &public_key));
3632
3633   // The maximum size of an encrypted message is:
3634   //   modulus length
3635   //   - 1 (leading octet)
3636   //   - hash size (maskedSeed)
3637   //   - hash size (lHash portion of maskedDB)
3638   //   - 1 (at least one octet for the padding string)
3639   size_t kMaxMessageSize = (kModulusLengthBits / 8) - 2 - (2 * kHashSize);
3640
3641   // The label has no influence on the maximum message size. For simplicity,
3642   // use the empty string.
3643   std::vector<uint8> label;
3644   blink::WebCryptoAlgorithm op_algorithm = CreateRsaOaepAlgorithm(label);
3645
3646   // Test that a message just before the boundary succeeds.
3647   std::string large_message;
3648   large_message.resize(kMaxMessageSize - 1, 'A');
3649
3650   std::vector<uint8> ciphertext;
3651   ASSERT_EQ(
3652       Status::Success(),
3653       Encrypt(
3654           op_algorithm, public_key, CryptoData(large_message), &ciphertext));
3655
3656   // Test that a message at the boundary succeeds.
3657   large_message.resize(kMaxMessageSize, 'A');
3658   ciphertext.clear();
3659
3660   ASSERT_EQ(
3661       Status::Success(),
3662       Encrypt(
3663           op_algorithm, public_key, CryptoData(large_message), &ciphertext));
3664
3665   // Test that a message greater than the largest size fails.
3666   large_message.resize(kMaxMessageSize + 1, 'A');
3667   ciphertext.clear();
3668
3669   ASSERT_EQ(
3670       Status::OperationError(),
3671       Encrypt(
3672           op_algorithm, public_key, CryptoData(large_message), &ciphertext));
3673 }
3674
3675 // Ensures that if the selected hash algorithm for the RSA-OAEP message is too
3676 // large, then it is rejected, independent of the actual message to be
3677 // encrypted.
3678 // For example, a 1024-bit RSA key is too small to accomodate a message that
3679 // uses OAEP with SHA-512, since it requires 1040 bits to encode
3680 // (2 * hash size + 2 padding bytes).
3681 TEST_F(SharedCryptoRsaOaepTest, EncryptWithLargeDigestFails) {
3682   if (!SupportsRsaOaep()) {
3683     LOG(WARNING) << "RSA-OAEP support not present; skipping.";
3684     return;
3685   }
3686
3687   const blink::WebCryptoAlgorithmId kHash = blink::WebCryptoAlgorithmIdSha512;
3688
3689   scoped_ptr<base::DictionaryValue> jwk(CreatePublicKeyJwkDict());
3690
3691   blink::WebCryptoKey public_key = blink::WebCryptoKey::createNull();
3692   ASSERT_EQ(Status::Success(),
3693             ImportKeyJwkFromDict(*jwk.get(),
3694                                  CreateRsaHashedImportAlgorithm(
3695                                      blink::WebCryptoAlgorithmIdRsaOaep, kHash),
3696                                  true,
3697                                  blink::WebCryptoKeyUsageEncrypt,
3698                                  &public_key));
3699
3700   // The label has no influence on the maximum message size. For simplicity,
3701   // use the empty string.
3702   std::vector<uint8> label;
3703   blink::WebCryptoAlgorithm op_algorithm = CreateRsaOaepAlgorithm(label);
3704
3705   std::string small_message("A");
3706   std::vector<uint8> ciphertext;
3707   // This is an operation error, as the internal consistency checking of the
3708   // algorithm parameters is up to the implementation.
3709   ASSERT_EQ(
3710       Status::OperationError(),
3711       Encrypt(
3712           op_algorithm, public_key, CryptoData(small_message), &ciphertext));
3713 }
3714
3715 TEST_F(SharedCryptoRsaOaepTest, DecryptWithLargeMessageFails) {
3716   if (!SupportsRsaOaep()) {
3717     LOG(WARNING) << "RSA-OAEP support not present; skipping.";
3718     return;
3719   }
3720
3721   blink::WebCryptoKey private_key = blink::WebCryptoKey::createNull();
3722   ASSERT_EQ(Status::Success(),
3723             ImportKey(blink::WebCryptoKeyFormatPkcs8,
3724                       CryptoData(HexStringToBytes(kPrivateKeyPkcs8DerHex)),
3725                       CreateRsaHashedImportAlgorithm(
3726                           blink::WebCryptoAlgorithmIdRsaOaep,
3727                           blink::WebCryptoAlgorithmIdSha1),
3728                       true,
3729                       blink::WebCryptoKeyUsageDecrypt,
3730                       &private_key));
3731
3732   // The label has no influence on the maximum message size. For simplicity,
3733   // use the empty string.
3734   std::vector<uint8> label;
3735   blink::WebCryptoAlgorithm op_algorithm = CreateRsaOaepAlgorithm(label);
3736
3737   std::string large_dummy_message(kModulusLengthBits / 8, 'A');
3738   std::vector<uint8> plaintext;
3739
3740   ASSERT_EQ(Status::OperationError(),
3741             Decrypt(op_algorithm,
3742                     private_key,
3743                     CryptoData(large_dummy_message),
3744                     &plaintext));
3745 }
3746
3747 TEST_F(SharedCryptoRsaOaepTest, WrapUnwrapRawKey) {
3748   if (!SupportsRsaOaep()) {
3749     LOG(WARNING) << "RSA-OAEP support not present; skipping.";
3750     return;
3751   }
3752
3753   blink::WebCryptoAlgorithm import_algorithm = CreateRsaHashedImportAlgorithm(
3754       blink::WebCryptoAlgorithmIdRsaOaep, blink::WebCryptoAlgorithmIdSha1);
3755   blink::WebCryptoKey public_key = blink::WebCryptoKey::createNull();
3756   blink::WebCryptoKey private_key = blink::WebCryptoKey::createNull();
3757
3758   ASSERT_NO_FATAL_FAILURE(ImportRsaKeyPair(
3759       HexStringToBytes(kPublicKeySpkiDerHex),
3760       HexStringToBytes(kPrivateKeyPkcs8DerHex),
3761       import_algorithm,
3762       false,
3763       blink::WebCryptoKeyUsageEncrypt | blink::WebCryptoKeyUsageWrapKey,
3764       blink::WebCryptoKeyUsageDecrypt | blink::WebCryptoKeyUsageUnwrapKey,
3765       &public_key,
3766       &private_key));
3767
3768   std::vector<uint8> label;
3769   blink::WebCryptoAlgorithm wrapping_algorithm = CreateRsaOaepAlgorithm(label);
3770
3771   const std::string key_hex = "000102030405060708090A0B0C0D0E0F";
3772   const blink::WebCryptoAlgorithm key_algorithm =
3773       webcrypto::CreateAlgorithm(blink::WebCryptoAlgorithmIdAesCbc);
3774
3775   blink::WebCryptoKey key =
3776       ImportSecretKeyFromRaw(HexStringToBytes(key_hex),
3777                              key_algorithm,
3778                              blink::WebCryptoKeyUsageEncrypt);
3779   ASSERT_FALSE(key.isNull());
3780
3781   std::vector<uint8> wrapped_key;
3782   ASSERT_EQ(Status::Success(),
3783             WrapKey(blink::WebCryptoKeyFormatRaw,
3784                     key,
3785                     public_key,
3786                     wrapping_algorithm,
3787                     &wrapped_key));
3788
3789   // Verify that |wrapped_key| can be decrypted and yields the key data.
3790   // Because |private_key| supports both decrypt and unwrap, this is valid.
3791   std::vector<uint8> decrypted_key;
3792   ASSERT_EQ(Status::Success(),
3793             Decrypt(wrapping_algorithm,
3794                     private_key,
3795                     CryptoData(wrapped_key),
3796                     &decrypted_key));
3797   EXPECT_BYTES_EQ_HEX(key_hex, decrypted_key);
3798
3799   // Now attempt to unwrap the key, which should also decrypt the data.
3800   blink::WebCryptoKey unwrapped_key = blink::WebCryptoKey::createNull();
3801   ASSERT_EQ(Status::Success(),
3802             UnwrapKey(blink::WebCryptoKeyFormatRaw,
3803                       CryptoData(wrapped_key),
3804                       private_key,
3805                       wrapping_algorithm,
3806                       key_algorithm,
3807                       true,
3808                       blink::WebCryptoKeyUsageEncrypt,
3809                       &unwrapped_key));
3810   ASSERT_FALSE(unwrapped_key.isNull());
3811
3812   std::vector<uint8> raw_key;
3813   ASSERT_EQ(Status::Success(),
3814             ExportKey(blink::WebCryptoKeyFormatRaw, unwrapped_key, &raw_key));
3815   EXPECT_BYTES_EQ_HEX(key_hex, raw_key);
3816 }
3817
3818 TEST_F(SharedCryptoRsaOaepTest, WrapUnwrapJwkSymKey) {
3819   if (!SupportsRsaOaep()) {
3820     LOG(WARNING) << "RSA-OAEP support not present; skipping.";
3821     return;
3822   }
3823
3824   // The public and private portions of a 2048-bit RSA key with the
3825   // id-rsaEncryption OID
3826   const char kPublicKey2048SpkiDerHex[] =
3827       "30820122300d06092a864886f70d01010105000382010f003082010a0282010100c5d8ce"
3828       "137a38168c8ab70229cfa5accc640567159750a312ce2e7d54b6e2fdd59b300c6a6c9764"
3829       "f8de6f00519cdb90111453d273a967462786480621f9e7cee5b73d63358448e7183a3a68"
3830       "e991186359f26aa88fbca5f53e673e502e4c5a2ba5068aeba60c9d0c44d872458d1b1e2f"
3831       "7f339f986076d516e93dc750f0b7680b6f5f02bc0d5590495be04c4ae59d34ba17bc5d08"
3832       "a93c75cfda2828f4a55b153af912038438276cb4a14f8116ca94db0ea9893652d02fc606"
3833       "36f19975e3d79a4d8ea8bfed6f8e0a24b63d243b08ea70a086ad56dd6341d733711c89ca"
3834       "749d4a80b3e6ecd2f8e53731eadeac2ea77788ee55d7b4b47c0f2523fbd61b557c16615d"
3835       "5d0203010001";
3836   const char kPrivateKey2048Pkcs8DerHex[] =
3837       "308204bd020100300d06092a864886f70d0101010500048204a7308204a3020100028201"
3838       "0100c5d8ce137a38168c8ab70229cfa5accc640567159750a312ce2e7d54b6e2fdd59b30"
3839       "0c6a6c9764f8de6f00519cdb90111453d273a967462786480621f9e7cee5b73d63358448"
3840       "e7183a3a68e991186359f26aa88fbca5f53e673e502e4c5a2ba5068aeba60c9d0c44d872"
3841       "458d1b1e2f7f339f986076d516e93dc750f0b7680b6f5f02bc0d5590495be04c4ae59d34"
3842       "ba17bc5d08a93c75cfda2828f4a55b153af912038438276cb4a14f8116ca94db0ea98936"
3843       "52d02fc60636f19975e3d79a4d8ea8bfed6f8e0a24b63d243b08ea70a086ad56dd6341d7"
3844       "33711c89ca749d4a80b3e6ecd2f8e53731eadeac2ea77788ee55d7b4b47c0f2523fbd61b"
3845       "557c16615d5d02030100010282010074b70feb41a0b0fcbc207670400556c9450042ede3"
3846       "d4383fb1ce8f3558a6d4641d26dd4c333fa4db842d2b9cf9d2354d3e16ad027a9f682d8c"
3847       "f4145a1ad97b9edcd8a41c402bd9d8db10f62f43df854cdccbbb2100834f083f53ed6d42"
3848       "b1b729a59072b004a4e945fc027db15e9c121d1251464d320d4774d5732df6b3dbf751f4"
3849       "9b19c9db201e19989c883bbaad5333db47f64f6f7a95b8d4936b10d945aa3f794cfaab62"
3850       "e7d47686129358914f3b8085f03698a650ab5b8c7e45813f2b0515ec05b6e5195b6a7c2a"
3851       "0d36969745f431ded4fd059f6aa361a4649541016d356297362b778e90f077d48815b339"
3852       "ec6f43aba345df93e67fcb6c2cb5b4544e9be902818100e9c90abe5f9f32468c5b6d630c"
3853       "54a4d7d75e29a72cf792f21e242aac78fd7995c42dfd4ae871d2619ff7096cb05baa78e3"
3854       "23ecab338401a8059adf7a0d8be3b21edc9a9c82c5605634a2ec81ec053271721351868a"
3855       "4c2e50c689d7cef94e31ff23658af5843366e2b289c5bf81d72756a7b93487dd8770d69c"
3856       "1f4e089d6d89f302818100d8a58a727c4e209132afd9933b98c89aca862a01cc0be74133"
3857       "bee517909e5c379e526895ac4af11780c1fe91194c777c9670b6423f0f5a32fd7691a622"
3858       "113eef4bed2ef863363a335fd55b0e75088c582437237d7f3ed3f0a643950237bc6e6277"
3859       "ccd0d0a1b4170aa1047aa7ffa7c8c54be10e8c7327ae2e0885663963817f6f02818100e5"
3860       "aed9ba4d71b7502e6748a1ce247ecb7bd10c352d6d9256031cdf3c11a65e44b0b7ca2945"
3861       "134671195af84c6b3bb3d10ebf65ae916f38bd5dbc59a0ad1c69b8beaf57cb3a8335f19b"
3862       "c7117b576987b48331cd9fd3d1a293436b7bb5e1a35c6560de4b5688ea834367cb0997eb"
3863       "b578f59ed4cb724c47dba94d3b484c1876dcd70281807f15bc7d2406007cac2b138a96af"
3864       "2d1e00276b84da593132c253fcb73212732dfd25824c2a615bc3d9b7f2c8d2fa542d3562"
3865       "b0c7738e61eeff580a6056239fb367ea9e5efe73d4f846033602e90c36a78db6fa8ea792"
3866       "0769675ec58e237bd994d189c8045a96f5dd3a4f12547257ce224e3c9af830a4da3c0eab"
3867       "9227a0035ae9028180067caea877e0b23090fc689322b71fbcce63d6596e66ab5fcdbaa0"
3868       "0d49e93aba8effb4518c2da637f209028401a68f344865b4956b032c69acde51d29177ca"
3869       "3db99fdbf5e74848ed4fa7bdfc2ebb60e2aaa5354770a763e1399ab7a2099762d525fea0"
3870       "37f3e1972c45a477e66db95c9609bb27f862700ef93379930786cf751b";
3871   blink::WebCryptoAlgorithm import_algorithm = CreateRsaHashedImportAlgorithm(
3872       blink::WebCryptoAlgorithmIdRsaOaep, blink::WebCryptoAlgorithmIdSha1);
3873   blink::WebCryptoKey public_key = blink::WebCryptoKey::createNull();
3874   blink::WebCryptoKey private_key = blink::WebCryptoKey::createNull();
3875
3876   ASSERT_NO_FATAL_FAILURE(ImportRsaKeyPair(
3877       HexStringToBytes(kPublicKey2048SpkiDerHex),
3878       HexStringToBytes(kPrivateKey2048Pkcs8DerHex),
3879       import_algorithm,
3880       false,
3881       blink::WebCryptoKeyUsageEncrypt | blink::WebCryptoKeyUsageWrapKey,
3882       blink::WebCryptoKeyUsageDecrypt | blink::WebCryptoKeyUsageUnwrapKey,
3883       &public_key,
3884       &private_key));
3885
3886   std::vector<uint8> label;
3887   blink::WebCryptoAlgorithm wrapping_algorithm = CreateRsaOaepAlgorithm(label);
3888
3889   const std::string key_hex = "000102030405060708090a0b0c0d0e0f";
3890   const blink::WebCryptoAlgorithm key_algorithm =
3891       webcrypto::CreateAlgorithm(blink::WebCryptoAlgorithmIdAesCbc);
3892
3893   blink::WebCryptoKey key =
3894       ImportSecretKeyFromRaw(HexStringToBytes(key_hex),
3895                              key_algorithm,
3896                              blink::WebCryptoKeyUsageEncrypt);
3897   ASSERT_FALSE(key.isNull());
3898
3899   std::vector<uint8> wrapped_key;
3900   ASSERT_EQ(Status::Success(),
3901             WrapKey(blink::WebCryptoKeyFormatJwk,
3902                     key,
3903                     public_key,
3904                     wrapping_algorithm,
3905                     &wrapped_key));
3906
3907   // Verify that |wrapped_key| can be decrypted and yields a valid JWK object.
3908   // Because |private_key| supports both decrypt and unwrap, this is valid.
3909   std::vector<uint8> decrypted_jwk;
3910   ASSERT_EQ(Status::Success(),
3911             Decrypt(wrapping_algorithm,
3912                     private_key,
3913                     CryptoData(wrapped_key),
3914                     &decrypted_jwk));
3915   EXPECT_TRUE(VerifySecretJwk(
3916       decrypted_jwk, "A128CBC", key_hex, blink::WebCryptoKeyUsageEncrypt));
3917
3918   // Now attempt to unwrap the key, which should also decrypt the data.
3919   blink::WebCryptoKey unwrapped_key = blink::WebCryptoKey::createNull();
3920   ASSERT_EQ(Status::Success(),
3921             UnwrapKey(blink::WebCryptoKeyFormatJwk,
3922                       CryptoData(wrapped_key),
3923                       private_key,
3924                       wrapping_algorithm,
3925                       key_algorithm,
3926                       true,
3927                       blink::WebCryptoKeyUsageEncrypt,
3928                       &unwrapped_key));
3929   ASSERT_FALSE(unwrapped_key.isNull());
3930
3931   std::vector<uint8> raw_key;
3932   ASSERT_EQ(Status::Success(),
3933             ExportKey(blink::WebCryptoKeyFormatRaw, unwrapped_key, &raw_key));
3934   EXPECT_BYTES_EQ_HEX(key_hex, raw_key);
3935 }
3936
3937 // Try importing an RSA-SSA public key with unsupported key usages using SPKI
3938 // format. RSA-SSA public keys only support the 'verify' usage.
3939 TEST_F(SharedCryptoTest, MAYBE(ImportRsaSsaPublicKeyBadUsage_SPKI)) {
3940   const blink::WebCryptoAlgorithm algorithm =
3941       CreateRsaHashedImportAlgorithm(blink::WebCryptoAlgorithmIdRsaSsaPkcs1v1_5,
3942                                      blink::WebCryptoAlgorithmIdSha256);
3943
3944   blink::WebCryptoKeyUsageMask bad_usages[] = {
3945       blink::WebCryptoKeyUsageSign,
3946       blink::WebCryptoKeyUsageSign | blink::WebCryptoKeyUsageVerify,
3947       blink::WebCryptoKeyUsageEncrypt,
3948       blink::WebCryptoKeyUsageEncrypt | blink::WebCryptoKeyUsageDecrypt,
3949   };
3950
3951   for (size_t i = 0; i < arraysize(bad_usages); ++i) {
3952     SCOPED_TRACE(i);
3953
3954     blink::WebCryptoKey public_key = blink::WebCryptoKey::createNull();
3955     ASSERT_EQ(Status::ErrorCreateKeyBadUsages(),
3956               ImportKey(blink::WebCryptoKeyFormatSpki,
3957                         CryptoData(HexStringToBytes(kPublicKeySpkiDerHex)),
3958                         algorithm,
3959                         false,
3960                         bad_usages[i],
3961                         &public_key));
3962   }
3963 }
3964
3965 // Try importing an RSA-SSA public key with unsupported key usages using JWK
3966 // format. RSA-SSA public keys only support the 'verify' usage.
3967 TEST_F(SharedCryptoTest, MAYBE(ImportRsaSsaPublicKeyBadUsage_JWK)) {
3968   const blink::WebCryptoAlgorithm algorithm =
3969       CreateRsaHashedImportAlgorithm(blink::WebCryptoAlgorithmIdRsaSsaPkcs1v1_5,
3970                                      blink::WebCryptoAlgorithmIdSha256);
3971
3972   blink::WebCryptoKeyUsageMask bad_usages[] = {
3973       blink::WebCryptoKeyUsageSign,
3974       blink::WebCryptoKeyUsageSign | blink::WebCryptoKeyUsageVerify,
3975       blink::WebCryptoKeyUsageEncrypt,
3976       blink::WebCryptoKeyUsageEncrypt | blink::WebCryptoKeyUsageDecrypt,
3977   };
3978
3979   base::DictionaryValue dict;
3980   RestoreJwkRsaDictionary(&dict);
3981   dict.Remove("use", NULL);
3982   dict.SetString("alg", "RS256");
3983
3984   for (size_t i = 0; i < arraysize(bad_usages); ++i) {
3985     SCOPED_TRACE(i);
3986
3987     blink::WebCryptoKey public_key = blink::WebCryptoKey::createNull();
3988     ASSERT_EQ(Status::ErrorCreateKeyBadUsages(),
3989               ImportKeyJwkFromDict(
3990                   dict, algorithm, false, bad_usages[i], &public_key));
3991   }
3992 }
3993
3994 // Try importing an AES-CBC key with unsupported key usages using raw
3995 // format. AES-CBC keys support the following usages:
3996 //   'encrypt', 'decrypt', 'wrapKey', 'unwrapKey'
3997 TEST_F(SharedCryptoTest, MAYBE(ImportAesCbcKeyBadUsage_Raw)) {
3998   const blink::WebCryptoAlgorithm algorithm =
3999       CreateAlgorithm(blink::WebCryptoAlgorithmIdAesCbc);
4000
4001   blink::WebCryptoKeyUsageMask bad_usages[] = {
4002       blink::WebCryptoKeyUsageSign,
4003       blink::WebCryptoKeyUsageSign | blink::WebCryptoKeyUsageDecrypt,
4004       blink::WebCryptoKeyUsageDeriveBits,
4005       blink::WebCryptoKeyUsageUnwrapKey | blink::WebCryptoKeyUsageVerify,
4006   };
4007
4008   std::vector<uint8> key_bytes(16);
4009
4010   for (size_t i = 0; i < arraysize(bad_usages); ++i) {
4011     SCOPED_TRACE(i);
4012
4013     blink::WebCryptoKey key = blink::WebCryptoKey::createNull();
4014     ASSERT_EQ(Status::ErrorCreateKeyBadUsages(),
4015               ImportKey(blink::WebCryptoKeyFormatRaw,
4016                         CryptoData(key_bytes),
4017                         algorithm,
4018                         true,
4019                         bad_usages[i],
4020                         &key));
4021   }
4022 }
4023
4024 // Try importing an AES-KW key with unsupported key usages using raw
4025 // format. AES-KW keys support the following usages:
4026 //   'wrapKey', 'unwrapKey'
4027 TEST_F(SharedCryptoTest, MAYBE(ImportAesKwKeyBadUsage_Raw)) {
4028   const blink::WebCryptoAlgorithm algorithm =
4029       CreateAlgorithm(blink::WebCryptoAlgorithmIdAesKw);
4030
4031   blink::WebCryptoKeyUsageMask bad_usages[] = {
4032       blink::WebCryptoKeyUsageEncrypt,
4033       blink::WebCryptoKeyUsageDecrypt,
4034       blink::WebCryptoKeyUsageSign,
4035       blink::WebCryptoKeyUsageSign | blink::WebCryptoKeyUsageUnwrapKey,
4036       blink::WebCryptoKeyUsageDeriveBits,
4037       blink::WebCryptoKeyUsageUnwrapKey | blink::WebCryptoKeyUsageVerify,
4038   };
4039
4040   std::vector<uint8> key_bytes(16);
4041
4042   for (size_t i = 0; i < arraysize(bad_usages); ++i) {
4043     SCOPED_TRACE(i);
4044
4045     blink::WebCryptoKey key = blink::WebCryptoKey::createNull();
4046     ASSERT_EQ(Status::ErrorCreateKeyBadUsages(),
4047               ImportKey(blink::WebCryptoKeyFormatRaw,
4048                         CryptoData(key_bytes),
4049                         algorithm,
4050                         true,
4051                         bad_usages[i],
4052                         &key));
4053   }
4054 }
4055
4056 // Try unwrapping an HMAC key with unsupported usages using JWK format and
4057 // AES-KW. HMAC keys support the following usages:
4058 //   'sign', 'verify'
4059 TEST_F(SharedCryptoTest, MAYBE(UnwrapHmacKeyBadUsage_JWK)) {
4060   const blink::WebCryptoAlgorithm unwrap_algorithm =
4061       CreateAlgorithm(blink::WebCryptoAlgorithmIdAesKw);
4062
4063   blink::WebCryptoKeyUsageMask bad_usages[] = {
4064       blink::WebCryptoKeyUsageEncrypt,
4065       blink::WebCryptoKeyUsageDecrypt,
4066       blink::WebCryptoKeyUsageWrapKey,
4067       blink::WebCryptoKeyUsageSign | blink::WebCryptoKeyUsageWrapKey,
4068       blink::WebCryptoKeyUsageVerify | blink::WebCryptoKeyUsageDeriveKey,
4069   };
4070
4071   // Import the wrapping key.
4072   blink::WebCryptoKey wrapping_key = blink::WebCryptoKey::createNull();
4073   ASSERT_EQ(Status::Success(),
4074             ImportKey(blink::WebCryptoKeyFormatRaw,
4075                       CryptoData(std::vector<uint8>(16)),
4076                       unwrap_algorithm,
4077                       true,
4078                       blink::WebCryptoKeyUsageUnwrapKey,
4079                       &wrapping_key));
4080
4081   // The JWK plain text is:
4082   //   {   "kty": "oct","alg": "HS256","k": "GADWrMRHwQfoNaXU5fZvTg=="}
4083   const char* kWrappedJwk =
4084       "0AA245F17064FFB2A7A094436A39BEBFC962C627303D1327EA750CE9F917688C2782A943"
4085       "7AE7586547AC490E8AE7D5B02D63868D5C3BB57D36C4C8C5BF3962ACEC6F42E767E5706"
4086       "4";
4087
4088   for (size_t i = 0; i < arraysize(bad_usages); ++i) {
4089     SCOPED_TRACE(i);
4090
4091     blink::WebCryptoKey key = blink::WebCryptoKey::createNull();
4092
4093     ASSERT_EQ(Status::ErrorCreateKeyBadUsages(),
4094               UnwrapKey(blink::WebCryptoKeyFormatJwk,
4095                         CryptoData(HexStringToBytes(kWrappedJwk)),
4096                         wrapping_key,
4097                         unwrap_algorithm,
4098                         webcrypto::CreateHmacImportAlgorithm(
4099                             blink::WebCryptoAlgorithmIdSha256),
4100                         true,
4101                         bad_usages[i],
4102                         &key));
4103   }
4104 }
4105
4106 // Try unwrapping an RSA-SSA public key with unsupported usages using JWK format
4107 // and AES-KW. RSA-SSA public keys support the following usages:
4108 //   'verify'
4109 TEST_F(SharedCryptoTest, MAYBE(UnwrapRsaSsaPublicKeyBadUsage_JWK)) {
4110   const blink::WebCryptoAlgorithm unwrap_algorithm =
4111       CreateAlgorithm(blink::WebCryptoAlgorithmIdAesKw);
4112
4113   blink::WebCryptoKeyUsageMask bad_usages[] = {
4114       blink::WebCryptoKeyUsageEncrypt,
4115       blink::WebCryptoKeyUsageSign,
4116       blink::WebCryptoKeyUsageDecrypt,
4117       blink::WebCryptoKeyUsageWrapKey,
4118       blink::WebCryptoKeyUsageSign | blink::WebCryptoKeyUsageWrapKey,
4119   };
4120
4121   // Import the wrapping key.
4122   blink::WebCryptoKey wrapping_key = blink::WebCryptoKey::createNull();
4123   ASSERT_EQ(Status::Success(),
4124             ImportKey(blink::WebCryptoKeyFormatRaw,
4125                       CryptoData(std::vector<uint8>(16)),
4126                       unwrap_algorithm,
4127                       true,
4128                       blink::WebCryptoKeyUsageUnwrapKey,
4129                       &wrapping_key));
4130
4131   // The JWK plaintext is:
4132   // {    "kty": "RSA","alg": "RS256","n": "...","e": "AQAB"}
4133
4134   const char* kWrappedJwk =
4135       "CE8DAEF99E977EE58958B8C4494755C846E883B2ECA575C5366622839AF71AB30875F152"
4136       "E8E33E15A7817A3A2874EB53EFE05C774D98BC936BA9BA29BEB8BB3F3C3CE2323CB3359D"
4137       "E3F426605CF95CCF0E01E870ABD7E35F62E030B5FB6E520A5885514D1D850FB64B57806D"
4138       "1ADA57C6E27DF345D8292D80F6B074F1BE51C4CF3D76ECC8886218551308681B44FAC60B"
4139       "8CF6EA439BC63239103D0AE81ADB96F908680586C6169284E32EB7DD09D31103EBDAC0C2"
4140       "40C72DCF0AEA454113CC47457B13305B25507CBEAB9BDC8D8E0F867F9167F9DCEF0D9F9B"
4141       "30F2EE83CEDFD51136852C8A5939B768";
4142
4143   for (size_t i = 0; i < arraysize(bad_usages); ++i) {
4144     SCOPED_TRACE(i);
4145
4146     blink::WebCryptoKey key = blink::WebCryptoKey::createNull();
4147
4148     ASSERT_EQ(Status::ErrorCreateKeyBadUsages(),
4149               UnwrapKey(blink::WebCryptoKeyFormatJwk,
4150                         CryptoData(HexStringToBytes(kWrappedJwk)),
4151                         wrapping_key,
4152                         unwrap_algorithm,
4153                         webcrypto::CreateRsaHashedImportAlgorithm(
4154                             blink::WebCryptoAlgorithmIdRsaSsaPkcs1v1_5,
4155                             blink::WebCryptoAlgorithmIdSha256),
4156                         true,
4157                         bad_usages[i],
4158                         &key));
4159   }
4160 }
4161
4162 // Generate an AES-CBC key with invalid usages. AES-CBC supports:
4163 //   'encrypt', 'decrypt', 'wrapKey', 'unwrapKey'
4164 TEST_F(SharedCryptoTest, MAYBE(GenerateAesKeyBadUsages)) {
4165   blink::WebCryptoKeyUsageMask bad_usages[] = {
4166       blink::WebCryptoKeyUsageSign, blink::WebCryptoKeyUsageVerify,
4167       blink::WebCryptoKeyUsageDecrypt | blink::WebCryptoKeyUsageVerify,
4168   };
4169
4170   for (size_t i = 0; i < arraysize(bad_usages); ++i) {
4171     SCOPED_TRACE(i);
4172
4173     blink::WebCryptoKey key = blink::WebCryptoKey::createNull();
4174
4175     ASSERT_EQ(Status::ErrorCreateKeyBadUsages(),
4176               GenerateSecretKey(
4177                   CreateAesCbcKeyGenAlgorithm(128), true, bad_usages[i], &key));
4178   }
4179 }
4180
4181 // Generate an RSA-SSA key pair with invalid usages. RSA-SSA supports:
4182 //   'sign', 'verify'
4183 TEST_F(SharedCryptoTest, MAYBE(GenerateRsaSsaBadUsages)) {
4184   blink::WebCryptoKeyUsageMask bad_usages[] = {
4185       blink::WebCryptoKeyUsageDecrypt,
4186       blink::WebCryptoKeyUsageVerify | blink::WebCryptoKeyUsageDecrypt,
4187       blink::WebCryptoKeyUsageWrapKey,
4188   };
4189
4190   const unsigned int modulus_length = 256;
4191   const std::vector<uint8> public_exponent = HexStringToBytes("010001");
4192
4193   for (size_t i = 0; i < arraysize(bad_usages); ++i) {
4194     SCOPED_TRACE(i);
4195
4196     blink::WebCryptoKey public_key = blink::WebCryptoKey::createNull();
4197     blink::WebCryptoKey private_key = blink::WebCryptoKey::createNull();
4198
4199     ASSERT_EQ(Status::ErrorCreateKeyBadUsages(),
4200               GenerateKeyPair(CreateRsaHashedKeyGenAlgorithm(
4201                                   blink::WebCryptoAlgorithmIdRsaSsaPkcs1v1_5,
4202                                   blink::WebCryptoAlgorithmIdSha256,
4203                                   modulus_length,
4204                                   public_exponent),
4205                               true,
4206                               bad_usages[i],
4207                               &public_key,
4208                               &private_key));
4209   }
4210 }
4211
4212 // Generate an RSA-SSA key pair. The public and private keys should select the
4213 // key usages which are applicable, and not have the exact same usages as was
4214 // specified to GenerateKey
4215 TEST_F(SharedCryptoTest, MAYBE(GenerateRsaSsaKeyPairIntersectUsages)) {
4216   const unsigned int modulus_length = 256;
4217   const std::vector<uint8> public_exponent = HexStringToBytes("010001");
4218
4219   blink::WebCryptoKey public_key = blink::WebCryptoKey::createNull();
4220   blink::WebCryptoKey private_key = blink::WebCryptoKey::createNull();
4221
4222   ASSERT_EQ(Status::Success(),
4223             GenerateKeyPair(
4224                 CreateRsaHashedKeyGenAlgorithm(
4225                     blink::WebCryptoAlgorithmIdRsaSsaPkcs1v1_5,
4226                     blink::WebCryptoAlgorithmIdSha256,
4227                     modulus_length,
4228                     public_exponent),
4229                 true,
4230                 blink::WebCryptoKeyUsageSign | blink::WebCryptoKeyUsageVerify,
4231                 &public_key,
4232                 &private_key));
4233
4234   EXPECT_EQ(blink::WebCryptoKeyUsageVerify, public_key.usages());
4235   EXPECT_EQ(blink::WebCryptoKeyUsageSign, private_key.usages());
4236
4237   // Try again but this time without the Verify usages.
4238   ASSERT_EQ(Status::Success(),
4239             GenerateKeyPair(CreateRsaHashedKeyGenAlgorithm(
4240                                 blink::WebCryptoAlgorithmIdRsaSsaPkcs1v1_5,
4241                                 blink::WebCryptoAlgorithmIdSha256,
4242                                 modulus_length,
4243                                 public_exponent),
4244                             true,
4245                             blink::WebCryptoKeyUsageSign,
4246                             &public_key,
4247                             &private_key));
4248
4249   EXPECT_EQ(0, public_key.usages());
4250   EXPECT_EQ(blink::WebCryptoKeyUsageSign, private_key.usages());
4251 }
4252
4253 // Generate an AES-CBC key and an RSA key pair. Use the AES-CBC key to wrap the
4254 // key pair (using SPKI format for public key, PKCS8 format for private key).
4255 // Then unwrap the wrapped key pair and verify that the key data is the same.
4256 TEST_F(SharedCryptoTest, MAYBE(WrapUnwrapRoundtripSpkiPkcs8UsingAesCbc)) {
4257   if (!SupportsRsaKeyImport())
4258     return;
4259
4260   // Generate the wrapping key.
4261   blink::WebCryptoKey wrapping_key = blink::WebCryptoKey::createNull();
4262   ASSERT_EQ(Status::Success(),
4263             GenerateSecretKey(CreateAesCbcKeyGenAlgorithm(128),
4264                               true,
4265                               blink::WebCryptoKeyUsageWrapKey |
4266                                   blink::WebCryptoKeyUsageUnwrapKey,
4267                               &wrapping_key));
4268
4269   // Generate an RSA key pair to be wrapped.
4270   const unsigned int modulus_length = 256;
4271   const std::vector<uint8> public_exponent = HexStringToBytes("010001");
4272
4273   blink::WebCryptoKey public_key = blink::WebCryptoKey::createNull();
4274   blink::WebCryptoKey private_key = blink::WebCryptoKey::createNull();
4275   ASSERT_EQ(Status::Success(),
4276             GenerateKeyPair(CreateRsaHashedKeyGenAlgorithm(
4277                                 blink::WebCryptoAlgorithmIdRsaSsaPkcs1v1_5,
4278                                 blink::WebCryptoAlgorithmIdSha256,
4279                                 modulus_length,
4280                                 public_exponent),
4281                             true,
4282                             0,
4283                             &public_key,
4284                             &private_key));
4285
4286   // Export key pair as SPKI + PKCS8
4287   std::vector<uint8> public_key_spki;
4288   ASSERT_EQ(
4289       Status::Success(),
4290       ExportKey(blink::WebCryptoKeyFormatSpki, public_key, &public_key_spki));
4291
4292   std::vector<uint8> private_key_pkcs8;
4293   ASSERT_EQ(
4294       Status::Success(),
4295       ExportKey(
4296           blink::WebCryptoKeyFormatPkcs8, private_key, &private_key_pkcs8));
4297
4298   // Wrap the key pair.
4299   blink::WebCryptoAlgorithm wrap_algorithm =
4300       CreateAesCbcAlgorithm(std::vector<uint8>(16, 0));
4301
4302   std::vector<uint8> wrapped_public_key;
4303   ASSERT_EQ(Status::Success(),
4304             WrapKey(blink::WebCryptoKeyFormatSpki,
4305                     public_key,
4306                     wrapping_key,
4307                     wrap_algorithm,
4308                     &wrapped_public_key));
4309
4310   std::vector<uint8> wrapped_private_key;
4311   ASSERT_EQ(Status::Success(),
4312             WrapKey(blink::WebCryptoKeyFormatPkcs8,
4313                     private_key,
4314                     wrapping_key,
4315                     wrap_algorithm,
4316                     &wrapped_private_key));
4317
4318   // Unwrap the key pair.
4319   blink::WebCryptoAlgorithm rsa_import_algorithm =
4320       CreateRsaHashedImportAlgorithm(blink::WebCryptoAlgorithmIdRsaSsaPkcs1v1_5,
4321                                      blink::WebCryptoAlgorithmIdSha256);
4322
4323   blink::WebCryptoKey unwrapped_public_key = blink::WebCryptoKey::createNull();
4324
4325   ASSERT_EQ(Status::Success(),
4326             UnwrapKey(blink::WebCryptoKeyFormatSpki,
4327                       CryptoData(wrapped_public_key),
4328                       wrapping_key,
4329                       wrap_algorithm,
4330                       rsa_import_algorithm,
4331                       true,
4332                       0,
4333                       &unwrapped_public_key));
4334
4335   blink::WebCryptoKey unwrapped_private_key = blink::WebCryptoKey::createNull();
4336
4337   ASSERT_EQ(Status::Success(),
4338             UnwrapKey(blink::WebCryptoKeyFormatPkcs8,
4339                       CryptoData(wrapped_private_key),
4340                       wrapping_key,
4341                       wrap_algorithm,
4342                       rsa_import_algorithm,
4343                       true,
4344                       0,
4345                       &unwrapped_private_key));
4346
4347   // Export unwrapped key pair as SPKI + PKCS8
4348   std::vector<uint8> unwrapped_public_key_spki;
4349   ASSERT_EQ(Status::Success(),
4350             ExportKey(blink::WebCryptoKeyFormatSpki,
4351                       unwrapped_public_key,
4352                       &unwrapped_public_key_spki));
4353
4354   std::vector<uint8> unwrapped_private_key_pkcs8;
4355   ASSERT_EQ(Status::Success(),
4356             ExportKey(blink::WebCryptoKeyFormatPkcs8,
4357                       unwrapped_private_key,
4358                       &unwrapped_private_key_pkcs8));
4359
4360   EXPECT_EQ(public_key_spki, unwrapped_public_key_spki);
4361   EXPECT_EQ(private_key_pkcs8, unwrapped_private_key_pkcs8);
4362
4363   EXPECT_NE(public_key_spki, wrapped_public_key);
4364   EXPECT_NE(private_key_pkcs8, wrapped_private_key);
4365 }
4366
4367 }  // namespace webcrypto
4368
4369 }  // namespace content