CryptoAlgorithms.cpp 71 KB

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