CryptoAlgorithms.cpp 64 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281
  1. /*
  2. * Copyright (c) 2024, Andrew Kaster <akaster@serenityos.org>
  3. *
  4. * SPDX-License-Identifier: BSD-2-Clause
  5. */
  6. #include <AK/Base64.h>
  7. #include <AK/QuickSort.h>
  8. #include <LibCrypto/ASN1/DER.h>
  9. #include <LibCrypto/Curves/Ed25519.h>
  10. #include <LibCrypto/Curves/SECPxxxr1.h>
  11. #include <LibCrypto/Hash/HashManager.h>
  12. #include <LibCrypto/PK/RSA.h>
  13. #include <LibJS/Runtime/ArrayBuffer.h>
  14. #include <LibJS/Runtime/DataView.h>
  15. #include <LibJS/Runtime/TypedArray.h>
  16. #include <LibTLS/Certificate.h>
  17. #include <LibWeb/Crypto/CryptoAlgorithms.h>
  18. #include <LibWeb/Crypto/KeyAlgorithms.h>
  19. #include <LibWeb/Crypto/SubtleCrypto.h>
  20. #include <LibWeb/WebIDL/AbstractOperations.h>
  21. namespace Web::Crypto {
  22. // https://w3c.github.io/webcrypto/#concept-usage-intersection
  23. static Vector<Bindings::KeyUsage> usage_intersection(ReadonlySpan<Bindings::KeyUsage> a, ReadonlySpan<Bindings::KeyUsage> b)
  24. {
  25. Vector<Bindings::KeyUsage> result;
  26. for (auto const& usage : a) {
  27. if (b.contains_slow(usage))
  28. result.append(usage);
  29. }
  30. quick_sort(result);
  31. return result;
  32. }
  33. // Out of line to ensure this class has a key function
  34. AlgorithmMethods::~AlgorithmMethods() = default;
  35. // https://w3c.github.io/webcrypto/#big-integer
  36. static ::Crypto::UnsignedBigInteger big_integer_from_api_big_integer(JS::GCPtr<JS::Uint8Array> const& big_integer)
  37. {
  38. static_assert(AK::HostIsLittleEndian, "This method needs special treatment for BE");
  39. // The BigInteger typedef is a Uint8Array that holds an arbitrary magnitude unsigned integer
  40. // **in big-endian order**. Values read from the API SHALL have minimal typed array length
  41. // (that is, at most 7 leading zero bits, except the value 0 which shall have length 8 bits).
  42. // The API SHALL accept values with any number of leading zero bits, including the empty array, which represents zero.
  43. auto const& buffer = big_integer->viewed_array_buffer()->buffer();
  44. ::Crypto::UnsignedBigInteger result(0);
  45. if (buffer.size() > 0) {
  46. // We need to reverse the buffer to get it into little-endian order
  47. Vector<u8, 32> reversed_buffer;
  48. reversed_buffer.resize(buffer.size());
  49. for (size_t i = 0; i < buffer.size(); ++i) {
  50. reversed_buffer[buffer.size() - i - 1] = buffer[i];
  51. }
  52. result = ::Crypto::UnsignedBigInteger::import_data(reversed_buffer.data(), reversed_buffer.size());
  53. }
  54. return result;
  55. }
  56. // https://www.rfc-editor.org/rfc/rfc7518#section-2
  57. ErrorOr<String> base64_url_uint_encode(::Crypto::UnsignedBigInteger integer)
  58. {
  59. static_assert(AK::HostIsLittleEndian, "This code assumes little-endian");
  60. // The representation of a positive or zero integer value as the
  61. // base64url encoding of the value's unsigned big-endian
  62. // representation as an octet sequence. The octet sequence MUST
  63. // utilize the minimum number of octets needed to represent the
  64. // value. Zero is represented as BASE64URL(single zero-valued
  65. // octet), which is "AA".
  66. auto bytes = TRY(ByteBuffer::create_uninitialized(integer.trimmed_byte_length()));
  67. bool const remove_leading_zeroes = true;
  68. auto data_size = integer.export_data(bytes.span(), remove_leading_zeroes);
  69. auto data_slice = bytes.bytes().slice(bytes.size() - data_size, data_size);
  70. // We need to encode the integer's big endian representation as a base64 string
  71. Vector<u8, 32> byte_swapped_data;
  72. byte_swapped_data.ensure_capacity(data_size);
  73. for (size_t i = 0; i < data_size; ++i)
  74. byte_swapped_data.append(data_slice[data_size - i - 1]);
  75. auto encoded = TRY(encode_base64url(byte_swapped_data));
  76. // FIXME: create a version of encode_base64url that omits padding bytes
  77. if (auto first_padding_byte = encoded.find_byte_offset('='); first_padding_byte.has_value())
  78. return encoded.substring_from_byte_offset(0, first_padding_byte.value());
  79. return encoded;
  80. }
  81. WebIDL::ExceptionOr<::Crypto::UnsignedBigInteger> base64_url_uint_decode(JS::Realm& realm, String const& base64_url_string)
  82. {
  83. auto& vm = realm.vm();
  84. static_assert(AK::HostIsLittleEndian, "This code assumes little-endian");
  85. // FIXME: Create a version of decode_base64url that ignores padding inconsistencies
  86. auto padded_string = base64_url_string;
  87. if (padded_string.byte_count() % 4 != 0) {
  88. padded_string = TRY_OR_THROW_OOM(vm, String::formatted("{}{}", padded_string, TRY_OR_THROW_OOM(vm, String::repeated('=', 4 - (padded_string.byte_count() % 4)))));
  89. }
  90. auto base64_bytes_or_error = decode_base64url(padded_string);
  91. if (base64_bytes_or_error.is_error()) {
  92. if (base64_bytes_or_error.error().code() == ENOMEM)
  93. return vm.throw_completion<JS::InternalError>(vm.error_message(::JS::VM::ErrorMessage::OutOfMemory));
  94. return WebIDL::DataError::create(realm, MUST(String::formatted("base64 decode: {}", base64_bytes_or_error.release_error())));
  95. }
  96. auto base64_bytes = base64_bytes_or_error.release_value();
  97. // We need to swap the integer's big-endian representation to little endian in order to import it
  98. Vector<u8, 32> byte_swapped_data;
  99. byte_swapped_data.ensure_capacity(base64_bytes.size());
  100. for (size_t i = 0; i < base64_bytes.size(); ++i)
  101. byte_swapped_data.append(base64_bytes[base64_bytes.size() - i - 1]);
  102. return ::Crypto::UnsignedBigInteger::import_data(byte_swapped_data.data(), byte_swapped_data.size());
  103. }
  104. // https://w3c.github.io/webcrypto/#concept-parse-an-asn1-structure
  105. template<typename Structure>
  106. static WebIDL::ExceptionOr<Structure> parse_an_ASN1_structure(JS::Realm& realm, ReadonlyBytes data, bool exact_data = true)
  107. {
  108. // 1. Let data be a sequence of bytes to be parsed.
  109. // 2. Let structure be the ASN.1 structure to be parsed.
  110. // 3. Let exactData be an optional boolean value. If it is not supplied, let it be initialized to true.
  111. // 4. Parse data according to the Distinguished Encoding Rules of [X690], using structure as the ASN.1 structure to be decoded.
  112. ::Crypto::ASN1::Decoder decoder(data);
  113. Structure structure;
  114. if constexpr (IsSame<Structure, TLS::SubjectPublicKey>) {
  115. auto maybe_subject_public_key = TLS::parse_subject_public_key_info(decoder);
  116. if (maybe_subject_public_key.is_error())
  117. return WebIDL::DataError::create(realm, MUST(String::formatted("Error parsing subjectPublicKeyInfo: {}", maybe_subject_public_key.release_error())));
  118. structure = maybe_subject_public_key.release_value();
  119. } else if constexpr (IsSame<Structure, TLS::PrivateKey>) {
  120. auto maybe_private_key = TLS::parse_private_key_info(decoder);
  121. if (maybe_private_key.is_error())
  122. return WebIDL::DataError::create(realm, MUST(String::formatted("Error parsing privateKeyInfo: {}", maybe_private_key.release_error())));
  123. structure = maybe_private_key.release_value();
  124. } else {
  125. static_assert(DependentFalse<Structure>, "Don't know how to parse ASN.1 structure type");
  126. }
  127. // 5. If exactData was specified, and all of the bytes of data were not consumed during the parsing phase, then throw a DataError.
  128. if (exact_data && !decoder.eof())
  129. return WebIDL::DataError::create(realm, "Not all bytes were consumed during the parsing phase"_fly_string);
  130. // 6. Return the parsed ASN.1 structure.
  131. return structure;
  132. }
  133. // https://w3c.github.io/webcrypto/#concept-parse-a-spki
  134. static WebIDL::ExceptionOr<TLS::SubjectPublicKey> parse_a_subject_public_key_info(JS::Realm& realm, ReadonlyBytes bytes)
  135. {
  136. // When this specification says to parse a subjectPublicKeyInfo, the user agent must parse an ASN.1 structure,
  137. // with data set to the sequence of bytes to be parsed, structure as the ASN.1 structure of subjectPublicKeyInfo,
  138. // as specified in [RFC5280], and exactData set to true.
  139. return parse_an_ASN1_structure<TLS::SubjectPublicKey>(realm, bytes, true);
  140. }
  141. // https://w3c.github.io/webcrypto/#concept-parse-a-privateKeyInfo
  142. static WebIDL::ExceptionOr<TLS::PrivateKey> parse_a_private_key_info(JS::Realm& realm, ReadonlyBytes bytes)
  143. {
  144. // When this specification says to parse a PrivateKeyInfo, the user agent must parse an ASN.1 structure
  145. // with data set to the sequence of bytes to be parsed, structure as the ASN.1 structure of PrivateKeyInfo,
  146. // as specified in [RFC5208], and exactData set to true.
  147. return parse_an_ASN1_structure<TLS::PrivateKey>(realm, bytes, true);
  148. }
  149. static WebIDL::ExceptionOr<::Crypto::PK::RSAPrivateKey<>> parse_jwk_rsa_private_key(JS::Realm& realm, Bindings::JsonWebKey const& jwk)
  150. {
  151. auto n = TRY(base64_url_uint_decode(realm, *jwk.n));
  152. auto d = TRY(base64_url_uint_decode(realm, *jwk.d));
  153. auto e = TRY(base64_url_uint_decode(realm, *jwk.e));
  154. // We know that if any of the extra parameters are provided, all of them must be
  155. if (!jwk.p.has_value())
  156. return ::Crypto::PK::RSAPrivateKey<>(move(n), move(d), move(e), 0, 0);
  157. auto p = TRY(base64_url_uint_decode(realm, *jwk.p));
  158. auto q = TRY(base64_url_uint_decode(realm, *jwk.q));
  159. auto dp = TRY(base64_url_uint_decode(realm, *jwk.dp));
  160. auto dq = TRY(base64_url_uint_decode(realm, *jwk.dq));
  161. auto qi = TRY(base64_url_uint_decode(realm, *jwk.qi));
  162. return ::Crypto::PK::RSAPrivateKey<>(move(n), move(d), move(e), move(p), move(q), move(dp), move(dq), move(qi));
  163. }
  164. static WebIDL::ExceptionOr<::Crypto::PK::RSAPublicKey<>> parse_jwk_rsa_public_key(JS::Realm& realm, Bindings::JsonWebKey const& jwk)
  165. {
  166. auto e = TRY(base64_url_uint_decode(realm, *jwk.e));
  167. auto n = TRY(base64_url_uint_decode(realm, *jwk.n));
  168. return ::Crypto::PK::RSAPublicKey<>(move(n), move(e));
  169. }
  170. AlgorithmParams::~AlgorithmParams() = default;
  171. JS::ThrowCompletionOr<NonnullOwnPtr<AlgorithmParams>> AlgorithmParams::from_value(JS::VM& vm, JS::Value value)
  172. {
  173. auto& object = value.as_object();
  174. auto name = TRY(object.get("name"));
  175. auto name_string = TRY(name.to_string(vm));
  176. return adopt_own(*new AlgorithmParams { name_string });
  177. }
  178. PBKDF2Params::~PBKDF2Params() = default;
  179. JS::ThrowCompletionOr<NonnullOwnPtr<AlgorithmParams>> PBKDF2Params::from_value(JS::VM& vm, JS::Value value)
  180. {
  181. auto& object = value.as_object();
  182. auto name_value = TRY(object.get("name"));
  183. auto name = TRY(name_value.to_string(vm));
  184. auto salt_value = TRY(object.get("salt"));
  185. if (!salt_value.is_object() || !(is<JS::TypedArrayBase>(salt_value.as_object()) || is<JS::ArrayBuffer>(salt_value.as_object()) || is<JS::DataView>(salt_value.as_object())))
  186. return vm.throw_completion<JS::TypeError>(JS::ErrorType::NotAnObjectOfType, "BufferSource");
  187. auto salt = TRY_OR_THROW_OOM(vm, WebIDL::get_buffer_source_copy(salt_value.as_object()));
  188. auto iterations_value = TRY(object.get("iterations"));
  189. auto iterations = TRY(iterations_value.to_u32(vm));
  190. auto hash_value = TRY(object.get("hash"));
  191. auto hash = Variant<Empty, HashAlgorithmIdentifier> { Empty {} };
  192. if (hash_value.is_string()) {
  193. auto hash_string = TRY(hash_value.to_string(vm));
  194. hash = HashAlgorithmIdentifier { hash_string };
  195. } else {
  196. auto hash_object = TRY(hash_value.to_object(vm));
  197. hash = HashAlgorithmIdentifier { hash_object };
  198. }
  199. return adopt_own<AlgorithmParams>(*new PBKDF2Params { name, salt, iterations, hash.downcast<HashAlgorithmIdentifier>() });
  200. }
  201. RsaKeyGenParams::~RsaKeyGenParams() = default;
  202. JS::ThrowCompletionOr<NonnullOwnPtr<AlgorithmParams>> RsaKeyGenParams::from_value(JS::VM& vm, JS::Value value)
  203. {
  204. auto& object = value.as_object();
  205. auto name_value = TRY(object.get("name"));
  206. auto name = TRY(name_value.to_string(vm));
  207. auto modulus_length_value = TRY(object.get("modulusLength"));
  208. auto modulus_length = TRY(modulus_length_value.to_u32(vm));
  209. auto public_exponent_value = TRY(object.get("publicExponent"));
  210. JS::GCPtr<JS::Uint8Array> public_exponent;
  211. if (!public_exponent_value.is_object() || !is<JS::Uint8Array>(public_exponent_value.as_object()))
  212. return vm.throw_completion<JS::TypeError>(JS::ErrorType::NotAnObjectOfType, "Uint8Array");
  213. public_exponent = static_cast<JS::Uint8Array&>(public_exponent_value.as_object());
  214. return adopt_own<AlgorithmParams>(*new RsaKeyGenParams { name, modulus_length, big_integer_from_api_big_integer(public_exponent) });
  215. }
  216. RsaHashedKeyGenParams::~RsaHashedKeyGenParams() = default;
  217. JS::ThrowCompletionOr<NonnullOwnPtr<AlgorithmParams>> RsaHashedKeyGenParams::from_value(JS::VM& vm, JS::Value value)
  218. {
  219. auto& object = value.as_object();
  220. auto name_value = TRY(object.get("name"));
  221. auto name = TRY(name_value.to_string(vm));
  222. auto modulus_length_value = TRY(object.get("modulusLength"));
  223. auto modulus_length = TRY(modulus_length_value.to_u32(vm));
  224. auto public_exponent_value = TRY(object.get("publicExponent"));
  225. JS::GCPtr<JS::Uint8Array> public_exponent;
  226. if (!public_exponent_value.is_object() || !is<JS::Uint8Array>(public_exponent_value.as_object()))
  227. return vm.throw_completion<JS::TypeError>(JS::ErrorType::NotAnObjectOfType, "Uint8Array");
  228. public_exponent = static_cast<JS::Uint8Array&>(public_exponent_value.as_object());
  229. auto hash_value = TRY(object.get("hash"));
  230. auto hash = Variant<Empty, HashAlgorithmIdentifier> { Empty {} };
  231. if (hash_value.is_string()) {
  232. auto hash_string = TRY(hash_value.to_string(vm));
  233. hash = HashAlgorithmIdentifier { hash_string };
  234. } else {
  235. auto hash_object = TRY(hash_value.to_object(vm));
  236. hash = HashAlgorithmIdentifier { hash_object };
  237. }
  238. return adopt_own<AlgorithmParams>(*new RsaHashedKeyGenParams { name, modulus_length, big_integer_from_api_big_integer(public_exponent), hash.get<HashAlgorithmIdentifier>() });
  239. }
  240. RsaHashedImportParams::~RsaHashedImportParams() = default;
  241. JS::ThrowCompletionOr<NonnullOwnPtr<AlgorithmParams>> RsaHashedImportParams::from_value(JS::VM& vm, JS::Value value)
  242. {
  243. auto& object = value.as_object();
  244. auto name_value = TRY(object.get("name"));
  245. auto name = TRY(name_value.to_string(vm));
  246. auto hash_value = TRY(object.get("hash"));
  247. auto hash = Variant<Empty, HashAlgorithmIdentifier> { Empty {} };
  248. if (hash_value.is_string()) {
  249. auto hash_string = TRY(hash_value.to_string(vm));
  250. hash = HashAlgorithmIdentifier { hash_string };
  251. } else {
  252. auto hash_object = TRY(hash_value.to_object(vm));
  253. hash = HashAlgorithmIdentifier { hash_object };
  254. }
  255. return adopt_own<AlgorithmParams>(*new RsaHashedImportParams { name, hash.get<HashAlgorithmIdentifier>() });
  256. }
  257. RsaOaepParams::~RsaOaepParams() = default;
  258. JS::ThrowCompletionOr<NonnullOwnPtr<AlgorithmParams>> RsaOaepParams::from_value(JS::VM& vm, JS::Value value)
  259. {
  260. auto& object = value.as_object();
  261. auto name_value = TRY(object.get("name"));
  262. auto name = TRY(name_value.to_string(vm));
  263. auto label_value = TRY(object.get("label"));
  264. ByteBuffer label;
  265. if (!label_value.is_nullish()) {
  266. if (!label_value.is_object() || !(is<JS::TypedArrayBase>(label_value.as_object()) || is<JS::ArrayBuffer>(label_value.as_object()) || is<JS::DataView>(label_value.as_object())))
  267. return vm.throw_completion<JS::TypeError>(JS::ErrorType::NotAnObjectOfType, "BufferSource");
  268. label = TRY_OR_THROW_OOM(vm, WebIDL::get_buffer_source_copy(label_value.as_object()));
  269. }
  270. return adopt_own<AlgorithmParams>(*new RsaOaepParams { name, move(label) });
  271. }
  272. EcdsaParams::~EcdsaParams() = default;
  273. JS::ThrowCompletionOr<NonnullOwnPtr<AlgorithmParams>> EcdsaParams::from_value(JS::VM& vm, JS::Value value)
  274. {
  275. auto& object = value.as_object();
  276. auto name_value = TRY(object.get("name"));
  277. auto name = TRY(name_value.to_string(vm));
  278. auto hash_value = TRY(object.get("hash"));
  279. auto hash = Variant<Empty, HashAlgorithmIdentifier> { Empty {} };
  280. if (hash_value.is_string()) {
  281. auto hash_string = TRY(hash_value.to_string(vm));
  282. hash = HashAlgorithmIdentifier { hash_string };
  283. } else {
  284. auto hash_object = TRY(hash_value.to_object(vm));
  285. hash = HashAlgorithmIdentifier { hash_object };
  286. }
  287. return adopt_own<AlgorithmParams>(*new EcdsaParams { name, hash.get<HashAlgorithmIdentifier>() });
  288. }
  289. EcKeyGenParams::~EcKeyGenParams() = default;
  290. JS::ThrowCompletionOr<NonnullOwnPtr<AlgorithmParams>> EcKeyGenParams::from_value(JS::VM& vm, JS::Value value)
  291. {
  292. auto& object = value.as_object();
  293. auto name_value = TRY(object.get("name"));
  294. auto name = TRY(name_value.to_string(vm));
  295. auto curve_value = TRY(object.get("namedCurve"));
  296. auto curve = TRY(curve_value.to_string(vm));
  297. return adopt_own<AlgorithmParams>(*new EcKeyGenParams { name, curve });
  298. }
  299. // https://w3c.github.io/webcrypto/#rsa-oaep-operations
  300. WebIDL::ExceptionOr<JS::NonnullGCPtr<JS::ArrayBuffer>> RSAOAEP::encrypt(AlgorithmParams const& params, JS::NonnullGCPtr<CryptoKey> key, ByteBuffer const& plaintext)
  301. {
  302. auto& realm = m_realm;
  303. auto& vm = realm.vm();
  304. auto const& normalized_algorithm = static_cast<RsaOaepParams const&>(params);
  305. // 1. If the [[type]] internal slot of key is not "public", then throw an InvalidAccessError.
  306. if (key->type() != Bindings::KeyType::Public)
  307. return WebIDL::InvalidAccessError::create(realm, "Key is not a public key"_fly_string);
  308. // 2. Let label be the contents of the label member of normalizedAlgorithm or the empty octet string if the label member of normalizedAlgorithm is not present.
  309. [[maybe_unused]] auto const& label = normalized_algorithm.label;
  310. // 3. Perform the encryption operation defined in Section 7.1 of [RFC3447] with the key represented by key as the recipient's RSA public key,
  311. // the contents of plaintext as the message to be encrypted, M and label as the label, L, and with the hash function specified by the hash attribute
  312. // of the [[algorithm]] internal slot of key as the Hash option and MGF1 (defined in Section B.2.1 of [RFC3447]) as the MGF option.
  313. // 4. If performing the operation results in an error, then throw an OperationError.
  314. // 5. Let ciphertext be the value C that results from performing the operation.
  315. // FIXME: Actually encrypt the data
  316. auto ciphertext = TRY_OR_THROW_OOM(vm, ByteBuffer::copy(plaintext));
  317. // 6. Return the result of creating an ArrayBuffer containing ciphertext.
  318. return JS::ArrayBuffer::create(realm, move(ciphertext));
  319. }
  320. // https://w3c.github.io/webcrypto/#rsa-oaep-operations
  321. WebIDL::ExceptionOr<JS::NonnullGCPtr<JS::ArrayBuffer>> RSAOAEP::decrypt(AlgorithmParams const& params, JS::NonnullGCPtr<CryptoKey> key, AK::ByteBuffer const& ciphertext)
  322. {
  323. auto& realm = m_realm;
  324. auto& vm = realm.vm();
  325. auto const& normalized_algorithm = static_cast<RsaOaepParams const&>(params);
  326. // 1. If the [[type]] internal slot of key is not "private", then throw an InvalidAccessError.
  327. if (key->type() != Bindings::KeyType::Private)
  328. return WebIDL::InvalidAccessError::create(realm, "Key is not a private key"_fly_string);
  329. // 2. Let label be the contents of the label member of normalizedAlgorithm or the empty octet string if the label member of normalizedAlgorithm is not present.
  330. [[maybe_unused]] auto const& label = normalized_algorithm.label;
  331. // 3. Perform the decryption operation defined in Section 7.1 of [RFC3447] with the key represented by key as the recipient's RSA private key,
  332. // the contents of ciphertext as the ciphertext to be decrypted, C, and label as the label, L, and with the hash function specified by the hash attribute
  333. // of the [[algorithm]] internal slot of key as the Hash option and MGF1 (defined in Section B.2.1 of [RFC3447]) as the MGF option.
  334. // 4. If performing the operation results in an error, then throw an OperationError.
  335. // 5. Let plaintext the value M that results from performing the operation.
  336. // FIXME: Actually decrypt the data
  337. auto plaintext = TRY_OR_THROW_OOM(vm, ByteBuffer::copy(ciphertext));
  338. // 6. Return the result of creating an ArrayBuffer containing plaintext.
  339. return JS::ArrayBuffer::create(realm, move(plaintext));
  340. }
  341. // https://w3c.github.io/webcrypto/#rsa-oaep-operations
  342. WebIDL::ExceptionOr<Variant<JS::NonnullGCPtr<CryptoKey>, JS::NonnullGCPtr<CryptoKeyPair>>> RSAOAEP::generate_key(AlgorithmParams const& params, bool extractable, Vector<Bindings::KeyUsage> const& key_usages)
  343. {
  344. // 1. If usages contains an entry which is not "encrypt", "decrypt", "wrapKey" or "unwrapKey", then throw a SyntaxError.
  345. for (auto const& usage : key_usages) {
  346. if (usage != Bindings::KeyUsage::Encrypt && usage != Bindings::KeyUsage::Decrypt && usage != Bindings::KeyUsage::Wrapkey && usage != Bindings::KeyUsage::Unwrapkey) {
  347. return WebIDL::SyntaxError::create(m_realm, MUST(String::formatted("Invalid key usage '{}'", idl_enum_to_string(usage))));
  348. }
  349. }
  350. // 2. Generate an RSA key pair, as defined in [RFC3447], with RSA modulus length equal to the modulusLength member of normalizedAlgorithm
  351. // and RSA public exponent equal to the publicExponent member of normalizedAlgorithm.
  352. // 3. If performing the operation results in an error, then throw an OperationError.
  353. auto const& normalized_algorithm = static_cast<RsaHashedKeyGenParams const&>(params);
  354. auto key_pair = ::Crypto::PK::RSA::generate_key_pair(normalized_algorithm.modulus_length, normalized_algorithm.public_exponent);
  355. // 4. Let algorithm be a new RsaHashedKeyAlgorithm object.
  356. auto algorithm = RsaHashedKeyAlgorithm::create(m_realm);
  357. // 5. Set the name attribute of algorithm to "RSA-OAEP".
  358. algorithm->set_name("RSA-OAEP"_string);
  359. // 6. Set the modulusLength attribute of algorithm to equal the modulusLength member of normalizedAlgorithm.
  360. algorithm->set_modulus_length(normalized_algorithm.modulus_length);
  361. // 7. Set the publicExponent attribute of algorithm to equal the publicExponent member of normalizedAlgorithm.
  362. TRY(algorithm->set_public_exponent(normalized_algorithm.public_exponent));
  363. // 8. Set the hash attribute of algorithm to equal the hash member of normalizedAlgorithm.
  364. algorithm->set_hash(normalized_algorithm.hash);
  365. // 9. Let publicKey be a new CryptoKey representing the public key of the generated key pair.
  366. auto public_key = CryptoKey::create(m_realm, CryptoKey::InternalKeyData { key_pair.public_key });
  367. // 10. Set the [[type]] internal slot of publicKey to "public"
  368. public_key->set_type(Bindings::KeyType::Public);
  369. // 11. Set the [[algorithm]] internal slot of publicKey to algorithm.
  370. public_key->set_algorithm(algorithm);
  371. // 12. Set the [[extractable]] internal slot of publicKey to true.
  372. public_key->set_extractable(true);
  373. // 13. Set the [[usages]] internal slot of publicKey to be the usage intersection of usages and [ "encrypt", "wrapKey" ].
  374. public_key->set_usages(usage_intersection(key_usages, { { Bindings::KeyUsage::Encrypt, Bindings::KeyUsage::Wrapkey } }));
  375. // 14. Let privateKey be a new CryptoKey representing the private key of the generated key pair.
  376. auto private_key = CryptoKey::create(m_realm, CryptoKey::InternalKeyData { key_pair.private_key });
  377. // 15. Set the [[type]] internal slot of privateKey to "private"
  378. private_key->set_type(Bindings::KeyType::Private);
  379. // 16. Set the [[algorithm]] internal slot of privateKey to algorithm.
  380. private_key->set_algorithm(algorithm);
  381. // 17. Set the [[extractable]] internal slot of privateKey to extractable.
  382. private_key->set_extractable(extractable);
  383. // 18. Set the [[usages]] internal slot of privateKey to be the usage intersection of usages and [ "decrypt", "unwrapKey" ].
  384. private_key->set_usages(usage_intersection(key_usages, { { Bindings::KeyUsage::Decrypt, Bindings::KeyUsage::Unwrapkey } }));
  385. // 19. Let result be a new CryptoKeyPair dictionary.
  386. // 20. Set the publicKey attribute of result to be publicKey.
  387. // 21. Set the privateKey attribute of result to be privateKey.
  388. // 22. Return the result of converting result to an ECMAScript Object, as defined by [WebIDL].
  389. return Variant<JS::NonnullGCPtr<CryptoKey>, JS::NonnullGCPtr<CryptoKeyPair>> { CryptoKeyPair::create(m_realm, public_key, private_key) };
  390. }
  391. // https://w3c.github.io/webcrypto/#rsa-oaep-operations
  392. WebIDL::ExceptionOr<JS::NonnullGCPtr<CryptoKey>> RSAOAEP::import_key(Web::Crypto::AlgorithmParams const& params, Bindings::KeyFormat key_format, CryptoKey::InternalKeyData key_data, bool extractable, Vector<Bindings::KeyUsage> const& usages)
  393. {
  394. auto& realm = m_realm;
  395. // 1. Let keyData be the key data to be imported.
  396. JS::GCPtr<CryptoKey> key = nullptr;
  397. auto const& normalized_algorithm = static_cast<RsaHashedImportParams const&>(params);
  398. // 2. -> If format is "spki":
  399. if (key_format == Bindings::KeyFormat::Spki) {
  400. // 1. If usages contains an entry which is not "encrypt" or "wrapKey", then throw a SyntaxError.
  401. for (auto const& usage : usages) {
  402. if (usage != Bindings::KeyUsage::Encrypt && usage != Bindings::KeyUsage::Wrapkey) {
  403. return WebIDL::SyntaxError::create(m_realm, MUST(String::formatted("Invalid key usage '{}'", idl_enum_to_string(usage))));
  404. }
  405. }
  406. VERIFY(key_data.has<ByteBuffer>());
  407. // 2. Let spki be the result of running the parse a subjectPublicKeyInfo algorithm over keyData.
  408. // 3. If an error occurred while parsing, then throw a DataError.
  409. auto spki = TRY(parse_a_subject_public_key_info(m_realm, key_data.get<ByteBuffer>()));
  410. // 4. If the algorithm object identifier field of the algorithm AlgorithmIdentifier field of spki
  411. // is not equal to the rsaEncryption object identifier defined in [RFC3447], then throw a DataError.
  412. if (spki.algorithm.identifier != TLS::rsa_encryption_oid)
  413. return WebIDL::DataError::create(m_realm, "Algorithm object identifier is not the rsaEncryption object identifier"_fly_string);
  414. // 5. Let publicKey be the result of performing the parse an ASN.1 structure algorithm,
  415. // with data as the subjectPublicKeyInfo field of spki, structure as the RSAPublicKey structure
  416. // specified in Section A.1.1 of [RFC3447], and exactData set to true.
  417. // NOTE: We already did this in parse_a_subject_public_key_info
  418. auto& public_key = spki.rsa;
  419. // 6. If an error occurred while parsing, or it can be determined that publicKey is not
  420. // a valid public key according to [RFC3447], then throw a DataError.
  421. // FIXME: Validate the public key
  422. // 7. Let key be a new CryptoKey that represents the RSA public key identified by publicKey.
  423. key = CryptoKey::create(m_realm, CryptoKey::InternalKeyData { public_key });
  424. // 8. Set the [[type]] internal slot of key to "public"
  425. key->set_type(Bindings::KeyType::Public);
  426. }
  427. // -> If format is "pkcs8":
  428. else if (key_format == Bindings::KeyFormat::Pkcs8) {
  429. // 1. If usages contains an entry which is not "decrypt" or "unwrapKey", then throw a SyntaxError.
  430. for (auto const& usage : usages) {
  431. if (usage != Bindings::KeyUsage::Decrypt && usage != Bindings::KeyUsage::Unwrapkey) {
  432. return WebIDL::SyntaxError::create(m_realm, MUST(String::formatted("Invalid key usage '{}'", idl_enum_to_string(usage))));
  433. }
  434. }
  435. VERIFY(key_data.has<ByteBuffer>());
  436. // 2. Let privateKeyInfo be the result of running the parse a privateKeyInfo algorithm over keyData.
  437. // 3. If an error occurred while parsing, then throw a DataError.
  438. auto private_key_info = TRY(parse_a_private_key_info(m_realm, key_data.get<ByteBuffer>()));
  439. // 4. If the algorithm object identifier field of the privateKeyAlgorithm PrivateKeyAlgorithm field of privateKeyInfo
  440. // is not equal to the rsaEncryption object identifier defined in [RFC3447], then throw a DataError.
  441. if (private_key_info.algorithm.identifier != TLS::rsa_encryption_oid)
  442. return WebIDL::DataError::create(m_realm, "Algorithm object identifier is not the rsaEncryption object identifier"_fly_string);
  443. // 5. Let rsaPrivateKey be the result of performing the parse an ASN.1 structure algorithm,
  444. // with data as the privateKey field of privateKeyInfo, structure as the RSAPrivateKey structure
  445. // specified in Section A.1.2 of [RFC3447], and exactData set to true.
  446. // NOTE: We already did this in parse_a_private_key_info
  447. auto& rsa_private_key = private_key_info.rsa;
  448. // 6. If an error occurred while parsing, or if rsaPrivateKey is not
  449. // a valid RSA private key according to [RFC3447], then throw a DataError.
  450. // FIXME: Validate the private key
  451. // 7. Let key be a new CryptoKey that represents the RSA private key identified by rsaPrivateKey.
  452. key = CryptoKey::create(m_realm, CryptoKey::InternalKeyData { rsa_private_key });
  453. // 8. Set the [[type]] internal slot of key to "private"
  454. key->set_type(Bindings::KeyType::Private);
  455. }
  456. // -> If format is "jwk":
  457. else if (key_format == Bindings::KeyFormat::Jwk) {
  458. // 1. -> If keyData is a JsonWebKey dictionary:
  459. // Let jwk equal keyData.
  460. // -> Otherwise:
  461. // Throw a DataError.
  462. if (!key_data.has<Bindings::JsonWebKey>())
  463. return WebIDL::DataError::create(m_realm, "keyData is not a JsonWebKey dictionary"_fly_string);
  464. auto& jwk = key_data.get<Bindings::JsonWebKey>();
  465. // 2. If the d field of jwk is present and usages contains an entry which is not "decrypt" or "unwrapKey", then throw a SyntaxError.
  466. if (jwk.d.has_value()) {
  467. for (auto const& usage : usages) {
  468. if (usage != Bindings::KeyUsage::Decrypt && usage != Bindings::KeyUsage::Unwrapkey) {
  469. return WebIDL::SyntaxError::create(m_realm, MUST(String::formatted("Invalid key usage '{}'", Bindings::idl_enum_to_string(usage))));
  470. }
  471. }
  472. }
  473. // 3. If the d field of jwk is not present and usages contains an entry which is not "encrypt" or "wrapKey", then throw a SyntaxError.
  474. if (!jwk.d.has_value()) {
  475. for (auto const& usage : usages) {
  476. if (usage != Bindings::KeyUsage::Encrypt && usage != Bindings::KeyUsage::Wrapkey) {
  477. return WebIDL::SyntaxError::create(m_realm, MUST(String::formatted("Invalid key usage '{}'", Bindings::idl_enum_to_string(usage))));
  478. }
  479. }
  480. }
  481. // 4. If the kty field of jwk is not a case-sensitive string match to "RSA", then throw a DataError.
  482. if (jwk.kty != "RSA"_string)
  483. return WebIDL::DataError::create(m_realm, "Invalid key type"_fly_string);
  484. // 5. If usages is non-empty and the use field of jwk is present and is not a case-sensitive string match to "enc", then throw a DataError.
  485. if (!usages.is_empty() && jwk.use.has_value() && *jwk.use != "enc"_string)
  486. return WebIDL::DataError::create(m_realm, "Invalid use field"_fly_string);
  487. // 6. If the key_ops field of jwk is present, and is invalid according to the requirements of JSON Web Key [JWK]
  488. // or does not contain all of the specified usages values, then throw a DataError.
  489. for (auto const& usage : usages) {
  490. if (!jwk.key_ops->contains_slow(Bindings::idl_enum_to_string(usage)))
  491. return WebIDL::DataError::create(m_realm, MUST(String::formatted("Missing key_ops field: {}", Bindings::idl_enum_to_string(usage))));
  492. }
  493. // FIXME: Validate jwk.key_ops against requirements in https://www.rfc-editor.org/rfc/rfc7517#section-4.3
  494. // 7. If the ext field of jwk is present and has the value false and extractable is true, then throw a DataError.
  495. if (jwk.ext.has_value() && !*jwk.ext && extractable)
  496. return WebIDL::DataError::create(m_realm, "Invalid ext field"_fly_string);
  497. Optional<String> hash = {};
  498. // 8. -> If the alg field of jwk is not present:
  499. if (!jwk.alg.has_value()) {
  500. // Let hash be undefined.
  501. }
  502. // -> If the alg field of jwk is equal to "RSA-OAEP":
  503. if (jwk.alg == "RSA-OAEP"sv) {
  504. // Let hash be the string "SHA-1".
  505. hash = "SHA-1"_string;
  506. }
  507. // -> If the alg field of jwk is equal to "RSA-OAEP-256":
  508. else if (jwk.alg == "RSA-OAEP-256"sv) {
  509. // Let hash be the string "SHA-256".
  510. hash = "SHA-256"_string;
  511. }
  512. // -> If the alg field of jwk is equal to "RSA-OAEP-384":
  513. else if (jwk.alg == "RSA-OAEP-384"sv) {
  514. // Let hash be the string "SHA-384".
  515. hash = "SHA-384"_string;
  516. }
  517. // -> If the alg field of jwk is equal to "RSA-OAEP-512":
  518. else if (jwk.alg == "RSA-OAEP-512"sv) {
  519. // Let hash be the string "SHA-512".
  520. hash = "SHA-512"_string;
  521. }
  522. // -> Otherwise:
  523. else {
  524. // FIXME: Support 'other applicable specifications'
  525. // 1. Perform any key import steps defined by other applicable specifications, passing format, jwk and obtaining hash.
  526. // 2. If an error occurred or there are no applicable specifications, throw a DataError.
  527. return WebIDL::DataError::create(m_realm, "Invalid alg field"_fly_string);
  528. }
  529. // 9. If hash is not undefined:
  530. if (hash.has_value()) {
  531. // 1. Let normalizedHash be the result of normalize an algorithm with alg set to hash and op set to digest.
  532. auto normalized_hash = TRY(normalize_an_algorithm(m_realm, AlgorithmIdentifier { *hash }, "digest"_string));
  533. // 2. If normalizedHash is not equal to the hash member of normalizedAlgorithm, throw a DataError.
  534. if (normalized_hash.parameter->name != TRY(normalized_algorithm.hash.visit([](String const& name) -> JS::ThrowCompletionOr<String> { return name; }, [&](JS::Handle<JS::Object> const& obj) -> JS::ThrowCompletionOr<String> {
  535. auto name_property = TRY(obj->get("name"));
  536. return name_property.to_string(m_realm.vm()); })))
  537. return WebIDL::DataError::create(m_realm, "Invalid hash"_fly_string);
  538. }
  539. // 10. -> If the d field of jwk is present:
  540. if (jwk.d.has_value()) {
  541. // 1. If jwk does not meet the requirements of Section 6.3.2 of JSON Web Algorithms [JWA], then throw a DataError.
  542. bool meets_requirements = jwk.e.has_value() && jwk.n.has_value() && jwk.d.has_value();
  543. if (jwk.p.has_value() || jwk.q.has_value() || jwk.dp.has_value() || jwk.dq.has_value() || jwk.qi.has_value())
  544. meets_requirements |= jwk.p.has_value() && jwk.q.has_value() && jwk.dp.has_value() && jwk.dq.has_value() && jwk.qi.has_value();
  545. if (jwk.oth.has_value()) {
  546. // FIXME: We don't support > 2 primes in RSA keys
  547. meets_requirements = false;
  548. }
  549. if (!meets_requirements)
  550. return WebIDL::DataError::create(m_realm, "Invalid JWK private key"_fly_string);
  551. // FIXME: Spec error, it should say 'the RSA private key identified by interpreting jwk according to section 6.3.2'
  552. // 2. Let privateKey represent the RSA public key identified by interpreting jwk according to Section 6.3.1 of JSON Web Algorithms [JWA].
  553. auto private_key = TRY(parse_jwk_rsa_private_key(realm, jwk));
  554. // FIXME: Spec error, it should say 'not to be a valid RSA private key'
  555. // 3. If privateKey can be determined to not be a valid RSA public key according to [RFC3447], then throw a DataError.
  556. // FIXME: Validate the private key
  557. // 4. Let key be a new CryptoKey representing privateKey.
  558. key = CryptoKey::create(m_realm, CryptoKey::InternalKeyData { private_key });
  559. // 5. Set the [[type]] internal slot of key to "private"
  560. key->set_type(Bindings::KeyType::Private);
  561. }
  562. // -> Otherwise:
  563. else {
  564. // 1. If jwk does not meet the requirements of Section 6.3.1 of JSON Web Algorithms [JWA], then throw a DataError.
  565. if (!jwk.e.has_value() || !jwk.n.has_value())
  566. return WebIDL::DataError::create(m_realm, "Invalid JWK public key"_fly_string);
  567. // 2. Let publicKey represent the RSA public key identified by interpreting jwk according to Section 6.3.1 of JSON Web Algorithms [JWA].
  568. auto public_key = TRY(parse_jwk_rsa_public_key(realm, jwk));
  569. // 3. If publicKey can be determined to not be a valid RSA public key according to [RFC3447], then throw a DataError.
  570. // FIXME: Validate the public key
  571. // 4. Let key be a new CryptoKey representing publicKey.
  572. key = CryptoKey::create(m_realm, CryptoKey::InternalKeyData { public_key });
  573. // 5. Set the [[type]] internal slot of key to "public"
  574. key->set_type(Bindings::KeyType::Public);
  575. }
  576. }
  577. // -> Otherwise: throw a NotSupportedError.
  578. else {
  579. return WebIDL::NotSupportedError::create(m_realm, "Unsupported key format"_fly_string);
  580. }
  581. // 3. Let algorithm be a new RsaHashedKeyAlgorithm.
  582. auto algorithm = RsaHashedKeyAlgorithm::create(m_realm);
  583. // 4. Set the name attribute of algorithm to "RSA-OAEP"
  584. algorithm->set_name("RSA-OAEP"_string);
  585. // 5. Set the modulusLength attribute of algorithm to the length, in bits, of the RSA public modulus.
  586. // 6. Set the publicExponent attribute of algorithm to the BigInteger representation of the RSA public exponent.
  587. TRY(key->handle().visit(
  588. [&](::Crypto::PK::RSAPublicKey<> const& public_key) -> WebIDL::ExceptionOr<void> {
  589. algorithm->set_modulus_length(public_key.length());
  590. TRY(algorithm->set_public_exponent(public_key.public_exponent()));
  591. return {};
  592. },
  593. [&](::Crypto::PK::RSAPrivateKey<> const& private_key) -> WebIDL::ExceptionOr<void> {
  594. algorithm->set_modulus_length(private_key.length());
  595. TRY(algorithm->set_public_exponent(private_key.public_exponent()));
  596. return {};
  597. },
  598. [](auto) -> WebIDL::ExceptionOr<void> { VERIFY_NOT_REACHED(); }));
  599. // 7. Set the hash attribute of algorithm to the hash member of normalizedAlgorithm.
  600. algorithm->set_hash(normalized_algorithm.hash);
  601. // 8. Set the [[algorithm]] internal slot of key to algorithm
  602. key->set_algorithm(algorithm);
  603. // 9. Return key.
  604. return JS::NonnullGCPtr { *key };
  605. }
  606. // https://w3c.github.io/webcrypto/#rsa-oaep-operations
  607. WebIDL::ExceptionOr<JS::NonnullGCPtr<JS::Object>> RSAOAEP::export_key(Bindings::KeyFormat format, JS::NonnullGCPtr<CryptoKey> key)
  608. {
  609. auto& realm = m_realm;
  610. auto& vm = realm.vm();
  611. // 1. Let key be the key to be exported.
  612. // 2. If the underlying cryptographic key material represented by the [[handle]] internal slot of key cannot be accessed, then throw an OperationError.
  613. // Note: In our impl this is always accessible
  614. auto const& handle = key->handle();
  615. JS::GCPtr<JS::Object> result = nullptr;
  616. // 3. If format is "spki"
  617. if (format == Bindings::KeyFormat::Spki) {
  618. // 1. If the [[type]] internal slot of key is not "public", then throw an InvalidAccessError.
  619. if (key->type() != Bindings::KeyType::Public)
  620. return WebIDL::InvalidAccessError::create(realm, "Key is not public"_fly_string);
  621. // FIXME: 2. Let data be an instance of the subjectPublicKeyInfo ASN.1 structure defined in [RFC5280] with the following properties:
  622. // - Set the algorithm field to an AlgorithmIdentifier ASN.1 type with the following properties:
  623. // - Set the algorithm field to the OID rsaEncryption defined in [RFC3447].
  624. // - Set the params field to the ASN.1 type NULL.
  625. // - Set the subjectPublicKey field to the result of DER-encoding an RSAPublicKey ASN.1 type, as defined in [RFC3447], Appendix A.1.1,
  626. // that represents the RSA public key represented by the [[handle]] internal slot of key
  627. // FIXME: 3. Let result be the result of creating an ArrayBuffer containing data.
  628. result = JS::ArrayBuffer::create(realm, TRY_OR_THROW_OOM(vm, ByteBuffer::copy(("FIXME"sv).bytes())));
  629. }
  630. // FIXME: If format is "pkcs8"
  631. // If format is "jwk"
  632. else if (format == Bindings::KeyFormat::Jwk) {
  633. // 1. Let jwk be a new JsonWebKey dictionary.
  634. Bindings::JsonWebKey jwk = {};
  635. // 2. Set the kty attribute of jwk to the string "RSA".
  636. jwk.kty = "RSA"_string;
  637. // 4. Let hash be the name attribute of the hash attribute of the [[algorithm]] internal slot of key.
  638. auto hash = TRY(verify_cast<RsaHashedKeyAlgorithm>(*key->algorithm()).hash().visit([](String const& name) -> JS::ThrowCompletionOr<String> { return name; }, [&](JS::Handle<JS::Object> const& obj) -> JS::ThrowCompletionOr<String> {
  639. auto name_property = TRY(obj->get("name"));
  640. return name_property.to_string(realm.vm()); }));
  641. // 4. If hash is "SHA-1":
  642. // - Set the alg attribute of jwk to the string "RSA-OAEP".
  643. if (hash == "SHA-1"sv) {
  644. jwk.alg = "RSA-OAEP"_string;
  645. }
  646. // If hash is "SHA-256":
  647. // - Set the alg attribute of jwk to the string "RSA-OAEP-256".
  648. else if (hash == "SHA-256"sv) {
  649. jwk.alg = "RSA-OAEP-256"_string;
  650. }
  651. // If hash is "SHA-384":
  652. // - Set the alg attribute of jwk to the string "RSA-OAEP-384".
  653. else if (hash == "SHA-384"sv) {
  654. jwk.alg = "RSA-OAEP-384"_string;
  655. }
  656. // If hash is "SHA-512":
  657. // - Set the alg attribute of jwk to the string "RSA-OAEP-512".
  658. else if (hash == "SHA-512"sv) {
  659. jwk.alg = "RSA-OAEP-512"_string;
  660. } else {
  661. // FIXME: Support 'other applicable specifications'
  662. // - Perform any key export steps defined by other applicable specifications,
  663. // passing format and the hash attribute of the [[algorithm]] internal slot of key and obtaining alg.
  664. // - Set the alg attribute of jwk to alg.
  665. return WebIDL::NotSupportedError::create(realm, TRY_OR_THROW_OOM(vm, String::formatted("Unsupported hash algorithm '{}'", hash)));
  666. }
  667. // 10. Set the attributes n and e of jwk according to the corresponding definitions in JSON Web Algorithms [JWA], Section 6.3.1.
  668. auto maybe_error = handle.visit(
  669. [&](::Crypto::PK::RSAPublicKey<> const& public_key) -> ErrorOr<void> {
  670. jwk.n = TRY(base64_url_uint_encode(public_key.modulus()));
  671. jwk.e = TRY(base64_url_uint_encode(public_key.public_exponent()));
  672. return {};
  673. },
  674. [&](::Crypto::PK::RSAPrivateKey<> const& private_key) -> ErrorOr<void> {
  675. jwk.n = TRY(base64_url_uint_encode(private_key.modulus()));
  676. jwk.e = TRY(base64_url_uint_encode(private_key.public_exponent()));
  677. // 11. If the [[type]] internal slot of key is "private":
  678. // 1. Set the attributes named d, p, q, dp, dq, and qi of jwk according to the corresponding definitions in JSON Web Algorithms [JWA], Section 6.3.2.
  679. jwk.d = TRY(base64_url_uint_encode(private_key.private_exponent()));
  680. jwk.p = TRY(base64_url_uint_encode(private_key.prime1()));
  681. jwk.q = TRY(base64_url_uint_encode(private_key.prime2()));
  682. jwk.dp = TRY(base64_url_uint_encode(private_key.exponent1()));
  683. jwk.dq = TRY(base64_url_uint_encode(private_key.exponent2()));
  684. jwk.qi = TRY(base64_url_uint_encode(private_key.coefficient()));
  685. // 12. If the underlying RSA private key represented by the [[handle]] internal slot of key is represented by more than two primes,
  686. // set the attribute named oth of jwk according to the corresponding definition in JSON Web Algorithms [JWA], Section 6.3.2.7
  687. // FIXME: We don't support more than 2 primes on RSA keys
  688. return {};
  689. },
  690. [](auto) -> ErrorOr<void> {
  691. VERIFY_NOT_REACHED();
  692. });
  693. // FIXME: clang-format butchers the visit if we do the TRY inline
  694. TRY_OR_THROW_OOM(vm, maybe_error);
  695. // 13. Set the key_ops attribute of jwk to the usages attribute of key.
  696. jwk.key_ops = Vector<String> {};
  697. jwk.key_ops->ensure_capacity(key->internal_usages().size());
  698. for (auto const& usage : key->internal_usages()) {
  699. jwk.key_ops->append(Bindings::idl_enum_to_string(usage));
  700. }
  701. // 14. Set the ext attribute of jwk to the [[extractable]] internal slot of key.
  702. jwk.ext = key->extractable();
  703. // 15. Let result be the result of converting jwk to an ECMAScript Object, as defined by [WebIDL].
  704. result = TRY(jwk.to_object(realm));
  705. }
  706. // Otherwise throw a NotSupportedError.
  707. else {
  708. return WebIDL::NotSupportedError::create(realm, TRY_OR_THROW_OOM(vm, String::formatted("Exporting to format {} is not supported", Bindings::idl_enum_to_string(format))));
  709. }
  710. // 8. Return result
  711. return JS::NonnullGCPtr { *result };
  712. }
  713. WebIDL::ExceptionOr<JS::NonnullGCPtr<CryptoKey>> PBKDF2::import_key(AlgorithmParams const&, Bindings::KeyFormat format, CryptoKey::InternalKeyData key_data, bool extractable, Vector<Bindings::KeyUsage> const& key_usages)
  714. {
  715. // 1. If format is not "raw", throw a NotSupportedError
  716. if (format != Bindings::KeyFormat::Raw) {
  717. return WebIDL::NotSupportedError::create(m_realm, "Only raw format is supported"_fly_string);
  718. }
  719. // 2. If usages contains a value that is not "deriveKey" or "deriveBits", then throw a SyntaxError.
  720. for (auto& usage : key_usages) {
  721. if (usage != Bindings::KeyUsage::Derivekey && usage != Bindings::KeyUsage::Derivebits) {
  722. return WebIDL::SyntaxError::create(m_realm, MUST(String::formatted("Invalid key usage '{}'", idl_enum_to_string(usage))));
  723. }
  724. }
  725. // 3. If extractable is not false, then throw a SyntaxError.
  726. if (extractable)
  727. return WebIDL::SyntaxError::create(m_realm, "extractable must be false"_fly_string);
  728. // 4. Let key be a new CryptoKey representing keyData.
  729. auto key = CryptoKey::create(m_realm, move(key_data));
  730. // 5. Set the [[type]] internal slot of key to "secret".
  731. key->set_type(Bindings::KeyType::Secret);
  732. // 6. Set the [[extractable]] internal slot of key to false.
  733. key->set_extractable(false);
  734. // 7. Let algorithm be a new KeyAlgorithm object.
  735. auto algorithm = KeyAlgorithm::create(m_realm);
  736. // 8. Set the name attribute of algorithm to "PBKDF2".
  737. algorithm->set_name("PBKDF2"_string);
  738. // 9. Set the [[algorithm]] internal slot of key to algorithm.
  739. key->set_algorithm(algorithm);
  740. // 10. Return key.
  741. return key;
  742. }
  743. WebIDL::ExceptionOr<JS::NonnullGCPtr<JS::ArrayBuffer>> SHA::digest(AlgorithmParams const& algorithm, ByteBuffer const& data)
  744. {
  745. auto& algorithm_name = algorithm.name;
  746. ::Crypto::Hash::HashKind hash_kind;
  747. if (algorithm_name.equals_ignoring_ascii_case("SHA-1"sv)) {
  748. hash_kind = ::Crypto::Hash::HashKind::SHA1;
  749. } else if (algorithm_name.equals_ignoring_ascii_case("SHA-256"sv)) {
  750. hash_kind = ::Crypto::Hash::HashKind::SHA256;
  751. } else if (algorithm_name.equals_ignoring_ascii_case("SHA-384"sv)) {
  752. hash_kind = ::Crypto::Hash::HashKind::SHA384;
  753. } else if (algorithm_name.equals_ignoring_ascii_case("SHA-512"sv)) {
  754. hash_kind = ::Crypto::Hash::HashKind::SHA512;
  755. } else {
  756. return WebIDL::NotSupportedError::create(m_realm, MUST(String::formatted("Invalid hash function '{}'", algorithm_name)));
  757. }
  758. ::Crypto::Hash::Manager hash { hash_kind };
  759. hash.update(data);
  760. auto digest = hash.digest();
  761. auto result_buffer = ByteBuffer::copy(digest.immutable_data(), hash.digest_size());
  762. if (result_buffer.is_error())
  763. return WebIDL::OperationError::create(m_realm, "Failed to create result buffer"_fly_string);
  764. return JS::ArrayBuffer::create(m_realm, result_buffer.release_value());
  765. }
  766. // https://w3c.github.io/webcrypto/#ecdsa-operations
  767. WebIDL::ExceptionOr<Variant<JS::NonnullGCPtr<CryptoKey>, JS::NonnullGCPtr<CryptoKeyPair>>> ECDSA::generate_key(AlgorithmParams const& params, bool extractable, Vector<Bindings::KeyUsage> const& key_usages)
  768. {
  769. // 1. If usages contains a value which is not one of "sign" or "verify", then throw a SyntaxError.
  770. for (auto const& usage : key_usages) {
  771. if (usage != Bindings::KeyUsage::Sign && usage != Bindings::KeyUsage::Verify) {
  772. return WebIDL::SyntaxError::create(m_realm, MUST(String::formatted("Invalid key usage '{}'", idl_enum_to_string(usage))));
  773. }
  774. }
  775. auto const& normalized_algorithm = static_cast<EcKeyGenParams const&>(params);
  776. // 2. If the namedCurve member of normalizedAlgorithm is "P-256", "P-384" or "P-521":
  777. // Generate an Elliptic Curve key pair, as defined in [RFC6090]
  778. // with domain parameters for the curve identified by the namedCurve member of normalizedAlgorithm.
  779. Variant<Empty, ::Crypto::Curves::SECP256r1, ::Crypto::Curves::SECP384r1> curve;
  780. if (normalized_algorithm.named_curve.is_one_of("P-256"sv, "P-384"sv, "P-521"sv)) {
  781. if (normalized_algorithm.named_curve.equals_ignoring_ascii_case("P-256"sv))
  782. curve = ::Crypto::Curves::SECP256r1 {};
  783. if (normalized_algorithm.named_curve.equals_ignoring_ascii_case("P-384"sv))
  784. curve = ::Crypto::Curves::SECP384r1 {};
  785. // FIXME: Support P-521
  786. if (normalized_algorithm.named_curve.equals_ignoring_ascii_case("P-521"sv))
  787. return WebIDL::NotSupportedError::create(m_realm, "'P-521' is not supported yet"_fly_string);
  788. } else {
  789. // If the namedCurve member of normalizedAlgorithm is a value specified in an applicable specification:
  790. // Perform the ECDSA generation steps specified in that specification,
  791. // passing in normalizedAlgorithm and resulting in an elliptic curve key pair.
  792. // Otherwise: throw a NotSupportedError
  793. return WebIDL::NotSupportedError::create(m_realm, "Only 'P-256', 'P-384' and 'P-521' is supported"_fly_string);
  794. }
  795. // NOTE: Spec jumps to 6 here for some reason
  796. // 6. If performing the key generation operation results in an error, then throw an OperationError.
  797. auto maybe_private_key_data = curve.visit(
  798. [](Empty const&) -> ErrorOr<ByteBuffer> { return Error::from_string_view("noop error"sv); },
  799. [](auto instance) { return instance.generate_private_key(); });
  800. if (maybe_private_key_data.is_error())
  801. return WebIDL::OperationError::create(m_realm, "Failed to create valid crypto instance"_fly_string);
  802. auto private_key_data = maybe_private_key_data.release_value();
  803. auto maybe_public_key_data = curve.visit(
  804. [](Empty const&) -> ErrorOr<ByteBuffer> { return Error::from_string_view("noop error"sv); },
  805. [&](auto instance) { return instance.generate_public_key(private_key_data); });
  806. if (maybe_public_key_data.is_error())
  807. return WebIDL::OperationError::create(m_realm, "Failed to create valid crypto instance"_fly_string);
  808. auto public_key_data = maybe_public_key_data.release_value();
  809. // 7. Let algorithm be a new EcKeyAlgorithm object.
  810. auto algorithm = EcKeyAlgorithm::create(m_realm);
  811. // 8. Set the name attribute of algorithm to "ECDSA".
  812. algorithm->set_name("ECDSA"_string);
  813. // 9. Set the namedCurve attribute of algorithm to equal the namedCurve member of normalizedAlgorithm.
  814. algorithm->set_named_curve(normalized_algorithm.named_curve);
  815. // 10. Let publicKey be a new CryptoKey representing the public key of the generated key pair.
  816. auto public_key = CryptoKey::create(m_realm, CryptoKey::InternalKeyData { public_key_data });
  817. // 11. Set the [[type]] internal slot of publicKey to "public"
  818. public_key->set_type(Bindings::KeyType::Public);
  819. // 12. Set the [[algorithm]] internal slot of publicKey to algorithm.
  820. public_key->set_algorithm(algorithm);
  821. // 13. Set the [[extractable]] internal slot of publicKey to true.
  822. public_key->set_extractable(true);
  823. // 14. Set the [[usages]] internal slot of publicKey to be the usage intersection of usages and [ "verify" ].
  824. public_key->set_usages(usage_intersection(key_usages, { { Bindings::KeyUsage::Verify } }));
  825. // 15. Let privateKey be a new CryptoKey representing the private key of the generated key pair.
  826. auto private_key = CryptoKey::create(m_realm, CryptoKey::InternalKeyData { private_key_data });
  827. // 16. Set the [[type]] internal slot of privateKey to "private"
  828. private_key->set_type(Bindings::KeyType::Private);
  829. // 17. Set the [[algorithm]] internal slot of privateKey to algorithm.
  830. private_key->set_algorithm(algorithm);
  831. // 18. Set the [[extractable]] internal slot of privateKey to extractable.
  832. private_key->set_extractable(extractable);
  833. // 19. Set the [[usages]] internal slot of privateKey to be the usage intersection of usages and [ "sign" ].
  834. private_key->set_usages(usage_intersection(key_usages, { { Bindings::KeyUsage::Sign } }));
  835. // 20. Let result be a new CryptoKeyPair dictionary.
  836. // 21. Set the publicKey attribute of result to be publicKey.
  837. // 22. Set the privateKey attribute of result to be privateKey.
  838. // 23. Return the result of converting result to an ECMAScript Object, as defined by [WebIDL].
  839. return Variant<JS::NonnullGCPtr<CryptoKey>, JS::NonnullGCPtr<CryptoKeyPair>> { CryptoKeyPair::create(m_realm, public_key, private_key) };
  840. }
  841. // https://w3c.github.io/webcrypto/#ecdsa-operations
  842. WebIDL::ExceptionOr<JS::NonnullGCPtr<JS::ArrayBuffer>> ECDSA::sign(AlgorithmParams const& params, JS::NonnullGCPtr<CryptoKey> key, ByteBuffer const& message)
  843. {
  844. auto& realm = m_realm;
  845. auto& vm = realm.vm();
  846. auto const& normalized_algorithm = static_cast<EcdsaParams const&>(params);
  847. (void)vm;
  848. (void)message;
  849. // 1. If the [[type]] internal slot of key is not "private", then throw an InvalidAccessError.
  850. if (key->type() != Bindings::KeyType::Private)
  851. return WebIDL::InvalidAccessError::create(realm, "Key is not a private key"_fly_string);
  852. // 2. Let hashAlgorithm be the hash member of normalizedAlgorithm.
  853. [[maybe_unused]] auto const& hash_algorithm = normalized_algorithm.hash;
  854. // NOTE: We dont have sign() on the SECPxxxr1 curves, so we can't implement this yet
  855. // FIXME: 3. Let M be the result of performing the digest operation specified by hashAlgorithm using message.
  856. // FIXME: 4. Let d be the ECDSA private key associated with key.
  857. // FIXME: 5. Let params be the EC domain parameters associated with key.
  858. // FIXME: 6. If the namedCurve attribute of the [[algorithm]] internal slot of key is "P-256", "P-384" or "P-521":
  859. // FIXME: 1. Perform the ECDSA signing process, as specified in [RFC6090], Section 5.4, with M as the message, using params as the EC domain parameters, and with d as the private key.
  860. // FIXME: 2. Let r and s be the pair of integers resulting from performing the ECDSA signing process.
  861. // FIXME: 3. Let result be an empty byte sequence.
  862. // FIXME: 4. Let n be the smallest integer such that n * 8 is greater than the logarithm to base 2 of the order of the base point of the elliptic curve identified by params.
  863. // FIXME: 5. Convert r to an octet string of length n and append this sequence of bytes to result.
  864. // FIXME: 6. Convert s to an octet string of length n and append this sequence of bytes to result.
  865. // FIXME: Otherwise, the namedCurve attribute of the [[algorithm]] internal slot of key is a value specified in an applicable specification:
  866. // FIXME: Perform the ECDSA signature steps specified in that specification, passing in M, params and d and resulting in result.
  867. // NOTE: The spec jumps to 9 here for some reason
  868. // FIXME: 9. Return the result of creating an ArrayBuffer containing result.
  869. return WebIDL::NotSupportedError::create(realm, "ECDSA signing is not supported yet"_fly_string);
  870. }
  871. // https://w3c.github.io/webcrypto/#ecdsa-operations
  872. WebIDL::ExceptionOr<JS::Value> ECDSA::verify(AlgorithmParams const& params, JS::NonnullGCPtr<CryptoKey> key, ByteBuffer const& signature, ByteBuffer const& message)
  873. {
  874. auto& realm = m_realm;
  875. auto const& normalized_algorithm = static_cast<EcdsaParams const&>(params);
  876. // 1. If the [[type]] internal slot of key is not "public", then throw an InvalidAccessError.
  877. if (key->type() != Bindings::KeyType::Public)
  878. return WebIDL::InvalidAccessError::create(realm, "Key is not a public key"_fly_string);
  879. // 2. Let hashAlgorithm be the hash member of normalizedAlgorithm.
  880. [[maybe_unused]] auto const& hash_algorithm = TRY(normalized_algorithm.hash.visit(
  881. [](String const& name) -> JS::ThrowCompletionOr<String> { return name; },
  882. [&](JS::Handle<JS::Object> const& obj) -> JS::ThrowCompletionOr<String> {
  883. auto name_property = TRY(obj->get("name"));
  884. return name_property.to_string(m_realm.vm()); }));
  885. // 3. Let M be the result of performing the digest operation specified by hashAlgorithm using message.
  886. ::Crypto::Hash::HashKind hash_kind;
  887. if (hash_algorithm.equals_ignoring_ascii_case("SHA-1"sv)) {
  888. hash_kind = ::Crypto::Hash::HashKind::SHA1;
  889. } else if (hash_algorithm.equals_ignoring_ascii_case("SHA-256"sv)) {
  890. hash_kind = ::Crypto::Hash::HashKind::SHA256;
  891. } else if (hash_algorithm.equals_ignoring_ascii_case("SHA-384"sv)) {
  892. hash_kind = ::Crypto::Hash::HashKind::SHA384;
  893. } else if (hash_algorithm.equals_ignoring_ascii_case("SHA-512"sv)) {
  894. hash_kind = ::Crypto::Hash::HashKind::SHA512;
  895. } else {
  896. return WebIDL::NotSupportedError::create(m_realm, MUST(String::formatted("Invalid hash function '{}'", hash_algorithm)));
  897. }
  898. ::Crypto::Hash::Manager hash { hash_kind };
  899. hash.update(message);
  900. auto digest = hash.digest();
  901. auto result_buffer = ByteBuffer::copy(digest.immutable_data(), hash.digest_size());
  902. if (result_buffer.is_error())
  903. return WebIDL::OperationError::create(m_realm, "Failed to create result buffer"_fly_string);
  904. auto M = result_buffer.release_value();
  905. // 4. Let Q be the ECDSA public key associated with key.
  906. auto Q = key->handle().visit(
  907. [](ByteBuffer data) -> ByteBuffer {
  908. return data;
  909. },
  910. [](auto) -> ByteBuffer { VERIFY_NOT_REACHED(); });
  911. // FIXME: 5. Let params be the EC domain parameters associated with key.
  912. // 6. If the namedCurve attribute of the [[algorithm]] internal slot of key is "P-256", "P-384" or "P-521":
  913. auto const& internal_algorithm = static_cast<EcKeyAlgorithm const&>(*key->algorithm());
  914. auto const& named_curve = internal_algorithm.named_curve();
  915. auto result = false;
  916. Variant<Empty, ::Crypto::Curves::SECP256r1, ::Crypto::Curves::SECP384r1> curve;
  917. if (named_curve.is_one_of("P-256"sv, "P-384"sv, "P-521"sv)) {
  918. if (named_curve.equals_ignoring_ascii_case("P-256"sv))
  919. curve = ::Crypto::Curves::SECP256r1 {};
  920. if (named_curve.equals_ignoring_ascii_case("P-384"sv))
  921. curve = ::Crypto::Curves::SECP384r1 {};
  922. // FIXME: Support P-521
  923. if (named_curve.equals_ignoring_ascii_case("P-521"sv))
  924. return WebIDL::NotSupportedError::create(m_realm, "'P-521' is not supported yet"_fly_string);
  925. // Perform the ECDSA verifying process, as specified in [RFC6090], Section 5.3,
  926. // with M as the received message,
  927. // signature as the received signature
  928. // and using params as the EC domain parameters,
  929. // and Q as the public key.
  930. // NOTE: verify() takes the signature in X.509 format but JS uses IEEE P1363 format, so we need to convert it
  931. // FIXME: Dont construct an ASN1 object here just to pass it to verify
  932. auto half_size = signature.size() / 2;
  933. auto r = ::Crypto::UnsignedBigInteger::import_data(signature.data(), half_size);
  934. auto s = ::Crypto::UnsignedBigInteger::import_data(signature.data() + half_size, half_size);
  935. ::Crypto::ASN1::Encoder encoder;
  936. (void)encoder.write_constructed(::Crypto::ASN1::Class::Universal, ::Crypto::ASN1::Kind::Sequence, [&] {
  937. (void)encoder.write(r);
  938. (void)encoder.write(s);
  939. });
  940. auto encoded_signature = encoder.finish();
  941. auto maybe_result = curve.visit(
  942. [](Empty const&) -> ErrorOr<bool> { return Error::from_string_view("Failed to create valid crypto instance"sv); },
  943. [&](auto instance) { return instance.verify(M, Q, encoded_signature); });
  944. if (maybe_result.is_error()) {
  945. auto error_message = MUST(FlyString::from_utf8(maybe_result.error().string_literal()));
  946. return WebIDL::OperationError::create(m_realm, error_message);
  947. }
  948. result = maybe_result.release_value();
  949. } else {
  950. // FIXME: Otherwise, the namedCurve attribute of the [[algorithm]] internal slot of key is a value specified in an applicable specification:
  951. // FIXME: Perform the ECDSA verification steps specified in that specification passing in M, signature, params and Q and resulting in an indication of whether or not the purported signature is valid.
  952. }
  953. // 9. Let result be a boolean with the value true if the signature is valid and the value false otherwise.
  954. // 10. Return result.
  955. return JS::Value(result);
  956. }
  957. // https://wicg.github.io/webcrypto-secure-curves/#ed25519-operations
  958. WebIDL::ExceptionOr<Variant<JS::NonnullGCPtr<CryptoKey>, JS::NonnullGCPtr<CryptoKeyPair>>> ED25519::generate_key([[maybe_unused]] AlgorithmParams const& params, bool extractable, Vector<Bindings::KeyUsage> const& key_usages)
  959. {
  960. // 1. If usages contains a value which is not one of "sign" or "verify", then throw a SyntaxError.
  961. for (auto const& usage : key_usages) {
  962. if (usage != Bindings::KeyUsage::Sign && usage != Bindings::KeyUsage::Verify) {
  963. return WebIDL::SyntaxError::create(m_realm, MUST(String::formatted("Invalid key usage '{}'", idl_enum_to_string(usage))));
  964. }
  965. }
  966. // 2. Generate an Ed25519 key pair, as defined in [RFC8032], section 5.1.5.
  967. ::Crypto::Curves::Ed25519 curve;
  968. auto maybe_private_key = curve.generate_private_key();
  969. if (maybe_private_key.is_error())
  970. return WebIDL::OperationError::create(m_realm, "Failed to generate private key"_fly_string);
  971. auto private_key_data = maybe_private_key.release_value();
  972. auto maybe_public_key = curve.generate_public_key(private_key_data);
  973. if (maybe_public_key.is_error())
  974. return WebIDL::OperationError::create(m_realm, "Failed to generate public key"_fly_string);
  975. auto public_key_data = maybe_public_key.release_value();
  976. // 3. Let algorithm be a new KeyAlgorithm object.
  977. auto algorithm = KeyAlgorithm::create(m_realm);
  978. // 4. Set the name attribute of algorithm to "Ed25519".
  979. algorithm->set_name("Ed25519"_string);
  980. // 5. Let publicKey be a new CryptoKey associated with the relevant global object of this [HTML],
  981. // and representing the public key of the generated key pair.
  982. auto public_key = CryptoKey::create(m_realm, CryptoKey::InternalKeyData { public_key_data });
  983. // 6. Set the [[type]] internal slot of publicKey to "public"
  984. public_key->set_type(Bindings::KeyType::Public);
  985. // 7. Set the [[algorithm]] internal slot of publicKey to algorithm.
  986. public_key->set_algorithm(algorithm);
  987. // 8. Set the [[extractable]] internal slot of publicKey to true.
  988. public_key->set_extractable(true);
  989. // 9. Set the [[usages]] internal slot of publicKey to be the usage intersection of usages and [ "verify" ].
  990. public_key->set_usages(usage_intersection(key_usages, { { Bindings::KeyUsage::Verify } }));
  991. // 10. Let privateKey be a new CryptoKey associated with the relevant global object of this [HTML],
  992. // and representing the private key of the generated key pair.
  993. auto private_key = CryptoKey::create(m_realm, CryptoKey::InternalKeyData { private_key_data });
  994. // 11. Set the [[type]] internal slot of privateKey to "private"
  995. private_key->set_type(Bindings::KeyType::Private);
  996. // 12. Set the [[algorithm]] internal slot of privateKey to algorithm.
  997. private_key->set_algorithm(algorithm);
  998. // 13. Set the [[extractable]] internal slot of privateKey to extractable.
  999. private_key->set_extractable(extractable);
  1000. // 14. Set the [[usages]] internal slot of privateKey to be the usage intersection of usages and [ "sign" ].
  1001. private_key->set_usages(usage_intersection(key_usages, { { Bindings::KeyUsage::Sign } }));
  1002. // 15. Let result be a new CryptoKeyPair dictionary.
  1003. // 16. Set the publicKey attribute of result to be publicKey.
  1004. // 17. Set the privateKey attribute of result to be privateKey.
  1005. // 18. Return the result of converting result to an ECMAScript Object, as defined by [WebIDL].
  1006. return Variant<JS::NonnullGCPtr<CryptoKey>, JS::NonnullGCPtr<CryptoKeyPair>> { CryptoKeyPair::create(m_realm, public_key, private_key) };
  1007. }
  1008. }