CryptoAlgorithms.cpp 73 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445
  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. // 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. auto maybe_data = handle.visit(
  625. [&](::Crypto::PK::RSAPublicKey<> const& public_key) -> ErrorOr<ByteBuffer> {
  626. auto rsa_encryption_oid = Array<int, 7> { 1, 2, 840, 113549, 1, 1, 1 };
  627. return TRY(::Crypto::PK::wrap_in_subject_public_key_info(public_key, rsa_encryption_oid));
  628. },
  629. [](auto) -> ErrorOr<ByteBuffer> {
  630. VERIFY_NOT_REACHED();
  631. });
  632. // FIXME: clang-format butchers the visit if we do the TRY inline
  633. auto data = TRY_OR_THROW_OOM(vm, maybe_data);
  634. // 3. Let result be the result of creating an ArrayBuffer containing data.
  635. result = JS::ArrayBuffer::create(realm, data);
  636. }
  637. // If format is "pkcs8"
  638. else if (format == Bindings::KeyFormat::Pkcs8) {
  639. // 1. If the [[type]] internal slot of key is not "private", then throw an InvalidAccessError.
  640. if (key->type() != Bindings::KeyType::Private)
  641. return WebIDL::InvalidAccessError::create(realm, "Key is not private"_fly_string);
  642. // 2. Let data be the result of encoding a privateKeyInfo structure with the following properties:
  643. // - Set the version field to 0.
  644. // - Set the privateKeyAlgorithm field to an PrivateKeyAlgorithmIdentifier ASN.1 type with the following properties:
  645. // - - Set the algorithm field to the OID rsaEncryption defined in [RFC3447].
  646. // - - Set the params field to the ASN.1 type NULL.
  647. // - Set the privateKey field to the result of DER-encoding an RSAPrivateKey ASN.1 type, as defined in [RFC3447], Appendix A.1.2,
  648. // that represents the RSA private key represented by the [[handle]] internal slot of key
  649. auto maybe_data = handle.visit(
  650. [&](::Crypto::PK::RSAPrivateKey<> const& private_key) -> ErrorOr<ByteBuffer> {
  651. auto rsa_encryption_oid = Array<int, 7> { 1, 2, 840, 113549, 1, 1, 1 };
  652. return TRY(::Crypto::PK::wrap_in_private_key_info(private_key, rsa_encryption_oid));
  653. },
  654. [](auto) -> ErrorOr<ByteBuffer> {
  655. VERIFY_NOT_REACHED();
  656. });
  657. // FIXME: clang-format butchers the visit if we do the TRY inline
  658. auto data = TRY_OR_THROW_OOM(vm, maybe_data);
  659. // 3. Let result be the result of creating an ArrayBuffer containing data.
  660. result = JS::ArrayBuffer::create(realm, data);
  661. }
  662. // If format is "jwk"
  663. else if (format == Bindings::KeyFormat::Jwk) {
  664. // 1. Let jwk be a new JsonWebKey dictionary.
  665. Bindings::JsonWebKey jwk = {};
  666. // 2. Set the kty attribute of jwk to the string "RSA".
  667. jwk.kty = "RSA"_string;
  668. // 4. Let hash be the name attribute of the hash attribute of the [[algorithm]] internal slot of key.
  669. 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> {
  670. auto name_property = TRY(obj->get("name"));
  671. return name_property.to_string(realm.vm()); }));
  672. // 4. If hash is "SHA-1":
  673. // - Set the alg attribute of jwk to the string "RSA-OAEP".
  674. if (hash == "SHA-1"sv) {
  675. jwk.alg = "RSA-OAEP"_string;
  676. }
  677. // If hash is "SHA-256":
  678. // - Set the alg attribute of jwk to the string "RSA-OAEP-256".
  679. else if (hash == "SHA-256"sv) {
  680. jwk.alg = "RSA-OAEP-256"_string;
  681. }
  682. // If hash is "SHA-384":
  683. // - Set the alg attribute of jwk to the string "RSA-OAEP-384".
  684. else if (hash == "SHA-384"sv) {
  685. jwk.alg = "RSA-OAEP-384"_string;
  686. }
  687. // If hash is "SHA-512":
  688. // - Set the alg attribute of jwk to the string "RSA-OAEP-512".
  689. else if (hash == "SHA-512"sv) {
  690. jwk.alg = "RSA-OAEP-512"_string;
  691. } else {
  692. // FIXME: Support 'other applicable specifications'
  693. // - Perform any key export steps defined by other applicable specifications,
  694. // passing format and the hash attribute of the [[algorithm]] internal slot of key and obtaining alg.
  695. // - Set the alg attribute of jwk to alg.
  696. return WebIDL::NotSupportedError::create(realm, TRY_OR_THROW_OOM(vm, String::formatted("Unsupported hash algorithm '{}'", hash)));
  697. }
  698. // 10. Set the attributes n and e of jwk according to the corresponding definitions in JSON Web Algorithms [JWA], Section 6.3.1.
  699. auto maybe_error = handle.visit(
  700. [&](::Crypto::PK::RSAPublicKey<> const& public_key) -> ErrorOr<void> {
  701. jwk.n = TRY(base64_url_uint_encode(public_key.modulus()));
  702. jwk.e = TRY(base64_url_uint_encode(public_key.public_exponent()));
  703. return {};
  704. },
  705. [&](::Crypto::PK::RSAPrivateKey<> const& private_key) -> ErrorOr<void> {
  706. jwk.n = TRY(base64_url_uint_encode(private_key.modulus()));
  707. jwk.e = TRY(base64_url_uint_encode(private_key.public_exponent()));
  708. // 11. If the [[type]] internal slot of key is "private":
  709. // 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.
  710. jwk.d = TRY(base64_url_uint_encode(private_key.private_exponent()));
  711. jwk.p = TRY(base64_url_uint_encode(private_key.prime1()));
  712. jwk.q = TRY(base64_url_uint_encode(private_key.prime2()));
  713. jwk.dp = TRY(base64_url_uint_encode(private_key.exponent1()));
  714. jwk.dq = TRY(base64_url_uint_encode(private_key.exponent2()));
  715. jwk.qi = TRY(base64_url_uint_encode(private_key.coefficient()));
  716. // 12. If the underlying RSA private key represented by the [[handle]] internal slot of key is represented by more than two primes,
  717. // set the attribute named oth of jwk according to the corresponding definition in JSON Web Algorithms [JWA], Section 6.3.2.7
  718. // FIXME: We don't support more than 2 primes on RSA keys
  719. return {};
  720. },
  721. [](auto) -> ErrorOr<void> {
  722. VERIFY_NOT_REACHED();
  723. });
  724. // FIXME: clang-format butchers the visit if we do the TRY inline
  725. TRY_OR_THROW_OOM(vm, maybe_error);
  726. // 13. Set the key_ops attribute of jwk to the usages attribute of key.
  727. jwk.key_ops = Vector<String> {};
  728. jwk.key_ops->ensure_capacity(key->internal_usages().size());
  729. for (auto const& usage : key->internal_usages()) {
  730. jwk.key_ops->append(Bindings::idl_enum_to_string(usage));
  731. }
  732. // 14. Set the ext attribute of jwk to the [[extractable]] internal slot of key.
  733. jwk.ext = key->extractable();
  734. // 15. Let result be the result of converting jwk to an ECMAScript Object, as defined by [WebIDL].
  735. result = TRY(jwk.to_object(realm));
  736. }
  737. // Otherwise throw a NotSupportedError.
  738. else {
  739. return WebIDL::NotSupportedError::create(realm, TRY_OR_THROW_OOM(vm, String::formatted("Exporting to format {} is not supported", Bindings::idl_enum_to_string(format))));
  740. }
  741. // 8. Return result
  742. return JS::NonnullGCPtr { *result };
  743. }
  744. 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)
  745. {
  746. // 1. If format is not "raw", throw a NotSupportedError
  747. if (format != Bindings::KeyFormat::Raw) {
  748. return WebIDL::NotSupportedError::create(m_realm, "Only raw format is supported"_fly_string);
  749. }
  750. // 2. If usages contains a value that is not "deriveKey" or "deriveBits", then throw a SyntaxError.
  751. for (auto& usage : key_usages) {
  752. if (usage != Bindings::KeyUsage::Derivekey && usage != Bindings::KeyUsage::Derivebits) {
  753. return WebIDL::SyntaxError::create(m_realm, MUST(String::formatted("Invalid key usage '{}'", idl_enum_to_string(usage))));
  754. }
  755. }
  756. // 3. If extractable is not false, then throw a SyntaxError.
  757. if (extractable)
  758. return WebIDL::SyntaxError::create(m_realm, "extractable must be false"_fly_string);
  759. // 4. Let key be a new CryptoKey representing keyData.
  760. auto key = CryptoKey::create(m_realm, move(key_data));
  761. // 5. Set the [[type]] internal slot of key to "secret".
  762. key->set_type(Bindings::KeyType::Secret);
  763. // 6. Set the [[extractable]] internal slot of key to false.
  764. key->set_extractable(false);
  765. // 7. Let algorithm be a new KeyAlgorithm object.
  766. auto algorithm = KeyAlgorithm::create(m_realm);
  767. // 8. Set the name attribute of algorithm to "PBKDF2".
  768. algorithm->set_name("PBKDF2"_string);
  769. // 9. Set the [[algorithm]] internal slot of key to algorithm.
  770. key->set_algorithm(algorithm);
  771. // 10. Return key.
  772. return key;
  773. }
  774. WebIDL::ExceptionOr<JS::NonnullGCPtr<JS::ArrayBuffer>> SHA::digest(AlgorithmParams const& algorithm, ByteBuffer const& data)
  775. {
  776. auto& algorithm_name = algorithm.name;
  777. ::Crypto::Hash::HashKind hash_kind;
  778. if (algorithm_name.equals_ignoring_ascii_case("SHA-1"sv)) {
  779. hash_kind = ::Crypto::Hash::HashKind::SHA1;
  780. } else if (algorithm_name.equals_ignoring_ascii_case("SHA-256"sv)) {
  781. hash_kind = ::Crypto::Hash::HashKind::SHA256;
  782. } else if (algorithm_name.equals_ignoring_ascii_case("SHA-384"sv)) {
  783. hash_kind = ::Crypto::Hash::HashKind::SHA384;
  784. } else if (algorithm_name.equals_ignoring_ascii_case("SHA-512"sv)) {
  785. hash_kind = ::Crypto::Hash::HashKind::SHA512;
  786. } else {
  787. return WebIDL::NotSupportedError::create(m_realm, MUST(String::formatted("Invalid hash function '{}'", algorithm_name)));
  788. }
  789. ::Crypto::Hash::Manager hash { hash_kind };
  790. hash.update(data);
  791. auto digest = hash.digest();
  792. auto result_buffer = ByteBuffer::copy(digest.immutable_data(), hash.digest_size());
  793. if (result_buffer.is_error())
  794. return WebIDL::OperationError::create(m_realm, "Failed to create result buffer"_fly_string);
  795. return JS::ArrayBuffer::create(m_realm, result_buffer.release_value());
  796. }
  797. // https://w3c.github.io/webcrypto/#ecdsa-operations
  798. WebIDL::ExceptionOr<Variant<JS::NonnullGCPtr<CryptoKey>, JS::NonnullGCPtr<CryptoKeyPair>>> ECDSA::generate_key(AlgorithmParams const& params, bool extractable, Vector<Bindings::KeyUsage> const& key_usages)
  799. {
  800. // 1. If usages contains a value which is not one of "sign" or "verify", then throw a SyntaxError.
  801. for (auto const& usage : key_usages) {
  802. if (usage != Bindings::KeyUsage::Sign && usage != Bindings::KeyUsage::Verify) {
  803. return WebIDL::SyntaxError::create(m_realm, MUST(String::formatted("Invalid key usage '{}'", idl_enum_to_string(usage))));
  804. }
  805. }
  806. auto const& normalized_algorithm = static_cast<EcKeyGenParams const&>(params);
  807. // 2. If the namedCurve member of normalizedAlgorithm is "P-256", "P-384" or "P-521":
  808. // Generate an Elliptic Curve key pair, as defined in [RFC6090]
  809. // with domain parameters for the curve identified by the namedCurve member of normalizedAlgorithm.
  810. Variant<Empty, ::Crypto::Curves::SECP256r1, ::Crypto::Curves::SECP384r1> curve;
  811. if (normalized_algorithm.named_curve.is_one_of("P-256"sv, "P-384"sv, "P-521"sv)) {
  812. if (normalized_algorithm.named_curve.equals_ignoring_ascii_case("P-256"sv))
  813. curve = ::Crypto::Curves::SECP256r1 {};
  814. if (normalized_algorithm.named_curve.equals_ignoring_ascii_case("P-384"sv))
  815. curve = ::Crypto::Curves::SECP384r1 {};
  816. // FIXME: Support P-521
  817. if (normalized_algorithm.named_curve.equals_ignoring_ascii_case("P-521"sv))
  818. return WebIDL::NotSupportedError::create(m_realm, "'P-521' is not supported yet"_fly_string);
  819. } else {
  820. // If the namedCurve member of normalizedAlgorithm is a value specified in an applicable specification:
  821. // Perform the ECDSA generation steps specified in that specification,
  822. // passing in normalizedAlgorithm and resulting in an elliptic curve key pair.
  823. // Otherwise: throw a NotSupportedError
  824. return WebIDL::NotSupportedError::create(m_realm, "Only 'P-256', 'P-384' and 'P-521' is supported"_fly_string);
  825. }
  826. // NOTE: Spec jumps to 6 here for some reason
  827. // 6. If performing the key generation operation results in an error, then throw an OperationError.
  828. auto maybe_private_key_data = curve.visit(
  829. [](Empty const&) -> ErrorOr<ByteBuffer> { return Error::from_string_view("noop error"sv); },
  830. [](auto instance) { return instance.generate_private_key(); });
  831. if (maybe_private_key_data.is_error())
  832. return WebIDL::OperationError::create(m_realm, "Failed to create valid crypto instance"_fly_string);
  833. auto private_key_data = maybe_private_key_data.release_value();
  834. auto maybe_public_key_data = curve.visit(
  835. [](Empty const&) -> ErrorOr<ByteBuffer> { return Error::from_string_view("noop error"sv); },
  836. [&](auto instance) { return instance.generate_public_key(private_key_data); });
  837. if (maybe_public_key_data.is_error())
  838. return WebIDL::OperationError::create(m_realm, "Failed to create valid crypto instance"_fly_string);
  839. auto public_key_data = maybe_public_key_data.release_value();
  840. // 7. Let algorithm be a new EcKeyAlgorithm object.
  841. auto algorithm = EcKeyAlgorithm::create(m_realm);
  842. // 8. Set the name attribute of algorithm to "ECDSA".
  843. algorithm->set_name("ECDSA"_string);
  844. // 9. Set the namedCurve attribute of algorithm to equal the namedCurve member of normalizedAlgorithm.
  845. algorithm->set_named_curve(normalized_algorithm.named_curve);
  846. // 10. Let publicKey be a new CryptoKey representing the public key of the generated key pair.
  847. auto public_key = CryptoKey::create(m_realm, CryptoKey::InternalKeyData { public_key_data });
  848. // 11. Set the [[type]] internal slot of publicKey to "public"
  849. public_key->set_type(Bindings::KeyType::Public);
  850. // 12. Set the [[algorithm]] internal slot of publicKey to algorithm.
  851. public_key->set_algorithm(algorithm);
  852. // 13. Set the [[extractable]] internal slot of publicKey to true.
  853. public_key->set_extractable(true);
  854. // 14. Set the [[usages]] internal slot of publicKey to be the usage intersection of usages and [ "verify" ].
  855. public_key->set_usages(usage_intersection(key_usages, { { Bindings::KeyUsage::Verify } }));
  856. // 15. Let privateKey be a new CryptoKey representing the private key of the generated key pair.
  857. auto private_key = CryptoKey::create(m_realm, CryptoKey::InternalKeyData { private_key_data });
  858. // 16. Set the [[type]] internal slot of privateKey to "private"
  859. private_key->set_type(Bindings::KeyType::Private);
  860. // 17. Set the [[algorithm]] internal slot of privateKey to algorithm.
  861. private_key->set_algorithm(algorithm);
  862. // 18. Set the [[extractable]] internal slot of privateKey to extractable.
  863. private_key->set_extractable(extractable);
  864. // 19. Set the [[usages]] internal slot of privateKey to be the usage intersection of usages and [ "sign" ].
  865. private_key->set_usages(usage_intersection(key_usages, { { Bindings::KeyUsage::Sign } }));
  866. // 20. Let result be a new CryptoKeyPair dictionary.
  867. // 21. Set the publicKey attribute of result to be publicKey.
  868. // 22. Set the privateKey attribute of result to be privateKey.
  869. // 23. Return the result of converting result to an ECMAScript Object, as defined by [WebIDL].
  870. return Variant<JS::NonnullGCPtr<CryptoKey>, JS::NonnullGCPtr<CryptoKeyPair>> { CryptoKeyPair::create(m_realm, public_key, private_key) };
  871. }
  872. // https://w3c.github.io/webcrypto/#ecdsa-operations
  873. WebIDL::ExceptionOr<JS::NonnullGCPtr<JS::ArrayBuffer>> ECDSA::sign(AlgorithmParams const& params, JS::NonnullGCPtr<CryptoKey> key, ByteBuffer const& message)
  874. {
  875. auto& realm = m_realm;
  876. auto& vm = realm.vm();
  877. auto const& normalized_algorithm = static_cast<EcdsaParams const&>(params);
  878. (void)vm;
  879. (void)message;
  880. // 1. If the [[type]] internal slot of key is not "private", then throw an InvalidAccessError.
  881. if (key->type() != Bindings::KeyType::Private)
  882. return WebIDL::InvalidAccessError::create(realm, "Key is not a private key"_fly_string);
  883. // 2. Let hashAlgorithm be the hash member of normalizedAlgorithm.
  884. [[maybe_unused]] auto const& hash_algorithm = normalized_algorithm.hash;
  885. // NOTE: We dont have sign() on the SECPxxxr1 curves, so we can't implement this yet
  886. // FIXME: 3. Let M be the result of performing the digest operation specified by hashAlgorithm using message.
  887. // FIXME: 4. Let d be the ECDSA private key associated with key.
  888. // FIXME: 5. Let params be the EC domain parameters associated with key.
  889. // FIXME: 6. If the namedCurve attribute of the [[algorithm]] internal slot of key is "P-256", "P-384" or "P-521":
  890. // 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.
  891. // FIXME: 2. Let r and s be the pair of integers resulting from performing the ECDSA signing process.
  892. // FIXME: 3. Let result be an empty byte sequence.
  893. // 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.
  894. // FIXME: 5. Convert r to an octet string of length n and append this sequence of bytes to result.
  895. // FIXME: 6. Convert s to an octet string of length n and append this sequence of bytes to result.
  896. // FIXME: Otherwise, the namedCurve attribute of the [[algorithm]] internal slot of key is a value specified in an applicable specification:
  897. // FIXME: Perform the ECDSA signature steps specified in that specification, passing in M, params and d and resulting in result.
  898. // NOTE: The spec jumps to 9 here for some reason
  899. // FIXME: 9. Return the result of creating an ArrayBuffer containing result.
  900. return WebIDL::NotSupportedError::create(realm, "ECDSA signing is not supported yet"_fly_string);
  901. }
  902. // https://w3c.github.io/webcrypto/#ecdsa-operations
  903. WebIDL::ExceptionOr<JS::Value> ECDSA::verify(AlgorithmParams const& params, JS::NonnullGCPtr<CryptoKey> key, ByteBuffer const& signature, ByteBuffer const& message)
  904. {
  905. auto& realm = m_realm;
  906. auto const& normalized_algorithm = static_cast<EcdsaParams const&>(params);
  907. // 1. If the [[type]] internal slot of key is not "public", then throw an InvalidAccessError.
  908. if (key->type() != Bindings::KeyType::Public)
  909. return WebIDL::InvalidAccessError::create(realm, "Key is not a public key"_fly_string);
  910. // 2. Let hashAlgorithm be the hash member of normalizedAlgorithm.
  911. [[maybe_unused]] auto const& hash_algorithm = TRY(normalized_algorithm.hash.visit(
  912. [](String const& name) -> JS::ThrowCompletionOr<String> { return name; },
  913. [&](JS::Handle<JS::Object> const& obj) -> JS::ThrowCompletionOr<String> {
  914. auto name_property = TRY(obj->get("name"));
  915. return name_property.to_string(m_realm.vm()); }));
  916. // 3. Let M be the result of performing the digest operation specified by hashAlgorithm using message.
  917. ::Crypto::Hash::HashKind hash_kind;
  918. if (hash_algorithm.equals_ignoring_ascii_case("SHA-1"sv)) {
  919. hash_kind = ::Crypto::Hash::HashKind::SHA1;
  920. } else if (hash_algorithm.equals_ignoring_ascii_case("SHA-256"sv)) {
  921. hash_kind = ::Crypto::Hash::HashKind::SHA256;
  922. } else if (hash_algorithm.equals_ignoring_ascii_case("SHA-384"sv)) {
  923. hash_kind = ::Crypto::Hash::HashKind::SHA384;
  924. } else if (hash_algorithm.equals_ignoring_ascii_case("SHA-512"sv)) {
  925. hash_kind = ::Crypto::Hash::HashKind::SHA512;
  926. } else {
  927. return WebIDL::NotSupportedError::create(m_realm, MUST(String::formatted("Invalid hash function '{}'", hash_algorithm)));
  928. }
  929. ::Crypto::Hash::Manager hash { hash_kind };
  930. hash.update(message);
  931. auto digest = hash.digest();
  932. auto result_buffer = ByteBuffer::copy(digest.immutable_data(), hash.digest_size());
  933. if (result_buffer.is_error())
  934. return WebIDL::OperationError::create(m_realm, "Failed to create result buffer"_fly_string);
  935. auto M = result_buffer.release_value();
  936. // 4. Let Q be the ECDSA public key associated with key.
  937. auto Q = key->handle().visit(
  938. [](ByteBuffer data) -> ByteBuffer {
  939. return data;
  940. },
  941. [](auto) -> ByteBuffer { VERIFY_NOT_REACHED(); });
  942. // FIXME: 5. Let params be the EC domain parameters associated with key.
  943. // 6. If the namedCurve attribute of the [[algorithm]] internal slot of key is "P-256", "P-384" or "P-521":
  944. auto const& internal_algorithm = static_cast<EcKeyAlgorithm const&>(*key->algorithm());
  945. auto const& named_curve = internal_algorithm.named_curve();
  946. auto result = false;
  947. Variant<Empty, ::Crypto::Curves::SECP256r1, ::Crypto::Curves::SECP384r1> curve;
  948. if (named_curve.is_one_of("P-256"sv, "P-384"sv, "P-521"sv)) {
  949. if (named_curve.equals_ignoring_ascii_case("P-256"sv))
  950. curve = ::Crypto::Curves::SECP256r1 {};
  951. if (named_curve.equals_ignoring_ascii_case("P-384"sv))
  952. curve = ::Crypto::Curves::SECP384r1 {};
  953. // FIXME: Support P-521
  954. if (named_curve.equals_ignoring_ascii_case("P-521"sv))
  955. return WebIDL::NotSupportedError::create(m_realm, "'P-521' is not supported yet"_fly_string);
  956. // Perform the ECDSA verifying process, as specified in [RFC6090], Section 5.3,
  957. // with M as the received message,
  958. // signature as the received signature
  959. // and using params as the EC domain parameters,
  960. // and Q as the public key.
  961. // NOTE: verify() takes the signature in X.509 format but JS uses IEEE P1363 format, so we need to convert it
  962. // FIXME: Dont construct an ASN1 object here just to pass it to verify
  963. auto half_size = signature.size() / 2;
  964. auto r = ::Crypto::UnsignedBigInteger::import_data(signature.data(), half_size);
  965. auto s = ::Crypto::UnsignedBigInteger::import_data(signature.data() + half_size, half_size);
  966. ::Crypto::ASN1::Encoder encoder;
  967. (void)encoder.write_constructed(::Crypto::ASN1::Class::Universal, ::Crypto::ASN1::Kind::Sequence, [&] {
  968. (void)encoder.write(r);
  969. (void)encoder.write(s);
  970. });
  971. auto encoded_signature = encoder.finish();
  972. auto maybe_result = curve.visit(
  973. [](Empty const&) -> ErrorOr<bool> { return Error::from_string_view("Failed to create valid crypto instance"sv); },
  974. [&](auto instance) { return instance.verify(M, Q, encoded_signature); });
  975. if (maybe_result.is_error()) {
  976. auto error_message = MUST(FlyString::from_utf8(maybe_result.error().string_literal()));
  977. return WebIDL::OperationError::create(m_realm, error_message);
  978. }
  979. result = maybe_result.release_value();
  980. } else {
  981. // FIXME: Otherwise, the namedCurve attribute of the [[algorithm]] internal slot of key is a value specified in an applicable specification:
  982. // 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.
  983. }
  984. // 9. Let result be a boolean with the value true if the signature is valid and the value false otherwise.
  985. // 10. Return result.
  986. return JS::Value(result);
  987. }
  988. // https://wicg.github.io/webcrypto-secure-curves/#ed25519-operations
  989. 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)
  990. {
  991. // 1. If usages contains a value which is not one of "sign" or "verify", then throw a SyntaxError.
  992. for (auto const& usage : key_usages) {
  993. if (usage != Bindings::KeyUsage::Sign && usage != Bindings::KeyUsage::Verify) {
  994. return WebIDL::SyntaxError::create(m_realm, MUST(String::formatted("Invalid key usage '{}'", idl_enum_to_string(usage))));
  995. }
  996. }
  997. // 2. Generate an Ed25519 key pair, as defined in [RFC8032], section 5.1.5.
  998. ::Crypto::Curves::Ed25519 curve;
  999. auto maybe_private_key = curve.generate_private_key();
  1000. if (maybe_private_key.is_error())
  1001. return WebIDL::OperationError::create(m_realm, "Failed to generate private key"_fly_string);
  1002. auto private_key_data = maybe_private_key.release_value();
  1003. auto maybe_public_key = curve.generate_public_key(private_key_data);
  1004. if (maybe_public_key.is_error())
  1005. return WebIDL::OperationError::create(m_realm, "Failed to generate public key"_fly_string);
  1006. auto public_key_data = maybe_public_key.release_value();
  1007. // 3. Let algorithm be a new KeyAlgorithm object.
  1008. auto algorithm = KeyAlgorithm::create(m_realm);
  1009. // 4. Set the name attribute of algorithm to "Ed25519".
  1010. algorithm->set_name("Ed25519"_string);
  1011. // 5. Let publicKey be a new CryptoKey associated with the relevant global object of this [HTML],
  1012. // and representing the public key of the generated key pair.
  1013. auto public_key = CryptoKey::create(m_realm, CryptoKey::InternalKeyData { public_key_data });
  1014. // 6. Set the [[type]] internal slot of publicKey to "public"
  1015. public_key->set_type(Bindings::KeyType::Public);
  1016. // 7. Set the [[algorithm]] internal slot of publicKey to algorithm.
  1017. public_key->set_algorithm(algorithm);
  1018. // 8. Set the [[extractable]] internal slot of publicKey to true.
  1019. public_key->set_extractable(true);
  1020. // 9. Set the [[usages]] internal slot of publicKey to be the usage intersection of usages and [ "verify" ].
  1021. public_key->set_usages(usage_intersection(key_usages, { { Bindings::KeyUsage::Verify } }));
  1022. // 10. Let privateKey be a new CryptoKey associated with the relevant global object of this [HTML],
  1023. // and representing the private key of the generated key pair.
  1024. auto private_key = CryptoKey::create(m_realm, CryptoKey::InternalKeyData { private_key_data });
  1025. // 11. Set the [[type]] internal slot of privateKey to "private"
  1026. private_key->set_type(Bindings::KeyType::Private);
  1027. // 12. Set the [[algorithm]] internal slot of privateKey to algorithm.
  1028. private_key->set_algorithm(algorithm);
  1029. // 13. Set the [[extractable]] internal slot of privateKey to extractable.
  1030. private_key->set_extractable(extractable);
  1031. // 14. Set the [[usages]] internal slot of privateKey to be the usage intersection of usages and [ "sign" ].
  1032. private_key->set_usages(usage_intersection(key_usages, { { Bindings::KeyUsage::Sign } }));
  1033. // 15. Let result be a new CryptoKeyPair dictionary.
  1034. // 16. Set the publicKey attribute of result to be publicKey.
  1035. // 17. Set the privateKey attribute of result to be privateKey.
  1036. // 18. Return the result of converting result to an ECMAScript Object, as defined by [WebIDL].
  1037. return Variant<JS::NonnullGCPtr<CryptoKey>, JS::NonnullGCPtr<CryptoKeyPair>> { CryptoKeyPair::create(m_realm, public_key, private_key) };
  1038. }
  1039. WebIDL::ExceptionOr<JS::NonnullGCPtr<JS::ArrayBuffer>> ED25519::sign([[maybe_unused]] AlgorithmParams const& params, JS::NonnullGCPtr<CryptoKey> key, ByteBuffer const& message)
  1040. {
  1041. auto& realm = m_realm;
  1042. auto& vm = realm.vm();
  1043. // 1. If the [[type]] internal slot of key is not "private", then throw an InvalidAccessError.
  1044. if (key->type() != Bindings::KeyType::Private)
  1045. return WebIDL::InvalidAccessError::create(realm, "Key is not a private key"_fly_string);
  1046. // 2. Perform the Ed25519 signing process, as specified in [RFC8032], Section 5.1.6,
  1047. // with message as M, using the Ed25519 private key associated with key.
  1048. auto private_key = key->handle().visit(
  1049. [](ByteBuffer data) -> ByteBuffer {
  1050. return data;
  1051. },
  1052. [](auto) -> ByteBuffer { VERIFY_NOT_REACHED(); });
  1053. ::Crypto::Curves::Ed25519 curve;
  1054. auto maybe_public_key = curve.generate_public_key(private_key);
  1055. if (maybe_public_key.is_error())
  1056. return WebIDL::OperationError::create(realm, "Failed to generate public key"_fly_string);
  1057. auto public_key = maybe_public_key.release_value();
  1058. auto maybe_signature = curve.sign(public_key, private_key, message);
  1059. if (maybe_signature.is_error())
  1060. return WebIDL::OperationError::create(realm, "Failed to sign message"_fly_string);
  1061. auto signature = maybe_signature.release_value();
  1062. // 3. Return a new ArrayBuffer associated with the relevant global object of this [HTML],
  1063. // and containing the bytes of the signature resulting from performing the Ed25519 signing process.
  1064. auto result = TRY_OR_THROW_OOM(vm, ByteBuffer::copy(signature));
  1065. return JS::ArrayBuffer::create(realm, move(result));
  1066. }
  1067. WebIDL::ExceptionOr<JS::Value> ED25519::verify([[maybe_unused]] AlgorithmParams const& params, JS::NonnullGCPtr<CryptoKey> key, ByteBuffer const& signature, ByteBuffer const& message)
  1068. {
  1069. auto& realm = m_realm;
  1070. // 1. If the [[type]] internal slot of key is not "public", then throw an InvalidAccessError.
  1071. if (key->type() != Bindings::KeyType::Public)
  1072. return WebIDL::InvalidAccessError::create(realm, "Key is not a public key"_fly_string);
  1073. // NOTE: this is checked by ED25519::verify()
  1074. // 2. If the key data of key represents an invalid point or a small-order element on the Elliptic Curve of Ed25519, return false.
  1075. // 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.
  1076. // 4. Perform the Ed25519 verification steps, as specified in [RFC8032], Section 5.1.7,
  1077. // using the cofactorless (unbatched) equation, [S]B = R + [k]A', on the signature,
  1078. // with message as M, using the Ed25519 public key associated with key.
  1079. auto public_key = key->handle().visit(
  1080. [](ByteBuffer data) -> ByteBuffer {
  1081. return data;
  1082. },
  1083. [](auto) -> ByteBuffer { VERIFY_NOT_REACHED(); });
  1084. // 9. Let result be a boolean with the value true if the signature is valid and the value false otherwise.
  1085. ::Crypto::Curves::Ed25519 curve;
  1086. auto result = curve.verify(public_key, signature, message);
  1087. // 10. Return result.
  1088. return JS::Value(result);
  1089. }
  1090. WebIDL::ExceptionOr<JS::NonnullGCPtr<JS::ArrayBuffer>> PBKDF2::derive_bits(AlgorithmParams const& params, JS::NonnullGCPtr<CryptoKey> key, Optional<u32> length_optional)
  1091. {
  1092. auto& realm = m_realm;
  1093. auto const& normalized_algorithm = static_cast<PBKDF2Params const&>(params);
  1094. // 1. If length is null or zero, or is not a multiple of 8, then throw an OperationError.
  1095. auto length = length_optional.value_or(0);
  1096. if (length == 0 || length % 8 != 0)
  1097. return WebIDL::OperationError::create(realm, "Length must be greater than 0 and divisible by 8"_fly_string);
  1098. // 2. If the iterations member of normalizedAlgorithm is zero, then throw an OperationError.
  1099. if (normalized_algorithm.iterations == 0)
  1100. return WebIDL::OperationError::create(realm, "Iterations must be greater than 0"_fly_string);
  1101. // 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.
  1102. auto const& hash_algorithm = TRY(normalized_algorithm.hash.visit(
  1103. [](String const& name) -> JS::ThrowCompletionOr<String> { return name; },
  1104. [&](JS::Handle<JS::Object> const& obj) -> JS::ThrowCompletionOr<String> {
  1105. auto name_property = TRY(obj->get("name"));
  1106. return name_property.to_string(m_realm.vm()); }));
  1107. // 4. Let result be the result of performing the PBKDF2 operation defined in Section 5.2 of [RFC8018]
  1108. // using prf as the pseudo-random function, PRF,
  1109. // the password represented by [[handle]] internal slot of key as the password, P,
  1110. // the contents of the salt attribute of normalizedAlgorithm as the salt, S,
  1111. // the value of the iterations attribute of normalizedAlgorithm as the iteration count, c,
  1112. // and length divided by 8 as the intended key length, dkLen.
  1113. ErrorOr<ByteBuffer> result = Error::from_string_view("noop error"sv);
  1114. auto password = key->handle().visit(
  1115. [](ByteBuffer data) -> ByteBuffer {
  1116. return data;
  1117. },
  1118. [](auto) -> ByteBuffer { VERIFY_NOT_REACHED(); });
  1119. auto salt = normalized_algorithm.salt;
  1120. auto iterations = normalized_algorithm.iterations;
  1121. auto derived_key_length_bytes = length / 8;
  1122. if (hash_algorithm.equals_ignoring_ascii_case("SHA-1"sv)) {
  1123. result = ::Crypto::Hash::PBKDF2::derive_key<::Crypto::Authentication::HMAC<::Crypto::Hash::SHA1>>(password, salt, iterations, derived_key_length_bytes);
  1124. } else if (hash_algorithm.equals_ignoring_ascii_case("SHA-256"sv)) {
  1125. result = ::Crypto::Hash::PBKDF2::derive_key<::Crypto::Authentication::HMAC<::Crypto::Hash::SHA256>>(password, salt, iterations, derived_key_length_bytes);
  1126. } else if (hash_algorithm.equals_ignoring_ascii_case("SHA-384"sv)) {
  1127. result = ::Crypto::Hash::PBKDF2::derive_key<::Crypto::Authentication::HMAC<::Crypto::Hash::SHA384>>(password, salt, iterations, derived_key_length_bytes);
  1128. } else if (hash_algorithm.equals_ignoring_ascii_case("SHA-512"sv)) {
  1129. result = ::Crypto::Hash::PBKDF2::derive_key<::Crypto::Authentication::HMAC<::Crypto::Hash::SHA512>>(password, salt, iterations, derived_key_length_bytes);
  1130. } else {
  1131. return WebIDL::NotSupportedError::create(m_realm, MUST(String::formatted("Invalid hash function '{}'", hash_algorithm)));
  1132. }
  1133. // 5. If the key derivation operation fails, then throw an OperationError.
  1134. if (result.is_error())
  1135. return WebIDL::OperationError::create(realm, "Failed to derive key"_fly_string);
  1136. // 6. Return result
  1137. return JS::ArrayBuffer::create(realm, result.release_value());
  1138. }
  1139. WebIDL::ExceptionOr<JS::Value> PBKDF2::get_key_length(AlgorithmParams const&)
  1140. {
  1141. // 1. Return null.
  1142. return JS::js_null();
  1143. }
  1144. }