test_helpers.cc 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637
  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. #include "components/webcrypto/algorithms/test_helpers.h"
  5. #include <stddef.h>
  6. #include <algorithm>
  7. #include "base/base64url.h"
  8. #include "base/check.h"
  9. #include "base/files/file_util.h"
  10. #include "base/json/json_reader.h"
  11. #include "base/json/json_writer.h"
  12. #include "base/memory/raw_ptr.h"
  13. #include "base/path_service.h"
  14. #include "base/strings/string_number_conversions.h"
  15. #include "base/strings/string_util.h"
  16. #include "base/values.h"
  17. #include "components/webcrypto/algorithm_dispatch.h"
  18. #include "components/webcrypto/generate_key_result.h"
  19. #include "components/webcrypto/jwk.h"
  20. #include "components/webcrypto/status.h"
  21. #include "third_party/blink/public/platform/web_crypto_algorithm_params.h"
  22. #include "third_party/blink/public/platform/web_crypto_key_algorithm.h"
  23. #include "third_party/re2/src/re2/re2.h"
  24. namespace webcrypto {
  25. namespace {
  26. bool Base64DecodeUrlSafe(const std::string& input, std::string* output) {
  27. // The JSON web signature spec says that padding is omitted.
  28. // https://tools.ietf.org/html/draft-ietf-jose-json-web-signature-36#section-2
  29. return base::Base64UrlDecode(
  30. input, base::Base64UrlDecodePolicy::DISALLOW_PADDING, output);
  31. }
  32. absl::optional<base::Value> ReadJsonTestFile(const char* test_file_name) {
  33. base::FilePath test_data_dir;
  34. if (!base::PathService::Get(base::DIR_SOURCE_ROOT, &test_data_dir))
  35. return absl::nullopt;
  36. base::FilePath file_path = test_data_dir.AppendASCII("components")
  37. .AppendASCII("test")
  38. .AppendASCII("data")
  39. .AppendASCII("webcrypto")
  40. .AppendASCII(test_file_name);
  41. std::string file_contents;
  42. if (!base::ReadFileToString(file_path, &file_contents))
  43. return absl::nullopt;
  44. return base::JSONReader::Read(file_contents);
  45. }
  46. } // namespace
  47. // static
  48. void WebCryptoTestBase::SetUpTestCase() {}
  49. void PrintTo(const Status& status, ::std::ostream* os) {
  50. *os << StatusToString(status);
  51. }
  52. bool operator==(const Status& a, const Status& b) {
  53. if (a.IsSuccess() != b.IsSuccess())
  54. return false;
  55. if (a.IsSuccess())
  56. return true;
  57. return a.error_type() == b.error_type() &&
  58. a.error_details() == b.error_details();
  59. }
  60. bool operator!=(const Status& a, const Status& b) {
  61. return !(a == b);
  62. }
  63. static std::string ErrorTypeToString(blink::WebCryptoErrorType type) {
  64. switch (type) {
  65. case blink::kWebCryptoErrorTypeNotSupported:
  66. return "NotSupported";
  67. case blink::kWebCryptoErrorTypeType:
  68. return "TypeError";
  69. case blink::kWebCryptoErrorTypeData:
  70. return "DataError";
  71. case blink::kWebCryptoErrorTypeSyntax:
  72. return "SyntaxError";
  73. case blink::kWebCryptoErrorTypeOperation:
  74. return "OperationError";
  75. case blink::kWebCryptoErrorTypeInvalidAccess:
  76. return "InvalidAccess";
  77. default:
  78. return "?";
  79. }
  80. }
  81. std::string StatusToString(const Status& status) {
  82. if (status.IsSuccess())
  83. return "Success";
  84. std::string result = ErrorTypeToString(status.error_type());
  85. if (!status.error_details().empty())
  86. result += ": " + status.error_details();
  87. return result;
  88. }
  89. blink::WebCryptoAlgorithm CreateRsaHashedKeyGenAlgorithm(
  90. blink::WebCryptoAlgorithmId algorithm_id,
  91. const blink::WebCryptoAlgorithmId hash_id,
  92. unsigned int modulus_length,
  93. const std::vector<uint8_t>& public_exponent) {
  94. DCHECK(blink::WebCryptoAlgorithm::IsHash(hash_id));
  95. return blink::WebCryptoAlgorithm::AdoptParamsAndCreate(
  96. algorithm_id,
  97. new blink::WebCryptoRsaHashedKeyGenParams(
  98. CreateAlgorithm(hash_id), modulus_length, public_exponent));
  99. }
  100. std::vector<uint8_t> Corrupted(const std::vector<uint8_t>& input) {
  101. std::vector<uint8_t> corrupted_data(input);
  102. if (corrupted_data.empty())
  103. corrupted_data.push_back(0);
  104. corrupted_data[corrupted_data.size() / 2] ^= 0x01;
  105. return corrupted_data;
  106. }
  107. std::vector<uint8_t> HexStringToBytes(const std::string& hex) {
  108. std::vector<uint8_t> bytes;
  109. // HexStringToBytes() doesn't allow empty inputs, but this wrapper does.
  110. if (hex.empty())
  111. return bytes;
  112. bool result = base::HexStringToBytes(hex, &bytes);
  113. CHECK(result);
  114. return bytes;
  115. }
  116. std::vector<uint8_t> MakeJsonVector(const base::DictionaryValue& value) {
  117. return MakeJsonVector(base::ValueView(value));
  118. }
  119. std::vector<uint8_t> MakeJsonVector(const base::ValueView& value) {
  120. std::string json;
  121. bool ok = base::JSONWriter::Write(value, &json);
  122. CHECK(ok);
  123. return std::vector<uint8_t>(json.begin(), json.end());
  124. }
  125. base::Value::List ReadJsonTestFileAsList(const char* test_file_name) {
  126. absl::optional<base::Value> result = ReadJsonTestFile(test_file_name);
  127. CHECK(result.has_value());
  128. CHECK(result->is_list());
  129. return std::move(result->GetList());
  130. }
  131. std::vector<uint8_t> GetBytesFromHexString(const base::Value* dict,
  132. const std::string& property_name) {
  133. if (!dict->is_dict()) {
  134. ADD_FAILURE() << "Value is not a dictionary";
  135. return std::vector<uint8_t>();
  136. }
  137. const std::string* hex_string = dict->FindStringPath(property_name);
  138. if (!hex_string) {
  139. ADD_FAILURE() << "Couldn't get string property: " << property_name;
  140. return std::vector<uint8_t>();
  141. }
  142. return HexStringToBytes(*hex_string);
  143. }
  144. blink::WebCryptoAlgorithm GetDigestAlgorithm(const base::DictionaryValue* dict,
  145. const char* property_name) {
  146. std::string algorithm_name;
  147. if (!dict->GetString(property_name, &algorithm_name)) {
  148. ADD_FAILURE() << "Couldn't get string property: " << property_name;
  149. return blink::WebCryptoAlgorithm::CreateNull();
  150. }
  151. struct {
  152. const char* name;
  153. blink::WebCryptoAlgorithmId id;
  154. } kDigestNameToId[] = {
  155. {"sha-1", blink::kWebCryptoAlgorithmIdSha1},
  156. {"sha-256", blink::kWebCryptoAlgorithmIdSha256},
  157. {"sha-384", blink::kWebCryptoAlgorithmIdSha384},
  158. {"sha-512", blink::kWebCryptoAlgorithmIdSha512},
  159. };
  160. for (auto mapping : kDigestNameToId) {
  161. if (mapping.name == algorithm_name)
  162. return CreateAlgorithm(mapping.id);
  163. }
  164. return blink::WebCryptoAlgorithm::CreateNull();
  165. }
  166. // Creates a comparator for |bufs| which operates on indices rather than values.
  167. class CompareUsingIndex {
  168. public:
  169. explicit CompareUsingIndex(const std::vector<std::vector<uint8_t>>* bufs)
  170. : bufs_(bufs) {}
  171. bool operator()(size_t i1, size_t i2) { return (*bufs_)[i1] < (*bufs_)[i2]; }
  172. private:
  173. raw_ptr<const std::vector<std::vector<uint8_t>>> bufs_;
  174. };
  175. bool CopiesExist(const std::vector<std::vector<uint8_t>>& bufs) {
  176. return std::set(bufs.begin(), bufs.end()).size() != bufs.size();
  177. }
  178. blink::WebCryptoAlgorithm CreateAesKeyGenAlgorithm(
  179. blink::WebCryptoAlgorithmId aes_alg_id,
  180. uint16_t length) {
  181. return blink::WebCryptoAlgorithm::AdoptParamsAndCreate(
  182. aes_alg_id, new blink::WebCryptoAesKeyGenParams(length));
  183. }
  184. // The following key pair is comprised of the SPKI (public key) and PKCS#8
  185. // (private key) representations of the key pair provided in Example 1 of the
  186. // NIST test vectors at
  187. // ftp://ftp.rsa.com/pub/rsalabs/tmp/pkcs1v15sign-vectors.txt
  188. const unsigned int kModulusLengthBits = 1024;
  189. const char* const kPublicKeySpkiDerHex =
  190. "30819f300d06092a864886f70d010101050003818d0030818902818100a5"
  191. "6e4a0e701017589a5187dc7ea841d156f2ec0e36ad52a44dfeb1e61f7ad9"
  192. "91d8c51056ffedb162b4c0f283a12a88a394dff526ab7291cbb307ceabfc"
  193. "e0b1dfd5cd9508096d5b2b8b6df5d671ef6377c0921cb23c270a70e2598e"
  194. "6ff89d19f105acc2d3f0cb35f29280e1386b6f64c4ef22e1e1f20d0ce8cf"
  195. "fb2249bd9a21370203010001";
  196. const char* const kPrivateKeyPkcs8DerHex =
  197. "30820275020100300d06092a864886f70d01010105000482025f3082025b"
  198. "02010002818100a56e4a0e701017589a5187dc7ea841d156f2ec0e36ad52"
  199. "a44dfeb1e61f7ad991d8c51056ffedb162b4c0f283a12a88a394dff526ab"
  200. "7291cbb307ceabfce0b1dfd5cd9508096d5b2b8b6df5d671ef6377c0921c"
  201. "b23c270a70e2598e6ff89d19f105acc2d3f0cb35f29280e1386b6f64c4ef"
  202. "22e1e1f20d0ce8cffb2249bd9a2137020301000102818033a5042a90b27d"
  203. "4f5451ca9bbbd0b44771a101af884340aef9885f2a4bbe92e894a724ac3c"
  204. "568c8f97853ad07c0266c8c6a3ca0929f1e8f11231884429fc4d9ae55fee"
  205. "896a10ce707c3ed7e734e44727a39574501a532683109c2abacaba283c31"
  206. "b4bd2f53c3ee37e352cee34f9e503bd80c0622ad79c6dcee883547c6a3b3"
  207. "25024100e7e8942720a877517273a356053ea2a1bc0c94aa72d55c6e8629"
  208. "6b2dfc967948c0a72cbccca7eacb35706e09a1df55a1535bd9b3cc34160b"
  209. "3b6dcd3eda8e6443024100b69dca1cf7d4d7ec81e75b90fcca874abcde12"
  210. "3fd2700180aa90479b6e48de8d67ed24f9f19d85ba275874f542cd20dc72"
  211. "3e6963364a1f9425452b269a6799fd024028fa13938655be1f8a159cbaca"
  212. "5a72ea190c30089e19cd274a556f36c4f6e19f554b34c077790427bbdd8d"
  213. "d3ede2448328f385d81b30e8e43b2fffa02786197902401a8b38f398fa71"
  214. "2049898d7fb79ee0a77668791299cdfa09efc0e507acb21ed74301ef5bfd"
  215. "48be455eaeb6e1678255827580a8e4e8e14151d1510a82a3f2e729024027"
  216. "156aba4126d24a81f3a528cbfb27f56886f840a9f6e86e17a44b94fe9319"
  217. "584b8e22fdde1e5a2e3bd8aa5ba8d8584194eb2190acf832b847f13a3d24"
  218. "a79f4d";
  219. // The modulus and exponent (in hex) of kPublicKeySpkiDerHex
  220. const char* const kPublicKeyModulusHex =
  221. "A56E4A0E701017589A5187DC7EA841D156F2EC0E36AD52A44DFEB1E61F7AD991D8C51056"
  222. "FFEDB162B4C0F283A12A88A394DFF526AB7291CBB307CEABFCE0B1DFD5CD9508096D5B2B"
  223. "8B6DF5D671EF6377C0921CB23C270A70E2598E6FF89D19F105ACC2D3F0CB35F29280E138"
  224. "6B6F64C4EF22E1E1F20D0CE8CFFB2249BD9A2137";
  225. const char* const kPublicKeyExponentHex = "010001";
  226. blink::WebCryptoKey ImportSecretKeyFromRaw(
  227. const std::vector<uint8_t>& key_raw,
  228. const blink::WebCryptoAlgorithm& algorithm,
  229. blink::WebCryptoKeyUsageMask usage) {
  230. blink::WebCryptoKey key;
  231. bool extractable = true;
  232. EXPECT_EQ(Status::Success(), ImportKey(blink::kWebCryptoKeyFormatRaw, key_raw,
  233. algorithm, extractable, usage, &key));
  234. EXPECT_FALSE(key.IsNull());
  235. EXPECT_TRUE(key.Handle());
  236. EXPECT_EQ(blink::kWebCryptoKeyTypeSecret, key.GetType());
  237. EXPECT_EQ(algorithm.Id(), key.Algorithm().Id());
  238. EXPECT_EQ(extractable, key.Extractable());
  239. EXPECT_EQ(usage, key.Usages());
  240. return key;
  241. }
  242. void ImportRsaKeyPair(const std::vector<uint8_t>& spki_der,
  243. const std::vector<uint8_t>& pkcs8_der,
  244. const blink::WebCryptoAlgorithm& algorithm,
  245. bool extractable,
  246. blink::WebCryptoKeyUsageMask public_key_usages,
  247. blink::WebCryptoKeyUsageMask private_key_usages,
  248. blink::WebCryptoKey* public_key,
  249. blink::WebCryptoKey* private_key) {
  250. ASSERT_EQ(Status::Success(),
  251. ImportKey(blink::kWebCryptoKeyFormatSpki, spki_der, algorithm, true,
  252. public_key_usages, public_key));
  253. EXPECT_FALSE(public_key->IsNull());
  254. EXPECT_TRUE(public_key->Handle());
  255. EXPECT_EQ(blink::kWebCryptoKeyTypePublic, public_key->GetType());
  256. EXPECT_EQ(algorithm.Id(), public_key->Algorithm().Id());
  257. EXPECT_TRUE(public_key->Extractable());
  258. EXPECT_EQ(public_key_usages, public_key->Usages());
  259. ASSERT_EQ(Status::Success(),
  260. ImportKey(blink::kWebCryptoKeyFormatPkcs8, pkcs8_der, algorithm,
  261. extractable, private_key_usages, private_key));
  262. EXPECT_FALSE(private_key->IsNull());
  263. EXPECT_TRUE(private_key->Handle());
  264. EXPECT_EQ(blink::kWebCryptoKeyTypePrivate, private_key->GetType());
  265. EXPECT_EQ(algorithm.Id(), private_key->Algorithm().Id());
  266. EXPECT_EQ(extractable, private_key->Extractable());
  267. EXPECT_EQ(private_key_usages, private_key->Usages());
  268. }
  269. Status ImportKeyJwkFromDict(const base::ValueView& dict,
  270. const blink::WebCryptoAlgorithm& algorithm,
  271. bool extractable,
  272. blink::WebCryptoKeyUsageMask usages,
  273. blink::WebCryptoKey* key) {
  274. return ImportKey(blink::kWebCryptoKeyFormatJwk, MakeJsonVector(dict),
  275. algorithm, extractable, usages, key);
  276. }
  277. Status ImportKeyJwkFromDict(const base::DictionaryValue& dict,
  278. const blink::WebCryptoAlgorithm& algorithm,
  279. bool extractable,
  280. blink::WebCryptoKeyUsageMask usages,
  281. blink::WebCryptoKey* key) {
  282. return ImportKeyJwkFromDict(base::ValueView(dict), algorithm, extractable,
  283. usages, key);
  284. }
  285. absl::optional<base::Value::Dict> GetJwkDictionary(
  286. const std::vector<uint8_t>& json) {
  287. base::StringPiece json_string(reinterpret_cast<const char*>(json.data()),
  288. json.size());
  289. absl::optional<base::Value> value = base::JSONReader::Read(json_string);
  290. EXPECT_TRUE(value.has_value());
  291. EXPECT_TRUE(value.value().is_dict());
  292. return absl::make_optional(std::move(value->GetDict()));
  293. }
  294. // Verifies the input dictionary contains the expected values. Exact matches are
  295. // required on the fields examined.
  296. ::testing::AssertionResult VerifyJwk(
  297. const base::Value::Dict& dict,
  298. const std::string& kty_expected,
  299. const std::string& alg_expected,
  300. blink::WebCryptoKeyUsageMask use_mask_expected) {
  301. // ---- kty
  302. const std::string* value_string = dict.FindString("kty");
  303. if (!value_string)
  304. return ::testing::AssertionFailure() << "Missing 'kty'";
  305. if (*value_string != kty_expected)
  306. return ::testing::AssertionFailure()
  307. << "Expected 'kty' to be " << kty_expected << "but found "
  308. << *value_string;
  309. // ---- alg
  310. value_string = dict.FindString("alg");
  311. if (!value_string)
  312. return ::testing::AssertionFailure() << "Missing 'alg'";
  313. if (*value_string != alg_expected)
  314. return ::testing::AssertionFailure()
  315. << "Expected 'alg' to be " << alg_expected << " but found "
  316. << *value_string;
  317. // ---- ext
  318. // always expect ext == true in this case
  319. absl::optional<bool> ext_value = dict.FindBool("ext");
  320. if (!ext_value)
  321. return ::testing::AssertionFailure() << "Missing 'ext'";
  322. if (!ext_value.value())
  323. return ::testing::AssertionFailure()
  324. << "Expected 'ext' to be true but found false";
  325. // ---- key_ops
  326. const base::Value::List* key_ops = dict.FindList("key_ops");
  327. if (!key_ops)
  328. return ::testing::AssertionFailure() << "Missing 'key_ops'";
  329. blink::WebCryptoKeyUsageMask key_ops_mask = 0;
  330. Status status =
  331. GetWebCryptoUsagesFromJwkKeyOpsForTest(*key_ops, &key_ops_mask);
  332. if (status.IsError())
  333. return ::testing::AssertionFailure() << "Failure extracting 'key_ops'";
  334. if (key_ops_mask != use_mask_expected)
  335. return ::testing::AssertionFailure()
  336. << "Expected 'key_ops' mask to be " << use_mask_expected
  337. << " but found " << key_ops_mask << " (" << value_string << ")";
  338. return ::testing::AssertionSuccess();
  339. }
  340. ::testing::AssertionResult VerifySecretJwk(
  341. const std::vector<uint8_t>& json,
  342. const std::string& alg_expected,
  343. const std::string& k_expected_hex,
  344. blink::WebCryptoKeyUsageMask use_mask_expected) {
  345. absl::optional<base::Value::Dict> dict = GetJwkDictionary(json);
  346. if (!dict.has_value() || dict.value().empty())
  347. return ::testing::AssertionFailure() << "JSON parsing failed";
  348. // ---- k
  349. const std::string* value_string = dict.value().FindString("k");
  350. if (!value_string)
  351. return ::testing::AssertionFailure() << "Missing 'k'";
  352. std::string k_value;
  353. if (!Base64DecodeUrlSafe(*value_string, &k_value))
  354. return ::testing::AssertionFailure() << "Base64DecodeUrlSafe(k) failed";
  355. if (!base::EqualsCaseInsensitiveASCII(
  356. base::HexEncode(k_value.data(), k_value.size()), k_expected_hex)) {
  357. return ::testing::AssertionFailure() << "Expected 'k' to be "
  358. << k_expected_hex
  359. << " but found something different";
  360. }
  361. return VerifyJwk(dict.value(), "oct", alg_expected, use_mask_expected);
  362. }
  363. ::testing::AssertionResult VerifyPublicJwk(
  364. const std::vector<uint8_t>& json,
  365. const std::string& alg_expected,
  366. const std::string& n_expected_hex,
  367. const std::string& e_expected_hex,
  368. blink::WebCryptoKeyUsageMask use_mask_expected) {
  369. absl::optional<base::Value::Dict> dict = GetJwkDictionary(json);
  370. if (!dict.has_value() || dict.value().empty())
  371. return ::testing::AssertionFailure() << "JSON parsing failed";
  372. // ---- n
  373. const std::string* value_string = dict.value().FindString("n");
  374. if (!value_string)
  375. return ::testing::AssertionFailure() << "Missing 'n'";
  376. std::string n_value;
  377. if (!Base64DecodeUrlSafe(*value_string, &n_value))
  378. return ::testing::AssertionFailure() << "Base64DecodeUrlSafe(n) failed";
  379. if (base::HexEncode(n_value.data(), n_value.size()) != n_expected_hex) {
  380. return ::testing::AssertionFailure() << "'n' does not match the expected "
  381. "value";
  382. }
  383. // TODO(padolph): EqualsCaseInsensitiveASCII() does not work for above!
  384. // ---- e
  385. value_string = dict.value().FindString("e");
  386. if (!value_string)
  387. return ::testing::AssertionFailure() << "Missing 'e'";
  388. std::string e_value;
  389. if (!Base64DecodeUrlSafe(*value_string, &e_value))
  390. return ::testing::AssertionFailure() << "Base64DecodeUrlSafe(e) failed";
  391. if (!base::EqualsCaseInsensitiveASCII(
  392. base::HexEncode(e_value.data(), e_value.size()), e_expected_hex)) {
  393. return ::testing::AssertionFailure() << "Expected 'e' to be "
  394. << e_expected_hex
  395. << " but found something different";
  396. }
  397. return VerifyJwk(dict.value(), "RSA", alg_expected, use_mask_expected);
  398. }
  399. void ImportExportJwkSymmetricKey(
  400. int key_len_bits,
  401. const blink::WebCryptoAlgorithm& import_algorithm,
  402. blink::WebCryptoKeyUsageMask usages,
  403. const std::string& jwk_alg) {
  404. std::vector<uint8_t> json;
  405. std::string key_hex;
  406. // Hardcoded pseudo-random bytes to use for keys of different lengths.
  407. switch (key_len_bits) {
  408. case 128:
  409. key_hex = "3f1e7cd4f6f8543f6b1e16002e688623";
  410. break;
  411. case 256:
  412. key_hex =
  413. "bd08286b81a74783fd1ccf46b7e05af84ee25ae021210074159e0c4d9d907692";
  414. break;
  415. case 384:
  416. key_hex =
  417. "a22c5441c8b185602283d64c7221de1d0951e706bfc09539435ec0e0ed614e1d40"
  418. "6623f2b31d31819fec30993380dd82";
  419. break;
  420. case 512:
  421. key_hex =
  422. "5834f639000d4cf82de124fbfd26fb88d463e99f839a76ba41ac88967c80a3f61e"
  423. "1239a452e573dba0750e988152988576efd75b8d0229b7aca2ada2afd392ee";
  424. break;
  425. default:
  426. FAIL() << "Unexpected key_len_bits" << key_len_bits;
  427. }
  428. // Import a raw key.
  429. blink::WebCryptoKey key = ImportSecretKeyFromRaw(HexStringToBytes(key_hex),
  430. import_algorithm, usages);
  431. // Export the key in JWK format and validate.
  432. ASSERT_EQ(Status::Success(),
  433. ExportKey(blink::kWebCryptoKeyFormatJwk, key, &json));
  434. EXPECT_TRUE(VerifySecretJwk(json, jwk_alg, key_hex, usages));
  435. // Import the JWK-formatted key.
  436. ASSERT_EQ(Status::Success(), ImportKey(blink::kWebCryptoKeyFormatJwk, json,
  437. import_algorithm, true, usages, &key));
  438. EXPECT_TRUE(key.Handle());
  439. EXPECT_EQ(blink::kWebCryptoKeyTypeSecret, key.GetType());
  440. EXPECT_EQ(import_algorithm.Id(), key.Algorithm().Id());
  441. EXPECT_EQ(true, key.Extractable());
  442. EXPECT_EQ(usages, key.Usages());
  443. // Export the key in raw format and compare to the original.
  444. std::vector<uint8_t> key_raw_out;
  445. ASSERT_EQ(Status::Success(),
  446. ExportKey(blink::kWebCryptoKeyFormatRaw, key, &key_raw_out));
  447. EXPECT_BYTES_EQ_HEX(key_hex, key_raw_out);
  448. }
  449. Status GenerateSecretKey(const blink::WebCryptoAlgorithm& algorithm,
  450. bool extractable,
  451. blink::WebCryptoKeyUsageMask usages,
  452. blink::WebCryptoKey* key) {
  453. GenerateKeyResult result;
  454. Status status = GenerateKey(algorithm, extractable, usages, &result);
  455. if (status.IsError())
  456. return status;
  457. if (result.type() != GenerateKeyResult::TYPE_SECRET_KEY)
  458. return Status::ErrorUnexpected();
  459. *key = result.secret_key();
  460. return Status::Success();
  461. }
  462. Status GenerateKeyPair(const blink::WebCryptoAlgorithm& algorithm,
  463. bool extractable,
  464. blink::WebCryptoKeyUsageMask usages,
  465. blink::WebCryptoKey* public_key,
  466. blink::WebCryptoKey* private_key) {
  467. GenerateKeyResult result;
  468. Status status = GenerateKey(algorithm, extractable, usages, &result);
  469. if (status.IsError())
  470. return status;
  471. if (result.type() != GenerateKeyResult::TYPE_PUBLIC_PRIVATE_KEY_PAIR)
  472. return Status::ErrorUnexpected();
  473. *public_key = result.public_key();
  474. *private_key = result.private_key();
  475. return Status::Success();
  476. }
  477. blink::WebCryptoKeyFormat GetKeyFormatFromJsonTestCase(
  478. const base::DictionaryValue* test) {
  479. std::string format;
  480. EXPECT_TRUE(test->GetString("key_format", &format));
  481. if (format == "jwk")
  482. return blink::kWebCryptoKeyFormatJwk;
  483. else if (format == "pkcs8")
  484. return blink::kWebCryptoKeyFormatPkcs8;
  485. else if (format == "spki")
  486. return blink::kWebCryptoKeyFormatSpki;
  487. else if (format == "raw")
  488. return blink::kWebCryptoKeyFormatRaw;
  489. ADD_FAILURE() << "Unrecognized key format: " << format;
  490. return blink::kWebCryptoKeyFormatRaw;
  491. }
  492. std::vector<uint8_t> GetKeyDataFromJsonTestCase(
  493. const base::DictionaryValue* test,
  494. blink::WebCryptoKeyFormat key_format) {
  495. if (key_format == blink::kWebCryptoKeyFormatJwk) {
  496. const base::DictionaryValue* json;
  497. EXPECT_TRUE(test->GetDictionary("key", &json));
  498. return MakeJsonVector(*json);
  499. }
  500. return GetBytesFromHexString(test, "key");
  501. }
  502. blink::WebCryptoNamedCurve GetCurveNameFromDictionary(
  503. const base::DictionaryValue* dict) {
  504. std::string curve_str;
  505. if (!dict->GetString("crv", &curve_str)) {
  506. ADD_FAILURE() << "Missing crv parameter";
  507. return blink::kWebCryptoNamedCurveP384;
  508. }
  509. if (curve_str == "P-256")
  510. return blink::kWebCryptoNamedCurveP256;
  511. if (curve_str == "P-384")
  512. return blink::kWebCryptoNamedCurveP384;
  513. if (curve_str == "P-521")
  514. return blink::kWebCryptoNamedCurveP521;
  515. else
  516. ADD_FAILURE() << "Unrecognized curve name: " << curve_str;
  517. return blink::kWebCryptoNamedCurveP384;
  518. }
  519. blink::WebCryptoAlgorithm CreateHmacImportAlgorithm(
  520. blink::WebCryptoAlgorithmId hash_id,
  521. unsigned int length_bits) {
  522. DCHECK(blink::WebCryptoAlgorithm::IsHash(hash_id));
  523. return blink::WebCryptoAlgorithm::AdoptParamsAndCreate(
  524. blink::kWebCryptoAlgorithmIdHmac,
  525. new blink::WebCryptoHmacImportParams(CreateAlgorithm(hash_id), true,
  526. length_bits));
  527. }
  528. blink::WebCryptoAlgorithm CreateHmacImportAlgorithmNoLength(
  529. blink::WebCryptoAlgorithmId hash_id) {
  530. DCHECK(blink::WebCryptoAlgorithm::IsHash(hash_id));
  531. return blink::WebCryptoAlgorithm::AdoptParamsAndCreate(
  532. blink::kWebCryptoAlgorithmIdHmac,
  533. new blink::WebCryptoHmacImportParams(CreateAlgorithm(hash_id), false, 0));
  534. }
  535. blink::WebCryptoAlgorithm CreateAlgorithm(blink::WebCryptoAlgorithmId id) {
  536. return blink::WebCryptoAlgorithm::AdoptParamsAndCreate(id, nullptr);
  537. }
  538. blink::WebCryptoAlgorithm CreateRsaHashedImportAlgorithm(
  539. blink::WebCryptoAlgorithmId id,
  540. blink::WebCryptoAlgorithmId hash_id) {
  541. DCHECK(blink::WebCryptoAlgorithm::IsHash(hash_id));
  542. return blink::WebCryptoAlgorithm::AdoptParamsAndCreate(
  543. id, new blink::WebCryptoRsaHashedImportParams(CreateAlgorithm(hash_id)));
  544. }
  545. blink::WebCryptoAlgorithm CreateEcImportAlgorithm(
  546. blink::WebCryptoAlgorithmId id,
  547. blink::WebCryptoNamedCurve named_curve) {
  548. return blink::WebCryptoAlgorithm::AdoptParamsAndCreate(
  549. id, new blink::WebCryptoEcKeyImportParams(named_curve));
  550. }
  551. } // namespace webcrypto