CryptoAlgorithms.cpp 90 KB

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