CryptoAlgorithms.cpp 94 KB

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