Merge Chromium + Blink git repositories
[chromium-blink-merge.git] / components / webcrypto / algorithms / test_helpers.cc
blobb096ac3786d6d606b2325d4c458ad8db9e28bcfc
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 "components/webcrypto/algorithms/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 "components/test_runner/test_common.h"
19 #include "components/webcrypto/algorithm_dispatch.h"
20 #include "components/webcrypto/crypto_data.h"
21 #include "components/webcrypto/generate_key_result.h"
22 #include "components/webcrypto/jwk.h"
23 #include "components/webcrypto/status.h"
24 #include "components/webcrypto/webcrypto_util.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 namespace webcrypto {
31 // static
32 void WebCryptoTestBase::SetUpTestCase() {
33 test_runner::EnsureBlinkInitialized();
36 void PrintTo(const Status& status, ::std::ostream* os) {
37 *os << StatusToString(status);
40 bool operator==(const Status& a, const Status& b) {
41 if (a.IsSuccess() != b.IsSuccess())
42 return false;
43 if (a.IsSuccess())
44 return true;
45 return a.error_type() == b.error_type() &&
46 a.error_details() == b.error_details();
49 bool operator!=(const Status& a, const Status& b) {
50 return !(a == b);
53 void PrintTo(const CryptoData& data, ::std::ostream* os) {
54 *os << "[" << base::HexEncode(data.bytes(), data.byte_length()) << "]";
57 bool operator==(const CryptoData& a, const CryptoData& b) {
58 return a.byte_length() == b.byte_length() &&
59 memcmp(a.bytes(), b.bytes(), a.byte_length()) == 0;
62 bool operator!=(const CryptoData& a, const CryptoData& b) {
63 return !(a == b);
66 static std::string ErrorTypeToString(blink::WebCryptoErrorType type) {
67 switch (type) {
68 case blink::WebCryptoErrorTypeNotSupported:
69 return "NotSupported";
70 case blink::WebCryptoErrorTypeType:
71 return "TypeError";
72 case blink::WebCryptoErrorTypeData:
73 return "DataError";
74 case blink::WebCryptoErrorTypeSyntax:
75 return "SyntaxError";
76 case blink::WebCryptoErrorTypeOperation:
77 return "OperationError";
78 case blink::WebCryptoErrorTypeInvalidAccess:
79 return "InvalidAccess";
80 default:
81 return "?";
85 std::string StatusToString(const Status& status) {
86 if (status.IsSuccess())
87 return "Success";
89 std::string result = ErrorTypeToString(status.error_type());
90 if (!status.error_details().empty())
91 result += ": " + status.error_details();
92 return result;
95 blink::WebCryptoAlgorithm CreateRsaHashedKeyGenAlgorithm(
96 blink::WebCryptoAlgorithmId algorithm_id,
97 const blink::WebCryptoAlgorithmId hash_id,
98 unsigned int modulus_length,
99 const std::vector<uint8_t>& public_exponent) {
100 DCHECK(blink::WebCryptoAlgorithm::isHash(hash_id));
101 return blink::WebCryptoAlgorithm::adoptParamsAndCreate(
102 algorithm_id, new blink::WebCryptoRsaHashedKeyGenParams(
103 CreateAlgorithm(hash_id), modulus_length,
104 vector_as_array(&public_exponent),
105 static_cast<unsigned int>(public_exponent.size())));
108 std::vector<uint8_t> Corrupted(const std::vector<uint8_t>& input) {
109 std::vector<uint8_t> corrupted_data(input);
110 if (corrupted_data.empty())
111 corrupted_data.push_back(0);
112 corrupted_data[corrupted_data.size() / 2] ^= 0x01;
113 return corrupted_data;
116 std::vector<uint8_t> HexStringToBytes(const std::string& hex) {
117 std::vector<uint8_t> bytes;
118 base::HexStringToBytes(hex, &bytes);
119 return bytes;
122 std::vector<uint8_t> MakeJsonVector(const std::string& json_string) {
123 return std::vector<uint8_t>(json_string.begin(), json_string.end());
126 std::vector<uint8_t> MakeJsonVector(const base::DictionaryValue& dict) {
127 std::string json;
128 base::JSONWriter::Write(dict, &json);
129 return MakeJsonVector(json);
132 ::testing::AssertionResult ReadJsonTestFile(const char* test_file_name,
133 scoped_ptr<base::Value>* value) {
134 base::FilePath test_data_dir;
135 if (!PathService::Get(base::DIR_SOURCE_ROOT, &test_data_dir))
136 return ::testing::AssertionFailure() << "Couldn't retrieve test dir";
138 base::FilePath file_path = test_data_dir.AppendASCII("components")
139 .AppendASCII("test")
140 .AppendASCII("data")
141 .AppendASCII("webcrypto")
142 .AppendASCII(test_file_name);
144 std::string file_contents;
145 if (!base::ReadFileToString(file_path, &file_contents)) {
146 return ::testing::AssertionFailure()
147 << "Couldn't read test file: " << file_path.value();
150 // Strip C++ style comments out of the "json" file, otherwise it cannot be
151 // parsed.
152 re2::RE2::GlobalReplace(&file_contents, re2::RE2("\\s*//.*"), "");
154 // Parse the JSON to a dictionary.
155 *value = base::JSONReader::Read(file_contents);
156 if (!value->get()) {
157 return ::testing::AssertionFailure()
158 << "Couldn't parse test file JSON: " << file_path.value();
161 return ::testing::AssertionSuccess();
164 ::testing::AssertionResult ReadJsonTestFileToList(
165 const char* test_file_name,
166 scoped_ptr<base::ListValue>* list) {
167 // Read the JSON.
168 scoped_ptr<base::Value> json;
169 ::testing::AssertionResult result = ReadJsonTestFile(test_file_name, &json);
170 if (!result)
171 return result;
173 // Cast to an ListValue.
174 base::ListValue* list_value = NULL;
175 if (!json->GetAsList(&list_value) || !list_value)
176 return ::testing::AssertionFailure() << "The JSON was not a list";
178 list->reset(list_value);
179 ignore_result(json.release());
181 return ::testing::AssertionSuccess();
184 ::testing::AssertionResult ReadJsonTestFileToDictionary(
185 const char* test_file_name,
186 scoped_ptr<base::DictionaryValue>* dict) {
187 // Read the JSON.
188 scoped_ptr<base::Value> json;
189 ::testing::AssertionResult result = ReadJsonTestFile(test_file_name, &json);
190 if (!result)
191 return result;
193 // Cast to an DictionaryValue.
194 base::DictionaryValue* dict_value = NULL;
195 if (!json->GetAsDictionary(&dict_value) || !dict_value)
196 return ::testing::AssertionFailure() << "The JSON was not a dictionary";
198 dict->reset(dict_value);
199 ignore_result(json.release());
201 return ::testing::AssertionSuccess();
204 std::vector<uint8_t> GetBytesFromHexString(const base::DictionaryValue* dict,
205 const std::string& property_name) {
206 std::string hex_string;
207 if (!dict->GetString(property_name, &hex_string)) {
208 ADD_FAILURE() << "Couldn't get string property: " << property_name;
209 return std::vector<uint8_t>();
212 return HexStringToBytes(hex_string);
215 blink::WebCryptoAlgorithm GetDigestAlgorithm(const base::DictionaryValue* dict,
216 const char* property_name) {
217 std::string algorithm_name;
218 if (!dict->GetString(property_name, &algorithm_name)) {
219 ADD_FAILURE() << "Couldn't get string property: " << property_name;
220 return blink::WebCryptoAlgorithm::createNull();
223 struct {
224 const char* name;
225 blink::WebCryptoAlgorithmId id;
226 } kDigestNameToId[] = {
227 {"sha-1", blink::WebCryptoAlgorithmIdSha1},
228 {"sha-256", blink::WebCryptoAlgorithmIdSha256},
229 {"sha-384", blink::WebCryptoAlgorithmIdSha384},
230 {"sha-512", blink::WebCryptoAlgorithmIdSha512},
233 for (size_t i = 0; i < arraysize(kDigestNameToId); ++i) {
234 if (kDigestNameToId[i].name == algorithm_name)
235 return CreateAlgorithm(kDigestNameToId[i].id);
238 return blink::WebCryptoAlgorithm::createNull();
241 // Creates a comparator for |bufs| which operates on indices rather than values.
242 class CompareUsingIndex {
243 public:
244 explicit CompareUsingIndex(const std::vector<std::vector<uint8_t>>* bufs)
245 : bufs_(bufs) {}
247 bool operator()(size_t i1, size_t i2) { return (*bufs_)[i1] < (*bufs_)[i2]; }
249 private:
250 const std::vector<std::vector<uint8_t>>* bufs_;
253 bool CopiesExist(const std::vector<std::vector<uint8_t>>& bufs) {
254 // Sort the indices of |bufs| into a separate vector. This reduces the amount
255 // of data copied versus sorting |bufs| directly.
256 std::vector<size_t> sorted_indices(bufs.size());
257 for (size_t i = 0; i < sorted_indices.size(); ++i)
258 sorted_indices[i] = i;
259 std::sort(sorted_indices.begin(), sorted_indices.end(),
260 CompareUsingIndex(&bufs));
262 // Scan for adjacent duplicates.
263 for (size_t i = 1; i < sorted_indices.size(); ++i) {
264 if (bufs[sorted_indices[i]] == bufs[sorted_indices[i - 1]])
265 return true;
267 return false;
270 blink::WebCryptoAlgorithm CreateAesKeyGenAlgorithm(
271 blink::WebCryptoAlgorithmId aes_alg_id,
272 unsigned short length) {
273 return blink::WebCryptoAlgorithm::adoptParamsAndCreate(
274 aes_alg_id, new blink::WebCryptoAesKeyGenParams(length));
277 // The following key pair is comprised of the SPKI (public key) and PKCS#8
278 // (private key) representations of the key pair provided in Example 1 of the
279 // NIST test vectors at
280 // ftp://ftp.rsa.com/pub/rsalabs/tmp/pkcs1v15sign-vectors.txt
281 const unsigned int kModulusLengthBits = 1024;
282 const char* const kPublicKeySpkiDerHex =
283 "30819f300d06092a864886f70d010101050003818d0030818902818100a5"
284 "6e4a0e701017589a5187dc7ea841d156f2ec0e36ad52a44dfeb1e61f7ad9"
285 "91d8c51056ffedb162b4c0f283a12a88a394dff526ab7291cbb307ceabfc"
286 "e0b1dfd5cd9508096d5b2b8b6df5d671ef6377c0921cb23c270a70e2598e"
287 "6ff89d19f105acc2d3f0cb35f29280e1386b6f64c4ef22e1e1f20d0ce8cf"
288 "fb2249bd9a21370203010001";
289 const char* const kPrivateKeyPkcs8DerHex =
290 "30820275020100300d06092a864886f70d01010105000482025f3082025b"
291 "02010002818100a56e4a0e701017589a5187dc7ea841d156f2ec0e36ad52"
292 "a44dfeb1e61f7ad991d8c51056ffedb162b4c0f283a12a88a394dff526ab"
293 "7291cbb307ceabfce0b1dfd5cd9508096d5b2b8b6df5d671ef6377c0921c"
294 "b23c270a70e2598e6ff89d19f105acc2d3f0cb35f29280e1386b6f64c4ef"
295 "22e1e1f20d0ce8cffb2249bd9a2137020301000102818033a5042a90b27d"
296 "4f5451ca9bbbd0b44771a101af884340aef9885f2a4bbe92e894a724ac3c"
297 "568c8f97853ad07c0266c8c6a3ca0929f1e8f11231884429fc4d9ae55fee"
298 "896a10ce707c3ed7e734e44727a39574501a532683109c2abacaba283c31"
299 "b4bd2f53c3ee37e352cee34f9e503bd80c0622ad79c6dcee883547c6a3b3"
300 "25024100e7e8942720a877517273a356053ea2a1bc0c94aa72d55c6e8629"
301 "6b2dfc967948c0a72cbccca7eacb35706e09a1df55a1535bd9b3cc34160b"
302 "3b6dcd3eda8e6443024100b69dca1cf7d4d7ec81e75b90fcca874abcde12"
303 "3fd2700180aa90479b6e48de8d67ed24f9f19d85ba275874f542cd20dc72"
304 "3e6963364a1f9425452b269a6799fd024028fa13938655be1f8a159cbaca"
305 "5a72ea190c30089e19cd274a556f36c4f6e19f554b34c077790427bbdd8d"
306 "d3ede2448328f385d81b30e8e43b2fffa02786197902401a8b38f398fa71"
307 "2049898d7fb79ee0a77668791299cdfa09efc0e507acb21ed74301ef5bfd"
308 "48be455eaeb6e1678255827580a8e4e8e14151d1510a82a3f2e729024027"
309 "156aba4126d24a81f3a528cbfb27f56886f840a9f6e86e17a44b94fe9319"
310 "584b8e22fdde1e5a2e3bd8aa5ba8d8584194eb2190acf832b847f13a3d24"
311 "a79f4d";
312 // The modulus and exponent (in hex) of kPublicKeySpkiDerHex
313 const char* const kPublicKeyModulusHex =
314 "A56E4A0E701017589A5187DC7EA841D156F2EC0E36AD52A44DFEB1E61F7AD991D8C51056"
315 "FFEDB162B4C0F283A12A88A394DFF526AB7291CBB307CEABFCE0B1DFD5CD9508096D5B2B"
316 "8B6DF5D671EF6377C0921CB23C270A70E2598E6FF89D19F105ACC2D3F0CB35F29280E138"
317 "6B6F64C4EF22E1E1F20D0CE8CFFB2249BD9A2137";
318 const char* const kPublicKeyExponentHex = "010001";
320 blink::WebCryptoKey ImportSecretKeyFromRaw(
321 const std::vector<uint8_t>& key_raw,
322 const blink::WebCryptoAlgorithm& algorithm,
323 blink::WebCryptoKeyUsageMask usage) {
324 blink::WebCryptoKey key;
325 bool extractable = true;
326 EXPECT_EQ(Status::Success(),
327 ImportKey(blink::WebCryptoKeyFormatRaw, CryptoData(key_raw),
328 algorithm, extractable, usage, &key));
330 EXPECT_FALSE(key.isNull());
331 EXPECT_TRUE(key.handle());
332 EXPECT_EQ(blink::WebCryptoKeyTypeSecret, key.type());
333 EXPECT_EQ(algorithm.id(), key.algorithm().id());
334 EXPECT_EQ(extractable, key.extractable());
335 EXPECT_EQ(usage, key.usages());
336 return key;
339 void ImportRsaKeyPair(const std::vector<uint8_t>& spki_der,
340 const std::vector<uint8_t>& pkcs8_der,
341 const blink::WebCryptoAlgorithm& algorithm,
342 bool extractable,
343 blink::WebCryptoKeyUsageMask public_key_usages,
344 blink::WebCryptoKeyUsageMask private_key_usages,
345 blink::WebCryptoKey* public_key,
346 blink::WebCryptoKey* private_key) {
347 ASSERT_EQ(Status::Success(),
348 ImportKey(blink::WebCryptoKeyFormatSpki, CryptoData(spki_der),
349 algorithm, true, public_key_usages, public_key));
350 EXPECT_FALSE(public_key->isNull());
351 EXPECT_TRUE(public_key->handle());
352 EXPECT_EQ(blink::WebCryptoKeyTypePublic, public_key->type());
353 EXPECT_EQ(algorithm.id(), public_key->algorithm().id());
354 EXPECT_TRUE(public_key->extractable());
355 EXPECT_EQ(public_key_usages, public_key->usages());
357 ASSERT_EQ(Status::Success(),
358 ImportKey(blink::WebCryptoKeyFormatPkcs8, CryptoData(pkcs8_der),
359 algorithm, extractable, private_key_usages, private_key));
360 EXPECT_FALSE(private_key->isNull());
361 EXPECT_TRUE(private_key->handle());
362 EXPECT_EQ(blink::WebCryptoKeyTypePrivate, private_key->type());
363 EXPECT_EQ(algorithm.id(), private_key->algorithm().id());
364 EXPECT_EQ(extractable, private_key->extractable());
365 EXPECT_EQ(private_key_usages, private_key->usages());
368 Status ImportKeyJwkFromDict(const base::DictionaryValue& dict,
369 const blink::WebCryptoAlgorithm& algorithm,
370 bool extractable,
371 blink::WebCryptoKeyUsageMask usages,
372 blink::WebCryptoKey* key) {
373 return ImportKey(blink::WebCryptoKeyFormatJwk,
374 CryptoData(MakeJsonVector(dict)), algorithm, extractable,
375 usages, key);
378 scoped_ptr<base::DictionaryValue> GetJwkDictionary(
379 const std::vector<uint8_t>& json) {
380 base::StringPiece json_string(
381 reinterpret_cast<const char*>(vector_as_array(&json)), json.size());
382 scoped_ptr<base::Value> value = base::JSONReader::Read(json_string);
383 EXPECT_TRUE(value.get());
384 EXPECT_TRUE(value->IsType(base::Value::TYPE_DICTIONARY));
386 return scoped_ptr<base::DictionaryValue>(
387 static_cast<base::DictionaryValue*>(value.release()));
390 // Verifies the input dictionary contains the expected values. Exact matches are
391 // required on the fields examined.
392 ::testing::AssertionResult VerifyJwk(
393 const scoped_ptr<base::DictionaryValue>& dict,
394 const std::string& kty_expected,
395 const std::string& alg_expected,
396 blink::WebCryptoKeyUsageMask use_mask_expected) {
397 // ---- kty
398 std::string value_string;
399 if (!dict->GetString("kty", &value_string))
400 return ::testing::AssertionFailure() << "Missing 'kty'";
401 if (value_string != kty_expected)
402 return ::testing::AssertionFailure() << "Expected 'kty' to be "
403 << kty_expected << "but found "
404 << value_string;
406 // ---- alg
407 if (!dict->GetString("alg", &value_string))
408 return ::testing::AssertionFailure() << "Missing 'alg'";
409 if (value_string != alg_expected)
410 return ::testing::AssertionFailure() << "Expected 'alg' to be "
411 << alg_expected << " but found "
412 << value_string;
414 // ---- ext
415 // always expect ext == true in this case
416 bool ext_value;
417 if (!dict->GetBoolean("ext", &ext_value))
418 return ::testing::AssertionFailure() << "Missing 'ext'";
419 if (!ext_value)
420 return ::testing::AssertionFailure()
421 << "Expected 'ext' to be true but found false";
423 // ---- key_ops
424 base::ListValue* key_ops;
425 if (!dict->GetList("key_ops", &key_ops))
426 return ::testing::AssertionFailure() << "Missing 'key_ops'";
427 blink::WebCryptoKeyUsageMask key_ops_mask = 0;
428 Status status =
429 GetWebCryptoUsagesFromJwkKeyOpsForTest(key_ops, &key_ops_mask);
430 if (status.IsError())
431 return ::testing::AssertionFailure() << "Failure extracting 'key_ops'";
432 if (key_ops_mask != use_mask_expected)
433 return ::testing::AssertionFailure()
434 << "Expected 'key_ops' mask to be " << use_mask_expected
435 << " but found " << key_ops_mask << " (" << value_string << ")";
437 return ::testing::AssertionSuccess();
440 ::testing::AssertionResult VerifySecretJwk(
441 const std::vector<uint8_t>& json,
442 const std::string& alg_expected,
443 const std::string& k_expected_hex,
444 blink::WebCryptoKeyUsageMask use_mask_expected) {
445 scoped_ptr<base::DictionaryValue> dict = GetJwkDictionary(json);
446 if (!dict.get() || dict->empty())
447 return ::testing::AssertionFailure() << "JSON parsing failed";
449 // ---- k
450 std::string value_string;
451 if (!dict->GetString("k", &value_string))
452 return ::testing::AssertionFailure() << "Missing 'k'";
453 std::string k_value;
454 if (!Base64DecodeUrlSafe(value_string, &k_value))
455 return ::testing::AssertionFailure() << "Base64DecodeUrlSafe(k) failed";
456 if (!base::LowerCaseEqualsASCII(
457 base::HexEncode(k_value.data(), k_value.size()),
458 k_expected_hex.c_str())) {
459 return ::testing::AssertionFailure() << "Expected 'k' to be "
460 << k_expected_hex
461 << " but found something different";
464 return VerifyJwk(dict, "oct", alg_expected, use_mask_expected);
467 ::testing::AssertionResult VerifyPublicJwk(
468 const std::vector<uint8_t>& json,
469 const std::string& alg_expected,
470 const std::string& n_expected_hex,
471 const std::string& e_expected_hex,
472 blink::WebCryptoKeyUsageMask use_mask_expected) {
473 scoped_ptr<base::DictionaryValue> dict = GetJwkDictionary(json);
474 if (!dict.get() || dict->empty())
475 return ::testing::AssertionFailure() << "JSON parsing failed";
477 // ---- n
478 std::string value_string;
479 if (!dict->GetString("n", &value_string))
480 return ::testing::AssertionFailure() << "Missing 'n'";
481 std::string n_value;
482 if (!Base64DecodeUrlSafe(value_string, &n_value))
483 return ::testing::AssertionFailure() << "Base64DecodeUrlSafe(n) failed";
484 if (base::HexEncode(n_value.data(), n_value.size()) != n_expected_hex) {
485 return ::testing::AssertionFailure() << "'n' does not match the expected "
486 "value";
488 // TODO(padolph): LowerCaseEqualsASCII() does not work for above!
490 // ---- e
491 if (!dict->GetString("e", &value_string))
492 return ::testing::AssertionFailure() << "Missing 'e'";
493 std::string e_value;
494 if (!Base64DecodeUrlSafe(value_string, &e_value))
495 return ::testing::AssertionFailure() << "Base64DecodeUrlSafe(e) failed";
496 if (!base::LowerCaseEqualsASCII(
497 base::HexEncode(e_value.data(), e_value.size()),
498 e_expected_hex.c_str())) {
499 return ::testing::AssertionFailure() << "Expected 'e' to be "
500 << e_expected_hex
501 << " but found something different";
504 return VerifyJwk(dict, "RSA", alg_expected, use_mask_expected);
507 void ImportExportJwkSymmetricKey(
508 int key_len_bits,
509 const blink::WebCryptoAlgorithm& import_algorithm,
510 blink::WebCryptoKeyUsageMask usages,
511 const std::string& jwk_alg) {
512 std::vector<uint8_t> json;
513 std::string key_hex;
515 // Hardcoded pseudo-random bytes to use for keys of different lengths.
516 switch (key_len_bits) {
517 case 128:
518 key_hex = "3f1e7cd4f6f8543f6b1e16002e688623";
519 break;
520 case 256:
521 key_hex =
522 "bd08286b81a74783fd1ccf46b7e05af84ee25ae021210074159e0c4d9d907692";
523 break;
524 case 384:
525 key_hex =
526 "a22c5441c8b185602283d64c7221de1d0951e706bfc09539435ec0e0ed614e1d40"
527 "6623f2b31d31819fec30993380dd82";
528 break;
529 case 512:
530 key_hex =
531 "5834f639000d4cf82de124fbfd26fb88d463e99f839a76ba41ac88967c80a3f61e"
532 "1239a452e573dba0750e988152988576efd75b8d0229b7aca2ada2afd392ee";
533 break;
534 default:
535 FAIL() << "Unexpected key_len_bits" << key_len_bits;
538 // Import a raw key.
539 blink::WebCryptoKey key = ImportSecretKeyFromRaw(HexStringToBytes(key_hex),
540 import_algorithm, usages);
542 // Export the key in JWK format and validate.
543 ASSERT_EQ(Status::Success(),
544 ExportKey(blink::WebCryptoKeyFormatJwk, key, &json));
545 EXPECT_TRUE(VerifySecretJwk(json, jwk_alg, key_hex, usages));
547 // Import the JWK-formatted key.
548 ASSERT_EQ(Status::Success(),
549 ImportKey(blink::WebCryptoKeyFormatJwk, CryptoData(json),
550 import_algorithm, true, usages, &key));
551 EXPECT_TRUE(key.handle());
552 EXPECT_EQ(blink::WebCryptoKeyTypeSecret, key.type());
553 EXPECT_EQ(import_algorithm.id(), key.algorithm().id());
554 EXPECT_EQ(true, key.extractable());
555 EXPECT_EQ(usages, key.usages());
557 // Export the key in raw format and compare to the original.
558 std::vector<uint8_t> key_raw_out;
559 ASSERT_EQ(Status::Success(),
560 ExportKey(blink::WebCryptoKeyFormatRaw, key, &key_raw_out));
561 EXPECT_BYTES_EQ_HEX(key_hex, key_raw_out);
564 Status GenerateSecretKey(const blink::WebCryptoAlgorithm& algorithm,
565 bool extractable,
566 blink::WebCryptoKeyUsageMask usages,
567 blink::WebCryptoKey* key) {
568 GenerateKeyResult result;
569 Status status = GenerateKey(algorithm, extractable, usages, &result);
570 if (status.IsError())
571 return status;
573 if (result.type() != GenerateKeyResult::TYPE_SECRET_KEY)
574 return Status::ErrorUnexpected();
576 *key = result.secret_key();
578 return Status::Success();
581 Status GenerateKeyPair(const blink::WebCryptoAlgorithm& algorithm,
582 bool extractable,
583 blink::WebCryptoKeyUsageMask usages,
584 blink::WebCryptoKey* public_key,
585 blink::WebCryptoKey* private_key) {
586 GenerateKeyResult result;
587 Status status = GenerateKey(algorithm, extractable, usages, &result);
588 if (status.IsError())
589 return status;
591 if (result.type() != GenerateKeyResult::TYPE_PUBLIC_PRIVATE_KEY_PAIR)
592 return Status::ErrorUnexpected();
594 *public_key = result.public_key();
595 *private_key = result.private_key();
597 return Status::Success();
600 blink::WebCryptoKeyFormat GetKeyFormatFromJsonTestCase(
601 const base::DictionaryValue* test) {
602 std::string format;
603 EXPECT_TRUE(test->GetString("key_format", &format));
604 if (format == "jwk")
605 return blink::WebCryptoKeyFormatJwk;
606 else if (format == "pkcs8")
607 return blink::WebCryptoKeyFormatPkcs8;
608 else if (format == "spki")
609 return blink::WebCryptoKeyFormatSpki;
610 else if (format == "raw")
611 return blink::WebCryptoKeyFormatRaw;
613 ADD_FAILURE() << "Unrecognized key format: " << format;
614 return blink::WebCryptoKeyFormatRaw;
617 std::vector<uint8_t> GetKeyDataFromJsonTestCase(
618 const base::DictionaryValue* test,
619 blink::WebCryptoKeyFormat key_format) {
620 if (key_format == blink::WebCryptoKeyFormatJwk) {
621 const base::DictionaryValue* json;
622 EXPECT_TRUE(test->GetDictionary("key", &json));
623 return MakeJsonVector(*json);
625 return GetBytesFromHexString(test, "key");
628 blink::WebCryptoNamedCurve GetCurveNameFromDictionary(
629 const base::DictionaryValue* dict) {
630 std::string curve_str;
631 if (!dict->GetString("crv", &curve_str)) {
632 ADD_FAILURE() << "Missing crv parameter";
633 return blink::WebCryptoNamedCurveP384;
636 if (curve_str == "P-256")
637 return blink::WebCryptoNamedCurveP256;
638 if (curve_str == "P-384")
639 return blink::WebCryptoNamedCurveP384;
640 if (curve_str == "P-521")
641 return blink::WebCryptoNamedCurveP521;
642 else
643 ADD_FAILURE() << "Unrecognized curve name: " << curve_str;
645 return blink::WebCryptoNamedCurveP384;
648 blink::WebCryptoAlgorithm CreateHmacImportAlgorithm(
649 blink::WebCryptoAlgorithmId hash_id,
650 unsigned int length_bits) {
651 DCHECK(blink::WebCryptoAlgorithm::isHash(hash_id));
652 return blink::WebCryptoAlgorithm::adoptParamsAndCreate(
653 blink::WebCryptoAlgorithmIdHmac,
654 new blink::WebCryptoHmacImportParams(CreateAlgorithm(hash_id), true,
655 length_bits));
658 blink::WebCryptoAlgorithm CreateHmacImportAlgorithmNoLength(
659 blink::WebCryptoAlgorithmId hash_id) {
660 DCHECK(blink::WebCryptoAlgorithm::isHash(hash_id));
661 return blink::WebCryptoAlgorithm::adoptParamsAndCreate(
662 blink::WebCryptoAlgorithmIdHmac,
663 new blink::WebCryptoHmacImportParams(CreateAlgorithm(hash_id), false, 0));
666 } // namespace webcrypto