cc: Make picture pile base thread safe.
[chromium-blink-merge.git] / content / child / webcrypto / test / test_helpers.cc
blob00af7628c2cc2e5f7235f25035dec8d44e4dceb6
1 // Copyright 2014 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
5 #include "content/child/webcrypto/test/test_helpers.h"
7 #include <algorithm>
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"
29 #if !defined(USE_OPENSSL)
30 #include <nss.h>
31 #include <pk11pub.h>
33 #include "crypto/nss_util.h"
34 #include "crypto/scoped_nss_types.h"
35 #endif
37 namespace content {
39 namespace webcrypto {
41 void PrintTo(const Status& status, ::std::ostream* os) {
42 if (status.IsSuccess())
43 *os << "Success";
44 else
45 *os << "Error type: " << status.error_type()
46 << " Error details: " << status.error_details();
49 bool operator==(const Status& a, const Status& b) {
50 if (a.IsSuccess() != b.IsSuccess())
51 return false;
52 if (a.IsSuccess())
53 return true;
54 return a.error_type() == b.error_type() &&
55 a.error_details() == b.error_details();
58 bool operator!=(const Status& a, const Status& b) {
59 return !(a == b);
62 void PrintTo(const CryptoData& data, ::std::ostream* os) {
63 *os << "[" << base::HexEncode(data.bytes(), data.byte_length()) << "]";
66 bool operator==(const CryptoData& a, const CryptoData& b) {
67 return a.byte_length() == b.byte_length() &&
68 memcmp(a.bytes(), b.bytes(), a.byte_length()) == 0;
71 bool operator!=(const CryptoData& a, const CryptoData& b) {
72 return !(a == b);
75 bool SupportsAesGcm() {
76 std::vector<uint8_t> key_raw(16, 0);
78 blink::WebCryptoKey key;
79 Status status = ImportKey(blink::WebCryptoKeyFormatRaw,
80 CryptoData(key_raw),
81 CreateAlgorithm(blink::WebCryptoAlgorithmIdAesGcm),
82 true,
83 blink::WebCryptoKeyUsageEncrypt,
84 &key);
86 if (status.IsError())
87 EXPECT_EQ(blink::WebCryptoErrorTypeNotSupported, status.error_type());
88 return status.IsSuccess();
91 bool SupportsRsaOaep() {
92 #if defined(USE_OPENSSL)
93 return true;
94 #else
95 crypto::EnsureNSSInit();
96 // TODO(eroman): Exclude version test for OS_CHROMEOS
97 #if defined(USE_NSS)
98 if (!NSS_VersionCheck("3.16.2"))
99 return false;
100 #endif
101 crypto::ScopedPK11Slot slot(PK11_GetInternalKeySlot());
102 return !!PK11_DoesMechanism(slot.get(), CKM_RSA_PKCS_OAEP);
103 #endif
106 bool SupportsRsaPrivateKeyImport() {
107 // TODO(eroman): Exclude version test for OS_CHROMEOS
108 #if defined(USE_NSS)
109 crypto::EnsureNSSInit();
110 if (!NSS_VersionCheck("3.16.2")) {
111 LOG(WARNING) << "RSA key import is not supported by this version of NSS. "
112 "Skipping some tests";
113 return false;
115 #endif
116 return true;
119 blink::WebCryptoAlgorithm CreateRsaHashedKeyGenAlgorithm(
120 blink::WebCryptoAlgorithmId algorithm_id,
121 const blink::WebCryptoAlgorithmId hash_id,
122 unsigned int modulus_length,
123 const std::vector<uint8_t>& public_exponent) {
124 DCHECK(blink::WebCryptoAlgorithm::isHash(hash_id));
125 return blink::WebCryptoAlgorithm::adoptParamsAndCreate(
126 algorithm_id,
127 new blink::WebCryptoRsaHashedKeyGenParams(
128 CreateAlgorithm(hash_id),
129 modulus_length,
130 vector_as_array(&public_exponent),
131 public_exponent.size()));
134 std::vector<uint8_t> Corrupted(const std::vector<uint8_t>& input) {
135 std::vector<uint8_t> corrupted_data(input);
136 if (corrupted_data.empty())
137 corrupted_data.push_back(0);
138 corrupted_data[corrupted_data.size() / 2] ^= 0x01;
139 return corrupted_data;
142 std::vector<uint8_t> HexStringToBytes(const std::string& hex) {
143 std::vector<uint8_t> bytes;
144 base::HexStringToBytes(hex, &bytes);
145 return bytes;
148 std::vector<uint8_t> MakeJsonVector(const std::string& json_string) {
149 return std::vector<uint8_t>(json_string.begin(), json_string.end());
152 std::vector<uint8_t> MakeJsonVector(const base::DictionaryValue& dict) {
153 std::string json;
154 base::JSONWriter::Write(&dict, &json);
155 return MakeJsonVector(json);
158 ::testing::AssertionResult ReadJsonTestFile(const char* test_file_name,
159 scoped_ptr<base::Value>* value) {
160 base::FilePath test_data_dir;
161 if (!PathService::Get(DIR_TEST_DATA, &test_data_dir))
162 return ::testing::AssertionFailure() << "Couldn't retrieve test dir";
164 base::FilePath file_path =
165 test_data_dir.AppendASCII("webcrypto").AppendASCII(test_file_name);
167 std::string file_contents;
168 if (!base::ReadFileToString(file_path, &file_contents)) {
169 return ::testing::AssertionFailure()
170 << "Couldn't read test file: " << file_path.value();
173 // Strip C++ style comments out of the "json" file, otherwise it cannot be
174 // parsed.
175 re2::RE2::GlobalReplace(&file_contents, re2::RE2("\\s*//.*"), "");
177 // Parse the JSON to a dictionary.
178 value->reset(base::JSONReader::Read(file_contents));
179 if (!value->get()) {
180 return ::testing::AssertionFailure()
181 << "Couldn't parse test file JSON: " << file_path.value();
184 return ::testing::AssertionSuccess();
187 ::testing::AssertionResult ReadJsonTestFileToList(
188 const char* test_file_name,
189 scoped_ptr<base::ListValue>* list) {
190 // Read the JSON.
191 scoped_ptr<base::Value> json;
192 ::testing::AssertionResult result = ReadJsonTestFile(test_file_name, &json);
193 if (!result)
194 return result;
196 // Cast to an ListValue.
197 base::ListValue* list_value = NULL;
198 if (!json->GetAsList(&list_value) || !list_value)
199 return ::testing::AssertionFailure() << "The JSON was not a list";
201 list->reset(list_value);
202 ignore_result(json.release());
204 return ::testing::AssertionSuccess();
207 ::testing::AssertionResult ReadJsonTestFileToDictionary(
208 const char* test_file_name,
209 scoped_ptr<base::DictionaryValue>* dict) {
210 // Read the JSON.
211 scoped_ptr<base::Value> json;
212 ::testing::AssertionResult result = ReadJsonTestFile(test_file_name, &json);
213 if (!result)
214 return result;
216 // Cast to an DictionaryValue.
217 base::DictionaryValue* dict_value = NULL;
218 if (!json->GetAsDictionary(&dict_value) || !dict_value)
219 return ::testing::AssertionFailure() << "The JSON was not a dictionary";
221 dict->reset(dict_value);
222 ignore_result(json.release());
224 return ::testing::AssertionSuccess();
227 std::vector<uint8_t> GetBytesFromHexString(const base::DictionaryValue* dict,
228 const std::string& property_name) {
229 std::string hex_string;
230 if (!dict->GetString(property_name, &hex_string)) {
231 EXPECT_TRUE(false) << "Couldn't get string property: " << property_name;
232 return std::vector<uint8_t>();
235 return HexStringToBytes(hex_string);
238 blink::WebCryptoAlgorithm GetDigestAlgorithm(const base::DictionaryValue* dict,
239 const char* property_name) {
240 std::string algorithm_name;
241 if (!dict->GetString(property_name, &algorithm_name)) {
242 EXPECT_TRUE(false) << "Couldn't get string property: " << property_name;
243 return blink::WebCryptoAlgorithm::createNull();
246 struct {
247 const char* name;
248 blink::WebCryptoAlgorithmId id;
249 } kDigestNameToId[] = {
250 {"sha-1", blink::WebCryptoAlgorithmIdSha1},
251 {"sha-256", blink::WebCryptoAlgorithmIdSha256},
252 {"sha-384", blink::WebCryptoAlgorithmIdSha384},
253 {"sha-512", blink::WebCryptoAlgorithmIdSha512},
256 for (size_t i = 0; i < arraysize(kDigestNameToId); ++i) {
257 if (kDigestNameToId[i].name == algorithm_name)
258 return CreateAlgorithm(kDigestNameToId[i].id);
261 return blink::WebCryptoAlgorithm::createNull();
264 // Creates a comparator for |bufs| which operates on indices rather than values.
265 class CompareUsingIndex {
266 public:
267 explicit CompareUsingIndex(const std::vector<std::vector<uint8_t> >* bufs)
268 : bufs_(bufs) {}
270 bool operator()(size_t i1, size_t i2) { return (*bufs_)[i1] < (*bufs_)[i2]; }
272 private:
273 const std::vector<std::vector<uint8_t> >* bufs_;
276 bool CopiesExist(const std::vector<std::vector<uint8_t> >& bufs) {
277 // Sort the indices of |bufs| into a separate vector. This reduces the amount
278 // of data copied versus sorting |bufs| directly.
279 std::vector<size_t> sorted_indices(bufs.size());
280 for (size_t i = 0; i < sorted_indices.size(); ++i)
281 sorted_indices[i] = i;
282 std::sort(
283 sorted_indices.begin(), sorted_indices.end(), CompareUsingIndex(&bufs));
285 // Scan for adjacent duplicates.
286 for (size_t i = 1; i < sorted_indices.size(); ++i) {
287 if (bufs[sorted_indices[i]] == bufs[sorted_indices[i - 1]])
288 return true;
290 return false;
293 blink::WebCryptoAlgorithm CreateAesKeyGenAlgorithm(
294 blink::WebCryptoAlgorithmId aes_alg_id,
295 unsigned short length) {
296 return blink::WebCryptoAlgorithm::adoptParamsAndCreate(
297 aes_alg_id, new blink::WebCryptoAesKeyGenParams(length));
300 // The following key pair is comprised of the SPKI (public key) and PKCS#8
301 // (private key) representations of the key pair provided in Example 1 of the
302 // NIST test vectors at
303 // ftp://ftp.rsa.com/pub/rsalabs/tmp/pkcs1v15sign-vectors.txt
304 const unsigned int kModulusLengthBits = 1024;
305 const char* const kPublicKeySpkiDerHex =
306 "30819f300d06092a864886f70d010101050003818d0030818902818100a5"
307 "6e4a0e701017589a5187dc7ea841d156f2ec0e36ad52a44dfeb1e61f7ad9"
308 "91d8c51056ffedb162b4c0f283a12a88a394dff526ab7291cbb307ceabfc"
309 "e0b1dfd5cd9508096d5b2b8b6df5d671ef6377c0921cb23c270a70e2598e"
310 "6ff89d19f105acc2d3f0cb35f29280e1386b6f64c4ef22e1e1f20d0ce8cf"
311 "fb2249bd9a21370203010001";
312 const char* const kPrivateKeyPkcs8DerHex =
313 "30820275020100300d06092a864886f70d01010105000482025f3082025b"
314 "02010002818100a56e4a0e701017589a5187dc7ea841d156f2ec0e36ad52"
315 "a44dfeb1e61f7ad991d8c51056ffedb162b4c0f283a12a88a394dff526ab"
316 "7291cbb307ceabfce0b1dfd5cd9508096d5b2b8b6df5d671ef6377c0921c"
317 "b23c270a70e2598e6ff89d19f105acc2d3f0cb35f29280e1386b6f64c4ef"
318 "22e1e1f20d0ce8cffb2249bd9a2137020301000102818033a5042a90b27d"
319 "4f5451ca9bbbd0b44771a101af884340aef9885f2a4bbe92e894a724ac3c"
320 "568c8f97853ad07c0266c8c6a3ca0929f1e8f11231884429fc4d9ae55fee"
321 "896a10ce707c3ed7e734e44727a39574501a532683109c2abacaba283c31"
322 "b4bd2f53c3ee37e352cee34f9e503bd80c0622ad79c6dcee883547c6a3b3"
323 "25024100e7e8942720a877517273a356053ea2a1bc0c94aa72d55c6e8629"
324 "6b2dfc967948c0a72cbccca7eacb35706e09a1df55a1535bd9b3cc34160b"
325 "3b6dcd3eda8e6443024100b69dca1cf7d4d7ec81e75b90fcca874abcde12"
326 "3fd2700180aa90479b6e48de8d67ed24f9f19d85ba275874f542cd20dc72"
327 "3e6963364a1f9425452b269a6799fd024028fa13938655be1f8a159cbaca"
328 "5a72ea190c30089e19cd274a556f36c4f6e19f554b34c077790427bbdd8d"
329 "d3ede2448328f385d81b30e8e43b2fffa02786197902401a8b38f398fa71"
330 "2049898d7fb79ee0a77668791299cdfa09efc0e507acb21ed74301ef5bfd"
331 "48be455eaeb6e1678255827580a8e4e8e14151d1510a82a3f2e729024027"
332 "156aba4126d24a81f3a528cbfb27f56886f840a9f6e86e17a44b94fe9319"
333 "584b8e22fdde1e5a2e3bd8aa5ba8d8584194eb2190acf832b847f13a3d24"
334 "a79f4d";
335 // The modulus and exponent (in hex) of kPublicKeySpkiDerHex
336 const char* const kPublicKeyModulusHex =
337 "A56E4A0E701017589A5187DC7EA841D156F2EC0E36AD52A44DFEB1E61F7AD991D8C51056"
338 "FFEDB162B4C0F283A12A88A394DFF526AB7291CBB307CEABFCE0B1DFD5CD9508096D5B2B"
339 "8B6DF5D671EF6377C0921CB23C270A70E2598E6FF89D19F105ACC2D3F0CB35F29280E138"
340 "6B6F64C4EF22E1E1F20D0CE8CFFB2249BD9A2137";
341 const char* const kPublicKeyExponentHex = "010001";
343 blink::WebCryptoKey ImportSecretKeyFromRaw(
344 const std::vector<uint8_t>& key_raw,
345 const blink::WebCryptoAlgorithm& algorithm,
346 blink::WebCryptoKeyUsageMask usage) {
347 blink::WebCryptoKey key;
348 bool extractable = true;
349 EXPECT_EQ(Status::Success(),
350 ImportKey(blink::WebCryptoKeyFormatRaw,
351 CryptoData(key_raw),
352 algorithm,
353 extractable,
354 usage,
355 &key));
357 EXPECT_FALSE(key.isNull());
358 EXPECT_TRUE(key.handle());
359 EXPECT_EQ(blink::WebCryptoKeyTypeSecret, key.type());
360 EXPECT_EQ(algorithm.id(), key.algorithm().id());
361 EXPECT_EQ(extractable, key.extractable());
362 EXPECT_EQ(usage, key.usages());
363 return key;
366 void ImportRsaKeyPair(const std::vector<uint8_t>& spki_der,
367 const std::vector<uint8_t>& pkcs8_der,
368 const blink::WebCryptoAlgorithm& algorithm,
369 bool extractable,
370 blink::WebCryptoKeyUsageMask public_key_usages,
371 blink::WebCryptoKeyUsageMask private_key_usages,
372 blink::WebCryptoKey* public_key,
373 blink::WebCryptoKey* private_key) {
374 ASSERT_EQ(Status::Success(),
375 ImportKey(blink::WebCryptoKeyFormatSpki,
376 CryptoData(spki_der),
377 algorithm,
378 true,
379 public_key_usages,
380 public_key));
381 EXPECT_FALSE(public_key->isNull());
382 EXPECT_TRUE(public_key->handle());
383 EXPECT_EQ(blink::WebCryptoKeyTypePublic, public_key->type());
384 EXPECT_EQ(algorithm.id(), public_key->algorithm().id());
385 EXPECT_TRUE(public_key->extractable());
386 EXPECT_EQ(public_key_usages, public_key->usages());
388 ASSERT_EQ(Status::Success(),
389 ImportKey(blink::WebCryptoKeyFormatPkcs8,
390 CryptoData(pkcs8_der),
391 algorithm,
392 extractable,
393 private_key_usages,
394 private_key));
395 EXPECT_FALSE(private_key->isNull());
396 EXPECT_TRUE(private_key->handle());
397 EXPECT_EQ(blink::WebCryptoKeyTypePrivate, private_key->type());
398 EXPECT_EQ(algorithm.id(), private_key->algorithm().id());
399 EXPECT_EQ(extractable, private_key->extractable());
400 EXPECT_EQ(private_key_usages, private_key->usages());
403 Status ImportKeyJwkFromDict(const base::DictionaryValue& dict,
404 const blink::WebCryptoAlgorithm& algorithm,
405 bool extractable,
406 blink::WebCryptoKeyUsageMask usages,
407 blink::WebCryptoKey* key) {
408 return ImportKey(blink::WebCryptoKeyFormatJwk,
409 CryptoData(MakeJsonVector(dict)),
410 algorithm,
411 extractable,
412 usages,
413 key);
416 scoped_ptr<base::DictionaryValue> GetJwkDictionary(
417 const std::vector<uint8_t>& json) {
418 base::StringPiece json_string(
419 reinterpret_cast<const char*>(vector_as_array(&json)), json.size());
420 base::Value* value = base::JSONReader::Read(json_string);
421 EXPECT_TRUE(value);
422 base::DictionaryValue* dict_value = NULL;
423 value->GetAsDictionary(&dict_value);
424 return scoped_ptr<base::DictionaryValue>(dict_value);
427 // Verifies the input dictionary contains the expected values. Exact matches are
428 // required on the fields examined.
429 ::testing::AssertionResult VerifyJwk(
430 const scoped_ptr<base::DictionaryValue>& dict,
431 const std::string& kty_expected,
432 const std::string& alg_expected,
433 blink::WebCryptoKeyUsageMask use_mask_expected) {
434 // ---- kty
435 std::string value_string;
436 if (!dict->GetString("kty", &value_string))
437 return ::testing::AssertionFailure() << "Missing 'kty'";
438 if (value_string != kty_expected)
439 return ::testing::AssertionFailure() << "Expected 'kty' to be "
440 << kty_expected << "but found "
441 << value_string;
443 // ---- alg
444 if (!dict->GetString("alg", &value_string))
445 return ::testing::AssertionFailure() << "Missing 'alg'";
446 if (value_string != alg_expected)
447 return ::testing::AssertionFailure() << "Expected 'alg' to be "
448 << alg_expected << " but found "
449 << value_string;
451 // ---- ext
452 // always expect ext == true in this case
453 bool ext_value;
454 if (!dict->GetBoolean("ext", &ext_value))
455 return ::testing::AssertionFailure() << "Missing 'ext'";
456 if (!ext_value)
457 return ::testing::AssertionFailure()
458 << "Expected 'ext' to be true but found false";
460 // ---- key_ops
461 base::ListValue* key_ops;
462 if (!dict->GetList("key_ops", &key_ops))
463 return ::testing::AssertionFailure() << "Missing 'key_ops'";
464 blink::WebCryptoKeyUsageMask key_ops_mask = 0;
465 Status status = GetWebCryptoUsagesFromJwkKeyOps(key_ops, &key_ops_mask);
466 if (status.IsError())
467 return ::testing::AssertionFailure() << "Failure extracting 'key_ops'";
468 if (key_ops_mask != use_mask_expected)
469 return ::testing::AssertionFailure()
470 << "Expected 'key_ops' mask to be " << use_mask_expected
471 << " but found " << key_ops_mask << " (" << value_string << ")";
473 return ::testing::AssertionSuccess();
476 ::testing::AssertionResult VerifySecretJwk(
477 const std::vector<uint8_t>& json,
478 const std::string& alg_expected,
479 const std::string& k_expected_hex,
480 blink::WebCryptoKeyUsageMask use_mask_expected) {
481 scoped_ptr<base::DictionaryValue> dict = GetJwkDictionary(json);
482 if (!dict.get() || dict->empty())
483 return ::testing::AssertionFailure() << "JSON parsing failed";
485 // ---- k
486 std::string value_string;
487 if (!dict->GetString("k", &value_string))
488 return ::testing::AssertionFailure() << "Missing 'k'";
489 std::string k_value;
490 if (!Base64DecodeUrlSafe(value_string, &k_value))
491 return ::testing::AssertionFailure() << "Base64DecodeUrlSafe(k) failed";
492 if (!LowerCaseEqualsASCII(base::HexEncode(k_value.data(), k_value.size()),
493 k_expected_hex.c_str())) {
494 return ::testing::AssertionFailure() << "Expected 'k' to be "
495 << k_expected_hex
496 << " but found something different";
499 return VerifyJwk(dict, "oct", alg_expected, use_mask_expected);
502 ::testing::AssertionResult VerifyPublicJwk(
503 const std::vector<uint8_t>& json,
504 const std::string& alg_expected,
505 const std::string& n_expected_hex,
506 const std::string& e_expected_hex,
507 blink::WebCryptoKeyUsageMask use_mask_expected) {
508 scoped_ptr<base::DictionaryValue> dict = GetJwkDictionary(json);
509 if (!dict.get() || dict->empty())
510 return ::testing::AssertionFailure() << "JSON parsing failed";
512 // ---- n
513 std::string value_string;
514 if (!dict->GetString("n", &value_string))
515 return ::testing::AssertionFailure() << "Missing 'n'";
516 std::string n_value;
517 if (!Base64DecodeUrlSafe(value_string, &n_value))
518 return ::testing::AssertionFailure() << "Base64DecodeUrlSafe(n) failed";
519 if (base::HexEncode(n_value.data(), n_value.size()) != n_expected_hex) {
520 return ::testing::AssertionFailure() << "'n' does not match the expected "
521 "value";
523 // TODO(padolph): LowerCaseEqualsASCII() does not work for above!
525 // ---- e
526 if (!dict->GetString("e", &value_string))
527 return ::testing::AssertionFailure() << "Missing 'e'";
528 std::string e_value;
529 if (!Base64DecodeUrlSafe(value_string, &e_value))
530 return ::testing::AssertionFailure() << "Base64DecodeUrlSafe(e) failed";
531 if (!LowerCaseEqualsASCII(base::HexEncode(e_value.data(), e_value.size()),
532 e_expected_hex.c_str())) {
533 return ::testing::AssertionFailure() << "Expected 'e' to be "
534 << e_expected_hex
535 << " but found something different";
538 return VerifyJwk(dict, "RSA", alg_expected, use_mask_expected);
541 void ImportExportJwkSymmetricKey(
542 int key_len_bits,
543 const blink::WebCryptoAlgorithm& import_algorithm,
544 blink::WebCryptoKeyUsageMask usages,
545 const std::string& jwk_alg) {
546 std::vector<uint8_t> json;
547 std::string key_hex;
549 // Hardcoded pseudo-random bytes to use for keys of different lengths.
550 switch (key_len_bits) {
551 case 128:
552 key_hex = "3f1e7cd4f6f8543f6b1e16002e688623";
553 break;
554 case 256:
555 key_hex =
556 "bd08286b81a74783fd1ccf46b7e05af84ee25ae021210074159e0c4d9d907692";
557 break;
558 case 384:
559 key_hex =
560 "a22c5441c8b185602283d64c7221de1d0951e706bfc09539435ec0e0ed614e1d40"
561 "6623f2b31d31819fec30993380dd82";
562 break;
563 case 512:
564 key_hex =
565 "5834f639000d4cf82de124fbfd26fb88d463e99f839a76ba41ac88967c80a3f61e"
566 "1239a452e573dba0750e988152988576efd75b8d0229b7aca2ada2afd392ee";
567 break;
568 default:
569 FAIL() << "Unexpected key_len_bits" << key_len_bits;
572 // Import a raw key.
573 blink::WebCryptoKey key = ImportSecretKeyFromRaw(
574 HexStringToBytes(key_hex), import_algorithm, usages);
576 // Export the key in JWK format and validate.
577 ASSERT_EQ(Status::Success(),
578 ExportKey(blink::WebCryptoKeyFormatJwk, key, &json));
579 EXPECT_TRUE(VerifySecretJwk(json, jwk_alg, key_hex, usages));
581 // Import the JWK-formatted key.
582 ASSERT_EQ(Status::Success(),
583 ImportKey(blink::WebCryptoKeyFormatJwk,
584 CryptoData(json),
585 import_algorithm,
586 true,
587 usages,
588 &key));
589 EXPECT_TRUE(key.handle());
590 EXPECT_EQ(blink::WebCryptoKeyTypeSecret, key.type());
591 EXPECT_EQ(import_algorithm.id(), key.algorithm().id());
592 EXPECT_EQ(true, key.extractable());
593 EXPECT_EQ(usages, key.usages());
595 // Export the key in raw format and compare to the original.
596 std::vector<uint8_t> key_raw_out;
597 ASSERT_EQ(Status::Success(),
598 ExportKey(blink::WebCryptoKeyFormatRaw, key, &key_raw_out));
599 EXPECT_BYTES_EQ_HEX(key_hex, key_raw_out);
602 Status GenerateSecretKey(const blink::WebCryptoAlgorithm& algorithm,
603 bool extractable,
604 blink::WebCryptoKeyUsageMask usages,
605 blink::WebCryptoKey* key) {
606 GenerateKeyResult result;
607 Status status = GenerateKey(algorithm, extractable, usages, &result);
608 if (status.IsError())
609 return status;
611 if (result.type() != GenerateKeyResult::TYPE_SECRET_KEY)
612 return Status::ErrorUnexpected();
614 *key = result.secret_key();
616 return Status::Success();
619 Status GenerateKeyPair(const blink::WebCryptoAlgorithm& algorithm,
620 bool extractable,
621 blink::WebCryptoKeyUsageMask usages,
622 blink::WebCryptoKey* public_key,
623 blink::WebCryptoKey* private_key) {
624 GenerateKeyResult result;
625 Status status = GenerateKey(algorithm, extractable, usages, &result);
626 if (status.IsError())
627 return status;
629 if (result.type() != GenerateKeyResult::TYPE_PUBLIC_PRIVATE_KEY_PAIR)
630 return Status::ErrorUnexpected();
632 *public_key = result.public_key();
633 *private_key = result.private_key();
635 return Status::Success();
638 } // namespace webcrypto
640 } // namesapce content