CryptoAlgorithms.cpp 73 KB

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