Update To 11.40.268.0
[platform/framework/web/crosswalk.git] / src / content / child / webcrypto / test / test_helpers.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/test/test_helpers.h"
6
7 #include <algorithm>
8
9 #include "base/files/file_util.h"
10 #include "base/json/json_reader.h"
11 #include "base/json/json_writer.h"
12 #include "base/logging.h"
13 #include "base/path_service.h"
14 #include "base/stl_util.h"
15 #include "base/strings/string_number_conversions.h"
16 #include "base/strings/string_util.h"
17 #include "base/values.h"
18 #include "content/child/webcrypto/algorithm_dispatch.h"
19 #include "content/child/webcrypto/crypto_data.h"
20 #include "content/child/webcrypto/generate_key_result.h"
21 #include "content/child/webcrypto/jwk.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 "third_party/WebKit/public/platform/WebCryptoAlgorithmParams.h"
26 #include "third_party/WebKit/public/platform/WebCryptoKeyAlgorithm.h"
27 #include "third_party/re2/re2/re2.h"
28
29 #if !defined(USE_OPENSSL)
30 #include <nss.h>
31 #include <pk11pub.h>
32
33 #include "crypto/nss_util.h"
34 #include "crypto/scoped_nss_types.h"
35 #endif
36
37 namespace content {
38
39 namespace webcrypto {
40
41 void PrintTo(const Status& status, ::std::ostream* os) {
42   *os << StatusToString(status);
43 }
44
45 bool operator==(const Status& a, const Status& b) {
46   if (a.IsSuccess() != b.IsSuccess())
47     return false;
48   if (a.IsSuccess())
49     return true;
50   return a.error_type() == b.error_type() &&
51          a.error_details() == b.error_details();
52 }
53
54 bool operator!=(const Status& a, const Status& b) {
55   return !(a == b);
56 }
57
58 void PrintTo(const CryptoData& data, ::std::ostream* os) {
59   *os << "[" << base::HexEncode(data.bytes(), data.byte_length()) << "]";
60 }
61
62 bool operator==(const CryptoData& a, const CryptoData& b) {
63   return a.byte_length() == b.byte_length() &&
64          memcmp(a.bytes(), b.bytes(), a.byte_length()) == 0;
65 }
66
67 bool operator!=(const CryptoData& a, const CryptoData& b) {
68   return !(a == b);
69 }
70
71 static std::string ErrorTypeToString(blink::WebCryptoErrorType type) {
72   switch (type) {
73     case blink::WebCryptoErrorTypeNotSupported:
74       return "NotSupported";
75     case blink::WebCryptoErrorTypeType:
76       return "TypeError";
77     case blink::WebCryptoErrorTypeData:
78       return "DataError";
79     case blink::WebCryptoErrorTypeSyntax:
80       return "SyntaxError";
81     case blink::WebCryptoErrorTypeOperation:
82       return "OperationError";
83     case blink::WebCryptoErrorTypeUnknown:
84       return "UnknownError";
85     case blink::WebCryptoErrorTypeInvalidState:
86       return "InvalidState";
87     case blink::WebCryptoErrorTypeInvalidAccess:
88       return "InvalidAccess";
89   }
90
91   return "?";
92 }
93
94 std::string StatusToString(const Status& status) {
95   if (status.IsSuccess())
96     return "Success";
97
98   std::string result = ErrorTypeToString(status.error_type());
99   if (!status.error_details().empty())
100     result += ": " + status.error_details();
101   return result;
102 }
103
104 bool SupportsAesGcm() {
105   std::vector<uint8_t> key_raw(16, 0);
106
107   blink::WebCryptoKey key;
108   Status status = ImportKey(blink::WebCryptoKeyFormatRaw,
109                             CryptoData(key_raw),
110                             CreateAlgorithm(blink::WebCryptoAlgorithmIdAesGcm),
111                             true,
112                             blink::WebCryptoKeyUsageEncrypt,
113                             &key);
114
115   if (status.IsError())
116     EXPECT_EQ(blink::WebCryptoErrorTypeNotSupported, status.error_type());
117   return status.IsSuccess();
118 }
119
120 bool SupportsRsaOaep() {
121 #if defined(USE_OPENSSL)
122   return true;
123 #else
124   crypto::EnsureNSSInit();
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 SupportsRsaPrivateKeyImport() {
136 // TODO(eroman): Exclude version test for OS_CHROMEOS
137 #if defined(USE_NSS)
138   crypto::EnsureNSSInit();
139   if (!NSS_VersionCheck("3.16.2")) {
140     LOG(WARNING) << "RSA key import is not supported by this version of NSS. "
141                     "Skipping some tests";
142     return false;
143   }
144 #endif
145   return true;
146 }
147
148 blink::WebCryptoAlgorithm CreateRsaHashedKeyGenAlgorithm(
149     blink::WebCryptoAlgorithmId algorithm_id,
150     const blink::WebCryptoAlgorithmId hash_id,
151     unsigned int modulus_length,
152     const std::vector<uint8_t>& public_exponent) {
153   DCHECK(blink::WebCryptoAlgorithm::isHash(hash_id));
154   return blink::WebCryptoAlgorithm::adoptParamsAndCreate(
155       algorithm_id,
156       new blink::WebCryptoRsaHashedKeyGenParams(
157           CreateAlgorithm(hash_id),
158           modulus_length,
159           vector_as_array(&public_exponent),
160           public_exponent.size()));
161 }
162
163 std::vector<uint8_t> Corrupted(const std::vector<uint8_t>& input) {
164   std::vector<uint8_t> corrupted_data(input);
165   if (corrupted_data.empty())
166     corrupted_data.push_back(0);
167   corrupted_data[corrupted_data.size() / 2] ^= 0x01;
168   return corrupted_data;
169 }
170
171 std::vector<uint8_t> HexStringToBytes(const std::string& hex) {
172   std::vector<uint8_t> bytes;
173   base::HexStringToBytes(hex, &bytes);
174   return bytes;
175 }
176
177 std::vector<uint8_t> MakeJsonVector(const std::string& json_string) {
178   return std::vector<uint8_t>(json_string.begin(), json_string.end());
179 }
180
181 std::vector<uint8_t> MakeJsonVector(const base::DictionaryValue& dict) {
182   std::string json;
183   base::JSONWriter::Write(&dict, &json);
184   return MakeJsonVector(json);
185 }
186
187 ::testing::AssertionResult ReadJsonTestFile(const char* test_file_name,
188                                             scoped_ptr<base::Value>* value) {
189   base::FilePath test_data_dir;
190   if (!PathService::Get(DIR_TEST_DATA, &test_data_dir))
191     return ::testing::AssertionFailure() << "Couldn't retrieve test dir";
192
193   base::FilePath file_path =
194       test_data_dir.AppendASCII("webcrypto").AppendASCII(test_file_name);
195
196   std::string file_contents;
197   if (!base::ReadFileToString(file_path, &file_contents)) {
198     return ::testing::AssertionFailure()
199            << "Couldn't read test file: " << file_path.value();
200   }
201
202   // Strip C++ style comments out of the "json" file, otherwise it cannot be
203   // parsed.
204   re2::RE2::GlobalReplace(&file_contents, re2::RE2("\\s*//.*"), "");
205
206   // Parse the JSON to a dictionary.
207   value->reset(base::JSONReader::Read(file_contents));
208   if (!value->get()) {
209     return ::testing::AssertionFailure()
210            << "Couldn't parse test file JSON: " << file_path.value();
211   }
212
213   return ::testing::AssertionSuccess();
214 }
215
216 ::testing::AssertionResult ReadJsonTestFileToList(
217     const char* test_file_name,
218     scoped_ptr<base::ListValue>* list) {
219   // Read the JSON.
220   scoped_ptr<base::Value> json;
221   ::testing::AssertionResult result = ReadJsonTestFile(test_file_name, &json);
222   if (!result)
223     return result;
224
225   // Cast to an ListValue.
226   base::ListValue* list_value = NULL;
227   if (!json->GetAsList(&list_value) || !list_value)
228     return ::testing::AssertionFailure() << "The JSON was not a list";
229
230   list->reset(list_value);
231   ignore_result(json.release());
232
233   return ::testing::AssertionSuccess();
234 }
235
236 ::testing::AssertionResult ReadJsonTestFileToDictionary(
237     const char* test_file_name,
238     scoped_ptr<base::DictionaryValue>* dict) {
239   // Read the JSON.
240   scoped_ptr<base::Value> json;
241   ::testing::AssertionResult result = ReadJsonTestFile(test_file_name, &json);
242   if (!result)
243     return result;
244
245   // Cast to an DictionaryValue.
246   base::DictionaryValue* dict_value = NULL;
247   if (!json->GetAsDictionary(&dict_value) || !dict_value)
248     return ::testing::AssertionFailure() << "The JSON was not a dictionary";
249
250   dict->reset(dict_value);
251   ignore_result(json.release());
252
253   return ::testing::AssertionSuccess();
254 }
255
256 std::vector<uint8_t> GetBytesFromHexString(const base::DictionaryValue* dict,
257                                            const std::string& property_name) {
258   std::string hex_string;
259   if (!dict->GetString(property_name, &hex_string)) {
260     EXPECT_TRUE(false) << "Couldn't get string property: " << property_name;
261     return std::vector<uint8_t>();
262   }
263
264   return HexStringToBytes(hex_string);
265 }
266
267 blink::WebCryptoAlgorithm GetDigestAlgorithm(const base::DictionaryValue* dict,
268                                              const char* property_name) {
269   std::string algorithm_name;
270   if (!dict->GetString(property_name, &algorithm_name)) {
271     EXPECT_TRUE(false) << "Couldn't get string property: " << property_name;
272     return blink::WebCryptoAlgorithm::createNull();
273   }
274
275   struct {
276     const char* name;
277     blink::WebCryptoAlgorithmId id;
278   } kDigestNameToId[] = {
279         {"sha-1", blink::WebCryptoAlgorithmIdSha1},
280         {"sha-256", blink::WebCryptoAlgorithmIdSha256},
281         {"sha-384", blink::WebCryptoAlgorithmIdSha384},
282         {"sha-512", blink::WebCryptoAlgorithmIdSha512},
283     };
284
285   for (size_t i = 0; i < arraysize(kDigestNameToId); ++i) {
286     if (kDigestNameToId[i].name == algorithm_name)
287       return CreateAlgorithm(kDigestNameToId[i].id);
288   }
289
290   return blink::WebCryptoAlgorithm::createNull();
291 }
292
293 // Creates a comparator for |bufs| which operates on indices rather than values.
294 class CompareUsingIndex {
295  public:
296   explicit CompareUsingIndex(const std::vector<std::vector<uint8_t> >* bufs)
297       : bufs_(bufs) {}
298
299   bool operator()(size_t i1, size_t i2) { return (*bufs_)[i1] < (*bufs_)[i2]; }
300
301  private:
302   const std::vector<std::vector<uint8_t> >* bufs_;
303 };
304
305 bool CopiesExist(const std::vector<std::vector<uint8_t> >& bufs) {
306   // Sort the indices of |bufs| into a separate vector. This reduces the amount
307   // of data copied versus sorting |bufs| directly.
308   std::vector<size_t> sorted_indices(bufs.size());
309   for (size_t i = 0; i < sorted_indices.size(); ++i)
310     sorted_indices[i] = i;
311   std::sort(
312       sorted_indices.begin(), sorted_indices.end(), CompareUsingIndex(&bufs));
313
314   // Scan for adjacent duplicates.
315   for (size_t i = 1; i < sorted_indices.size(); ++i) {
316     if (bufs[sorted_indices[i]] == bufs[sorted_indices[i - 1]])
317       return true;
318   }
319   return false;
320 }
321
322 blink::WebCryptoAlgorithm CreateAesKeyGenAlgorithm(
323     blink::WebCryptoAlgorithmId aes_alg_id,
324     unsigned short length) {
325   return blink::WebCryptoAlgorithm::adoptParamsAndCreate(
326       aes_alg_id, new blink::WebCryptoAesKeyGenParams(length));
327 }
328
329 // The following key pair is comprised of the SPKI (public key) and PKCS#8
330 // (private key) representations of the key pair provided in Example 1 of the
331 // NIST test vectors at
332 // ftp://ftp.rsa.com/pub/rsalabs/tmp/pkcs1v15sign-vectors.txt
333 const unsigned int kModulusLengthBits = 1024;
334 const char* const kPublicKeySpkiDerHex =
335     "30819f300d06092a864886f70d010101050003818d0030818902818100a5"
336     "6e4a0e701017589a5187dc7ea841d156f2ec0e36ad52a44dfeb1e61f7ad9"
337     "91d8c51056ffedb162b4c0f283a12a88a394dff526ab7291cbb307ceabfc"
338     "e0b1dfd5cd9508096d5b2b8b6df5d671ef6377c0921cb23c270a70e2598e"
339     "6ff89d19f105acc2d3f0cb35f29280e1386b6f64c4ef22e1e1f20d0ce8cf"
340     "fb2249bd9a21370203010001";
341 const char* const kPrivateKeyPkcs8DerHex =
342     "30820275020100300d06092a864886f70d01010105000482025f3082025b"
343     "02010002818100a56e4a0e701017589a5187dc7ea841d156f2ec0e36ad52"
344     "a44dfeb1e61f7ad991d8c51056ffedb162b4c0f283a12a88a394dff526ab"
345     "7291cbb307ceabfce0b1dfd5cd9508096d5b2b8b6df5d671ef6377c0921c"
346     "b23c270a70e2598e6ff89d19f105acc2d3f0cb35f29280e1386b6f64c4ef"
347     "22e1e1f20d0ce8cffb2249bd9a2137020301000102818033a5042a90b27d"
348     "4f5451ca9bbbd0b44771a101af884340aef9885f2a4bbe92e894a724ac3c"
349     "568c8f97853ad07c0266c8c6a3ca0929f1e8f11231884429fc4d9ae55fee"
350     "896a10ce707c3ed7e734e44727a39574501a532683109c2abacaba283c31"
351     "b4bd2f53c3ee37e352cee34f9e503bd80c0622ad79c6dcee883547c6a3b3"
352     "25024100e7e8942720a877517273a356053ea2a1bc0c94aa72d55c6e8629"
353     "6b2dfc967948c0a72cbccca7eacb35706e09a1df55a1535bd9b3cc34160b"
354     "3b6dcd3eda8e6443024100b69dca1cf7d4d7ec81e75b90fcca874abcde12"
355     "3fd2700180aa90479b6e48de8d67ed24f9f19d85ba275874f542cd20dc72"
356     "3e6963364a1f9425452b269a6799fd024028fa13938655be1f8a159cbaca"
357     "5a72ea190c30089e19cd274a556f36c4f6e19f554b34c077790427bbdd8d"
358     "d3ede2448328f385d81b30e8e43b2fffa02786197902401a8b38f398fa71"
359     "2049898d7fb79ee0a77668791299cdfa09efc0e507acb21ed74301ef5bfd"
360     "48be455eaeb6e1678255827580a8e4e8e14151d1510a82a3f2e729024027"
361     "156aba4126d24a81f3a528cbfb27f56886f840a9f6e86e17a44b94fe9319"
362     "584b8e22fdde1e5a2e3bd8aa5ba8d8584194eb2190acf832b847f13a3d24"
363     "a79f4d";
364 // The modulus and exponent (in hex) of kPublicKeySpkiDerHex
365 const char* const kPublicKeyModulusHex =
366     "A56E4A0E701017589A5187DC7EA841D156F2EC0E36AD52A44DFEB1E61F7AD991D8C51056"
367     "FFEDB162B4C0F283A12A88A394DFF526AB7291CBB307CEABFCE0B1DFD5CD9508096D5B2B"
368     "8B6DF5D671EF6377C0921CB23C270A70E2598E6FF89D19F105ACC2D3F0CB35F29280E138"
369     "6B6F64C4EF22E1E1F20D0CE8CFFB2249BD9A2137";
370 const char* const kPublicKeyExponentHex = "010001";
371
372 blink::WebCryptoKey ImportSecretKeyFromRaw(
373     const std::vector<uint8_t>& key_raw,
374     const blink::WebCryptoAlgorithm& algorithm,
375     blink::WebCryptoKeyUsageMask usage) {
376   blink::WebCryptoKey key;
377   bool extractable = true;
378   EXPECT_EQ(Status::Success(),
379             ImportKey(blink::WebCryptoKeyFormatRaw,
380                       CryptoData(key_raw),
381                       algorithm,
382                       extractable,
383                       usage,
384                       &key));
385
386   EXPECT_FALSE(key.isNull());
387   EXPECT_TRUE(key.handle());
388   EXPECT_EQ(blink::WebCryptoKeyTypeSecret, key.type());
389   EXPECT_EQ(algorithm.id(), key.algorithm().id());
390   EXPECT_EQ(extractable, key.extractable());
391   EXPECT_EQ(usage, key.usages());
392   return key;
393 }
394
395 void ImportRsaKeyPair(const std::vector<uint8_t>& spki_der,
396                       const std::vector<uint8_t>& pkcs8_der,
397                       const blink::WebCryptoAlgorithm& algorithm,
398                       bool extractable,
399                       blink::WebCryptoKeyUsageMask public_key_usages,
400                       blink::WebCryptoKeyUsageMask private_key_usages,
401                       blink::WebCryptoKey* public_key,
402                       blink::WebCryptoKey* private_key) {
403   ASSERT_EQ(Status::Success(),
404             ImportKey(blink::WebCryptoKeyFormatSpki,
405                       CryptoData(spki_der),
406                       algorithm,
407                       true,
408                       public_key_usages,
409                       public_key));
410   EXPECT_FALSE(public_key->isNull());
411   EXPECT_TRUE(public_key->handle());
412   EXPECT_EQ(blink::WebCryptoKeyTypePublic, public_key->type());
413   EXPECT_EQ(algorithm.id(), public_key->algorithm().id());
414   EXPECT_TRUE(public_key->extractable());
415   EXPECT_EQ(public_key_usages, public_key->usages());
416
417   ASSERT_EQ(Status::Success(),
418             ImportKey(blink::WebCryptoKeyFormatPkcs8,
419                       CryptoData(pkcs8_der),
420                       algorithm,
421                       extractable,
422                       private_key_usages,
423                       private_key));
424   EXPECT_FALSE(private_key->isNull());
425   EXPECT_TRUE(private_key->handle());
426   EXPECT_EQ(blink::WebCryptoKeyTypePrivate, private_key->type());
427   EXPECT_EQ(algorithm.id(), private_key->algorithm().id());
428   EXPECT_EQ(extractable, private_key->extractable());
429   EXPECT_EQ(private_key_usages, private_key->usages());
430 }
431
432 Status ImportKeyJwkFromDict(const base::DictionaryValue& dict,
433                             const blink::WebCryptoAlgorithm& algorithm,
434                             bool extractable,
435                             blink::WebCryptoKeyUsageMask usages,
436                             blink::WebCryptoKey* key) {
437   return ImportKey(blink::WebCryptoKeyFormatJwk,
438                    CryptoData(MakeJsonVector(dict)),
439                    algorithm,
440                    extractable,
441                    usages,
442                    key);
443 }
444
445 scoped_ptr<base::DictionaryValue> GetJwkDictionary(
446     const std::vector<uint8_t>& json) {
447   base::StringPiece json_string(
448       reinterpret_cast<const char*>(vector_as_array(&json)), json.size());
449   base::Value* value = base::JSONReader::Read(json_string);
450   EXPECT_TRUE(value);
451   base::DictionaryValue* dict_value = NULL;
452   value->GetAsDictionary(&dict_value);
453   return scoped_ptr<base::DictionaryValue>(dict_value);
454 }
455
456 // Verifies the input dictionary contains the expected values. Exact matches are
457 // required on the fields examined.
458 ::testing::AssertionResult VerifyJwk(
459     const scoped_ptr<base::DictionaryValue>& dict,
460     const std::string& kty_expected,
461     const std::string& alg_expected,
462     blink::WebCryptoKeyUsageMask use_mask_expected) {
463   // ---- kty
464   std::string value_string;
465   if (!dict->GetString("kty", &value_string))
466     return ::testing::AssertionFailure() << "Missing 'kty'";
467   if (value_string != kty_expected)
468     return ::testing::AssertionFailure() << "Expected 'kty' to be "
469                                          << kty_expected << "but found "
470                                          << value_string;
471
472   // ---- alg
473   if (!dict->GetString("alg", &value_string))
474     return ::testing::AssertionFailure() << "Missing 'alg'";
475   if (value_string != alg_expected)
476     return ::testing::AssertionFailure() << "Expected 'alg' to be "
477                                          << alg_expected << " but found "
478                                          << value_string;
479
480   // ---- ext
481   // always expect ext == true in this case
482   bool ext_value;
483   if (!dict->GetBoolean("ext", &ext_value))
484     return ::testing::AssertionFailure() << "Missing 'ext'";
485   if (!ext_value)
486     return ::testing::AssertionFailure()
487            << "Expected 'ext' to be true but found false";
488
489   // ---- key_ops
490   base::ListValue* key_ops;
491   if (!dict->GetList("key_ops", &key_ops))
492     return ::testing::AssertionFailure() << "Missing 'key_ops'";
493   blink::WebCryptoKeyUsageMask key_ops_mask = 0;
494   Status status = GetWebCryptoUsagesFromJwkKeyOps(key_ops, &key_ops_mask);
495   if (status.IsError())
496     return ::testing::AssertionFailure() << "Failure extracting 'key_ops'";
497   if (key_ops_mask != use_mask_expected)
498     return ::testing::AssertionFailure()
499            << "Expected 'key_ops' mask to be " << use_mask_expected
500            << " but found " << key_ops_mask << " (" << value_string << ")";
501
502   return ::testing::AssertionSuccess();
503 }
504
505 ::testing::AssertionResult VerifySecretJwk(
506     const std::vector<uint8_t>& json,
507     const std::string& alg_expected,
508     const std::string& k_expected_hex,
509     blink::WebCryptoKeyUsageMask use_mask_expected) {
510   scoped_ptr<base::DictionaryValue> dict = GetJwkDictionary(json);
511   if (!dict.get() || dict->empty())
512     return ::testing::AssertionFailure() << "JSON parsing failed";
513
514   // ---- k
515   std::string value_string;
516   if (!dict->GetString("k", &value_string))
517     return ::testing::AssertionFailure() << "Missing 'k'";
518   std::string k_value;
519   if (!Base64DecodeUrlSafe(value_string, &k_value))
520     return ::testing::AssertionFailure() << "Base64DecodeUrlSafe(k) failed";
521   if (!LowerCaseEqualsASCII(base::HexEncode(k_value.data(), k_value.size()),
522                             k_expected_hex.c_str())) {
523     return ::testing::AssertionFailure() << "Expected 'k' to be "
524                                          << k_expected_hex
525                                          << " but found something different";
526   }
527
528   return VerifyJwk(dict, "oct", alg_expected, use_mask_expected);
529 }
530
531 ::testing::AssertionResult VerifyPublicJwk(
532     const std::vector<uint8_t>& json,
533     const std::string& alg_expected,
534     const std::string& n_expected_hex,
535     const std::string& e_expected_hex,
536     blink::WebCryptoKeyUsageMask use_mask_expected) {
537   scoped_ptr<base::DictionaryValue> dict = GetJwkDictionary(json);
538   if (!dict.get() || dict->empty())
539     return ::testing::AssertionFailure() << "JSON parsing failed";
540
541   // ---- n
542   std::string value_string;
543   if (!dict->GetString("n", &value_string))
544     return ::testing::AssertionFailure() << "Missing 'n'";
545   std::string n_value;
546   if (!Base64DecodeUrlSafe(value_string, &n_value))
547     return ::testing::AssertionFailure() << "Base64DecodeUrlSafe(n) failed";
548   if (base::HexEncode(n_value.data(), n_value.size()) != n_expected_hex) {
549     return ::testing::AssertionFailure() << "'n' does not match the expected "
550                                             "value";
551   }
552   // TODO(padolph): LowerCaseEqualsASCII() does not work for above!
553
554   // ---- e
555   if (!dict->GetString("e", &value_string))
556     return ::testing::AssertionFailure() << "Missing 'e'";
557   std::string e_value;
558   if (!Base64DecodeUrlSafe(value_string, &e_value))
559     return ::testing::AssertionFailure() << "Base64DecodeUrlSafe(e) failed";
560   if (!LowerCaseEqualsASCII(base::HexEncode(e_value.data(), e_value.size()),
561                             e_expected_hex.c_str())) {
562     return ::testing::AssertionFailure() << "Expected 'e' to be "
563                                          << e_expected_hex
564                                          << " but found something different";
565   }
566
567   return VerifyJwk(dict, "RSA", alg_expected, use_mask_expected);
568 }
569
570 void ImportExportJwkSymmetricKey(
571     int key_len_bits,
572     const blink::WebCryptoAlgorithm& import_algorithm,
573     blink::WebCryptoKeyUsageMask usages,
574     const std::string& jwk_alg) {
575   std::vector<uint8_t> json;
576   std::string key_hex;
577
578   // Hardcoded pseudo-random bytes to use for keys of different lengths.
579   switch (key_len_bits) {
580     case 128:
581       key_hex = "3f1e7cd4f6f8543f6b1e16002e688623";
582       break;
583     case 256:
584       key_hex =
585           "bd08286b81a74783fd1ccf46b7e05af84ee25ae021210074159e0c4d9d907692";
586       break;
587     case 384:
588       key_hex =
589           "a22c5441c8b185602283d64c7221de1d0951e706bfc09539435ec0e0ed614e1d40"
590           "6623f2b31d31819fec30993380dd82";
591       break;
592     case 512:
593       key_hex =
594           "5834f639000d4cf82de124fbfd26fb88d463e99f839a76ba41ac88967c80a3f61e"
595           "1239a452e573dba0750e988152988576efd75b8d0229b7aca2ada2afd392ee";
596       break;
597     default:
598       FAIL() << "Unexpected key_len_bits" << key_len_bits;
599   }
600
601   // Import a raw key.
602   blink::WebCryptoKey key = ImportSecretKeyFromRaw(
603       HexStringToBytes(key_hex), import_algorithm, usages);
604
605   // Export the key in JWK format and validate.
606   ASSERT_EQ(Status::Success(),
607             ExportKey(blink::WebCryptoKeyFormatJwk, key, &json));
608   EXPECT_TRUE(VerifySecretJwk(json, jwk_alg, key_hex, usages));
609
610   // Import the JWK-formatted key.
611   ASSERT_EQ(Status::Success(),
612             ImportKey(blink::WebCryptoKeyFormatJwk,
613                       CryptoData(json),
614                       import_algorithm,
615                       true,
616                       usages,
617                       &key));
618   EXPECT_TRUE(key.handle());
619   EXPECT_EQ(blink::WebCryptoKeyTypeSecret, key.type());
620   EXPECT_EQ(import_algorithm.id(), key.algorithm().id());
621   EXPECT_EQ(true, key.extractable());
622   EXPECT_EQ(usages, key.usages());
623
624   // Export the key in raw format and compare to the original.
625   std::vector<uint8_t> key_raw_out;
626   ASSERT_EQ(Status::Success(),
627             ExportKey(blink::WebCryptoKeyFormatRaw, key, &key_raw_out));
628   EXPECT_BYTES_EQ_HEX(key_hex, key_raw_out);
629 }
630
631 Status GenerateSecretKey(const blink::WebCryptoAlgorithm& algorithm,
632                          bool extractable,
633                          blink::WebCryptoKeyUsageMask usages,
634                          blink::WebCryptoKey* key) {
635   GenerateKeyResult result;
636   Status status = GenerateKey(algorithm, extractable, usages, &result);
637   if (status.IsError())
638     return status;
639
640   if (result.type() != GenerateKeyResult::TYPE_SECRET_KEY)
641     return Status::ErrorUnexpected();
642
643   *key = result.secret_key();
644
645   return Status::Success();
646 }
647
648 Status GenerateKeyPair(const blink::WebCryptoAlgorithm& algorithm,
649                        bool extractable,
650                        blink::WebCryptoKeyUsageMask usages,
651                        blink::WebCryptoKey* public_key,
652                        blink::WebCryptoKey* private_key) {
653   GenerateKeyResult result;
654   Status status = GenerateKey(algorithm, extractable, usages, &result);
655   if (status.IsError())
656     return status;
657
658   if (result.type() != GenerateKeyResult::TYPE_PUBLIC_PRIVATE_KEY_PAIR)
659     return Status::ErrorUnexpected();
660
661   *public_key = result.public_key();
662   *private_key = result.private_key();
663
664   return Status::Success();
665 }
666
667 blink::WebCryptoKeyFormat GetKeyFormatFromJsonTestCase(
668     const base::DictionaryValue* test) {
669   std::string format;
670   EXPECT_TRUE(test->GetString("key_format", &format));
671   if (format == "jwk")
672     return blink::WebCryptoKeyFormatJwk;
673   else if (format == "pkcs8")
674     return blink::WebCryptoKeyFormatPkcs8;
675   else if (format == "spki")
676     return blink::WebCryptoKeyFormatSpki;
677
678   EXPECT_TRUE(false) << "Unrecognized key format: " << format;
679   return blink::WebCryptoKeyFormatRaw;
680 }
681
682 std::vector<uint8_t> GetKeyDataFromJsonTestCase(
683     const base::DictionaryValue* test,
684     blink::WebCryptoKeyFormat key_format) {
685   if (key_format == blink::WebCryptoKeyFormatJwk) {
686     const base::DictionaryValue* json;
687     EXPECT_TRUE(test->GetDictionary("key", &json));
688     return MakeJsonVector(*json);
689   }
690   return GetBytesFromHexString(test, "key");
691 }
692
693 }  // namespace webcrypto
694
695 }  // namesapce content