CryptoAlgorithms.cpp 79 KB

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