CryptoAlgorithms.cpp 42 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852
  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/Hash/HashManager.h>
  10. #include <LibCrypto/PK/RSA.h>
  11. #include <LibJS/Runtime/ArrayBuffer.h>
  12. #include <LibJS/Runtime/DataView.h>
  13. #include <LibJS/Runtime/TypedArray.h>
  14. #include <LibTLS/Certificate.h>
  15. #include <LibWeb/Crypto/CryptoAlgorithms.h>
  16. #include <LibWeb/Crypto/KeyAlgorithms.h>
  17. #include <LibWeb/Crypto/SubtleCrypto.h>
  18. #include <LibWeb/WebIDL/AbstractOperations.h>
  19. namespace Web::Crypto {
  20. // https://w3c.github.io/webcrypto/#concept-usage-intersection
  21. static Vector<Bindings::KeyUsage> usage_intersection(ReadonlySpan<Bindings::KeyUsage> a, ReadonlySpan<Bindings::KeyUsage> b)
  22. {
  23. Vector<Bindings::KeyUsage> result;
  24. for (auto const& usage : a) {
  25. if (b.contains_slow(usage))
  26. result.append(usage);
  27. }
  28. quick_sort(result);
  29. return result;
  30. }
  31. // Out of line to ensure this class has a key function
  32. AlgorithmMethods::~AlgorithmMethods() = default;
  33. // https://w3c.github.io/webcrypto/#big-integer
  34. static ::Crypto::UnsignedBigInteger big_integer_from_api_big_integer(JS::GCPtr<JS::Uint8Array> const& big_integer)
  35. {
  36. static_assert(AK::HostIsLittleEndian, "This method needs special treatment for BE");
  37. // The BigInteger typedef is a Uint8Array that holds an arbitrary magnitude unsigned integer
  38. // **in big-endian order**. Values read from the API SHALL have minimal typed array length
  39. // (that is, at most 7 leading zero bits, except the value 0 which shall have length 8 bits).
  40. // The API SHALL accept values with any number of leading zero bits, including the empty array, which represents zero.
  41. auto const& buffer = big_integer->viewed_array_buffer()->buffer();
  42. ::Crypto::UnsignedBigInteger result(0);
  43. if (buffer.size() > 0) {
  44. // We need to reverse the buffer to get it into little-endian order
  45. Vector<u8, 32> reversed_buffer;
  46. reversed_buffer.resize(buffer.size());
  47. for (size_t i = 0; i < buffer.size(); ++i) {
  48. reversed_buffer[buffer.size() - i - 1] = buffer[i];
  49. }
  50. result = ::Crypto::UnsignedBigInteger::import_data(reversed_buffer.data(), reversed_buffer.size());
  51. }
  52. return result;
  53. }
  54. // https://www.rfc-editor.org/rfc/rfc7518#section-2
  55. ErrorOr<String> base64_url_uint_encode(::Crypto::UnsignedBigInteger integer)
  56. {
  57. static_assert(AK::HostIsLittleEndian, "This code assumes little-endian");
  58. // The representation of a positive or zero integer value as the
  59. // base64url encoding of the value's unsigned big-endian
  60. // representation as an octet sequence. The octet sequence MUST
  61. // utilize the minimum number of octets needed to represent the
  62. // value. Zero is represented as BASE64URL(single zero-valued
  63. // octet), which is "AA".
  64. auto bytes = TRY(ByteBuffer::create_uninitialized(integer.trimmed_byte_length()));
  65. bool const remove_leading_zeroes = true;
  66. auto data_size = integer.export_data(bytes.span(), remove_leading_zeroes);
  67. auto data_slice = bytes.bytes().slice(bytes.size() - data_size, data_size);
  68. // We need to encode the integer's big endian representation as a base64 string
  69. Vector<u8, 32> byte_swapped_data;
  70. byte_swapped_data.ensure_capacity(data_size);
  71. for (size_t i = 0; i < data_size; ++i)
  72. byte_swapped_data.append(data_slice[data_size - i - 1]);
  73. auto encoded = TRY(encode_base64url(byte_swapped_data));
  74. // FIXME: create a version of encode_base64url that omits padding bytes
  75. if (auto first_padding_byte = encoded.find_byte_offset('='); first_padding_byte.has_value())
  76. return encoded.substring_from_byte_offset(0, first_padding_byte.value());
  77. return encoded;
  78. }
  79. WebIDL::ExceptionOr<::Crypto::UnsignedBigInteger> base64_url_uint_decode(JS::Realm& realm, String const& base64_url_string)
  80. {
  81. auto& vm = realm.vm();
  82. static_assert(AK::HostIsLittleEndian, "This code assumes little-endian");
  83. // FIXME: Create a version of decode_base64url that ignores padding inconsistencies
  84. auto padded_string = base64_url_string;
  85. if (padded_string.byte_count() % 4 != 0) {
  86. padded_string = TRY_OR_THROW_OOM(vm, String::formatted("{}{}", padded_string, TRY_OR_THROW_OOM(vm, String::repeated('=', 4 - (padded_string.byte_count() % 4)))));
  87. }
  88. auto base64_bytes_or_error = decode_base64url(padded_string);
  89. if (base64_bytes_or_error.is_error()) {
  90. if (base64_bytes_or_error.error().code() == ENOMEM)
  91. return vm.throw_completion<JS::InternalError>(vm.error_message(::JS::VM::ErrorMessage::OutOfMemory));
  92. return WebIDL::DataError::create(realm, MUST(String::formatted("base64 decode: {}", base64_bytes_or_error.release_error())));
  93. }
  94. auto base64_bytes = base64_bytes_or_error.release_value();
  95. // We need to swap the integer's big-endian representation to little endian in order to import it
  96. Vector<u8, 32> byte_swapped_data;
  97. byte_swapped_data.ensure_capacity(base64_bytes.size());
  98. for (size_t i = 0; i < base64_bytes.size(); ++i)
  99. byte_swapped_data.append(base64_bytes[base64_bytes.size() - i - 1]);
  100. return ::Crypto::UnsignedBigInteger::import_data(byte_swapped_data.data(), byte_swapped_data.size());
  101. }
  102. // https://w3c.github.io/webcrypto/#concept-parse-an-asn1-structure
  103. template<typename Structure>
  104. static WebIDL::ExceptionOr<Structure> parse_an_ASN1_structure(JS::Realm& realm, ReadonlyBytes data, bool exact_data = true)
  105. {
  106. // 1. Let data be a sequence of bytes to be parsed.
  107. // 2. Let structure be the ASN.1 structure to be parsed.
  108. // 3. Let exactData be an optional boolean value. If it is not supplied, let it be initialized to true.
  109. // 4. Parse data according to the Distinguished Encoding Rules of [X690], using structure as the ASN.1 structure to be decoded.
  110. ::Crypto::ASN1::Decoder decoder(data);
  111. Structure structure;
  112. if constexpr (IsSame<Structure, TLS::SubjectPublicKey>) {
  113. auto maybe_subject_public_key = TLS::parse_subject_public_key_info(decoder);
  114. if (maybe_subject_public_key.is_error())
  115. return WebIDL::DataError::create(realm, MUST(String::formatted("Error parsing subjectPublicKeyInfo: {}", maybe_subject_public_key.release_error())));
  116. structure = maybe_subject_public_key.release_value();
  117. } else if constexpr (IsSame<Structure, TLS::PrivateKey>) {
  118. auto maybe_private_key = TLS::parse_private_key_info(decoder);
  119. if (maybe_private_key.is_error())
  120. return WebIDL::DataError::create(realm, MUST(String::formatted("Error parsing privateKeyInfo: {}", maybe_private_key.release_error())));
  121. structure = maybe_private_key.release_value();
  122. } else {
  123. static_assert(DependentFalse<Structure>, "Don't know how to parse ASN.1 structure type");
  124. }
  125. // 5. If exactData was specified, and all of the bytes of data were not consumed during the parsing phase, then throw a DataError.
  126. if (exact_data && !decoder.eof())
  127. return WebIDL::DataError::create(realm, "Not all bytes were consumed during the parsing phase"_fly_string);
  128. // 6. Return the parsed ASN.1 structure.
  129. return structure;
  130. }
  131. // https://w3c.github.io/webcrypto/#concept-parse-a-spki
  132. static WebIDL::ExceptionOr<TLS::SubjectPublicKey> parse_a_subject_public_key_info(JS::Realm& realm, ReadonlyBytes bytes)
  133. {
  134. // When this specification says to parse a subjectPublicKeyInfo, the user agent must parse an ASN.1 structure,
  135. // with data set to the sequence of bytes to be parsed, structure as the ASN.1 structure of subjectPublicKeyInfo,
  136. // as specified in [RFC5280], and exactData set to true.
  137. return parse_an_ASN1_structure<TLS::SubjectPublicKey>(realm, bytes, true);
  138. }
  139. // https://w3c.github.io/webcrypto/#concept-parse-a-privateKeyInfo
  140. static WebIDL::ExceptionOr<TLS::PrivateKey> parse_a_private_key_info(JS::Realm& realm, ReadonlyBytes bytes)
  141. {
  142. // When this specification says to parse a PrivateKeyInfo, the user agent must parse an ASN.1 structure
  143. // with data set to the sequence of bytes to be parsed, structure as the ASN.1 structure of PrivateKeyInfo,
  144. // as specified in [RFC5208], and exactData set to true.
  145. return parse_an_ASN1_structure<TLS::PrivateKey>(realm, bytes, true);
  146. }
  147. static WebIDL::ExceptionOr<::Crypto::PK::RSAPrivateKey<>> parse_jwk_rsa_private_key(JS::Realm& realm, Bindings::JsonWebKey const& jwk)
  148. {
  149. auto n = TRY(base64_url_uint_decode(realm, *jwk.n));
  150. auto d = TRY(base64_url_uint_decode(realm, *jwk.d));
  151. auto e = TRY(base64_url_uint_decode(realm, *jwk.e));
  152. // We know that if any of the extra parameters are provided, all of them must be
  153. if (!jwk.p.has_value())
  154. return ::Crypto::PK::RSAPrivateKey<>(move(n), move(d), move(e), 0, 0);
  155. auto p = TRY(base64_url_uint_decode(realm, *jwk.p));
  156. auto q = TRY(base64_url_uint_decode(realm, *jwk.q));
  157. auto dp = TRY(base64_url_uint_decode(realm, *jwk.dp));
  158. auto dq = TRY(base64_url_uint_decode(realm, *jwk.dq));
  159. auto qi = TRY(base64_url_uint_decode(realm, *jwk.qi));
  160. return ::Crypto::PK::RSAPrivateKey<>(move(n), move(d), move(e), move(p), move(q), move(dp), move(dq), move(qi));
  161. }
  162. static WebIDL::ExceptionOr<::Crypto::PK::RSAPublicKey<>> parse_jwk_rsa_public_key(JS::Realm& realm, Bindings::JsonWebKey const& jwk)
  163. {
  164. auto e = TRY(base64_url_uint_decode(realm, *jwk.e));
  165. auto n = TRY(base64_url_uint_decode(realm, *jwk.n));
  166. return ::Crypto::PK::RSAPublicKey<>(move(n), move(e));
  167. }
  168. AlgorithmParams::~AlgorithmParams() = default;
  169. JS::ThrowCompletionOr<NonnullOwnPtr<AlgorithmParams>> AlgorithmParams::from_value(JS::VM& vm, JS::Value value)
  170. {
  171. auto& object = value.as_object();
  172. auto name = TRY(object.get("name"));
  173. auto name_string = TRY(name.to_string(vm));
  174. return adopt_own(*new AlgorithmParams { name_string });
  175. }
  176. PBKDF2Params::~PBKDF2Params() = default;
  177. JS::ThrowCompletionOr<NonnullOwnPtr<AlgorithmParams>> PBKDF2Params::from_value(JS::VM& vm, JS::Value value)
  178. {
  179. auto& object = value.as_object();
  180. auto name_value = TRY(object.get("name"));
  181. auto name = TRY(name_value.to_string(vm));
  182. auto salt_value = TRY(object.get("salt"));
  183. 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())))
  184. return vm.throw_completion<JS::TypeError>(JS::ErrorType::NotAnObjectOfType, "BufferSource");
  185. auto salt = TRY_OR_THROW_OOM(vm, WebIDL::get_buffer_source_copy(salt_value.as_object()));
  186. auto iterations_value = TRY(object.get("iterations"));
  187. auto iterations = TRY(iterations_value.to_u32(vm));
  188. auto hash_value = TRY(object.get("hash"));
  189. auto hash = Variant<Empty, HashAlgorithmIdentifier> { Empty {} };
  190. if (hash_value.is_string()) {
  191. auto hash_string = TRY(hash_value.to_string(vm));
  192. hash = HashAlgorithmIdentifier { hash_string };
  193. } else {
  194. auto hash_object = TRY(hash_value.to_object(vm));
  195. hash = HashAlgorithmIdentifier { hash_object };
  196. }
  197. return adopt_own<AlgorithmParams>(*new PBKDF2Params { name, salt, iterations, hash.downcast<HashAlgorithmIdentifier>() });
  198. }
  199. RsaKeyGenParams::~RsaKeyGenParams() = default;
  200. JS::ThrowCompletionOr<NonnullOwnPtr<AlgorithmParams>> RsaKeyGenParams::from_value(JS::VM& vm, JS::Value value)
  201. {
  202. auto& object = value.as_object();
  203. auto name_value = TRY(object.get("name"));
  204. auto name = TRY(name_value.to_string(vm));
  205. auto modulus_length_value = TRY(object.get("modulusLength"));
  206. auto modulus_length = TRY(modulus_length_value.to_u32(vm));
  207. auto public_exponent_value = TRY(object.get("publicExponent"));
  208. JS::GCPtr<JS::Uint8Array> public_exponent;
  209. if (!public_exponent_value.is_object() || !is<JS::Uint8Array>(public_exponent_value.as_object()))
  210. return vm.throw_completion<JS::TypeError>(JS::ErrorType::NotAnObjectOfType, "Uint8Array");
  211. public_exponent = static_cast<JS::Uint8Array&>(public_exponent_value.as_object());
  212. return adopt_own<AlgorithmParams>(*new RsaKeyGenParams { name, modulus_length, big_integer_from_api_big_integer(public_exponent) });
  213. }
  214. RsaHashedKeyGenParams::~RsaHashedKeyGenParams() = default;
  215. JS::ThrowCompletionOr<NonnullOwnPtr<AlgorithmParams>> RsaHashedKeyGenParams::from_value(JS::VM& vm, JS::Value value)
  216. {
  217. auto& object = value.as_object();
  218. auto name_value = TRY(object.get("name"));
  219. auto name = TRY(name_value.to_string(vm));
  220. auto modulus_length_value = TRY(object.get("modulusLength"));
  221. auto modulus_length = TRY(modulus_length_value.to_u32(vm));
  222. auto public_exponent_value = TRY(object.get("publicExponent"));
  223. JS::GCPtr<JS::Uint8Array> public_exponent;
  224. if (!public_exponent_value.is_object() || !is<JS::Uint8Array>(public_exponent_value.as_object()))
  225. return vm.throw_completion<JS::TypeError>(JS::ErrorType::NotAnObjectOfType, "Uint8Array");
  226. public_exponent = static_cast<JS::Uint8Array&>(public_exponent_value.as_object());
  227. auto hash_value = TRY(object.get("hash"));
  228. auto hash = Variant<Empty, HashAlgorithmIdentifier> { Empty {} };
  229. if (hash_value.is_string()) {
  230. auto hash_string = TRY(hash_value.to_string(vm));
  231. hash = HashAlgorithmIdentifier { hash_string };
  232. } else {
  233. auto hash_object = TRY(hash_value.to_object(vm));
  234. hash = HashAlgorithmIdentifier { hash_object };
  235. }
  236. return adopt_own<AlgorithmParams>(*new RsaHashedKeyGenParams { name, modulus_length, big_integer_from_api_big_integer(public_exponent), hash.get<HashAlgorithmIdentifier>() });
  237. }
  238. RsaHashedImportParams::~RsaHashedImportParams() = default;
  239. JS::ThrowCompletionOr<NonnullOwnPtr<AlgorithmParams>> RsaHashedImportParams::from_value(JS::VM& vm, JS::Value value)
  240. {
  241. auto& object = value.as_object();
  242. auto name_value = TRY(object.get("name"));
  243. auto name = TRY(name_value.to_string(vm));
  244. auto hash_value = TRY(object.get("hash"));
  245. auto hash = Variant<Empty, HashAlgorithmIdentifier> { Empty {} };
  246. if (hash_value.is_string()) {
  247. auto hash_string = TRY(hash_value.to_string(vm));
  248. hash = HashAlgorithmIdentifier { hash_string };
  249. } else {
  250. auto hash_object = TRY(hash_value.to_object(vm));
  251. hash = HashAlgorithmIdentifier { hash_object };
  252. }
  253. return adopt_own<AlgorithmParams>(*new RsaHashedImportParams { name, hash.get<HashAlgorithmIdentifier>() });
  254. }
  255. // https://w3c.github.io/webcrypto/#rsa-oaep-operations
  256. WebIDL::ExceptionOr<Variant<JS::NonnullGCPtr<CryptoKey>, JS::NonnullGCPtr<CryptoKeyPair>>> RSAOAEP::generate_key(AlgorithmParams const& params, bool extractable, Vector<Bindings::KeyUsage> const& key_usages)
  257. {
  258. // 1. If usages contains an entry which is not "encrypt", "decrypt", "wrapKey" or "unwrapKey", then throw a SyntaxError.
  259. for (auto const& usage : key_usages) {
  260. if (usage != Bindings::KeyUsage::Encrypt && usage != Bindings::KeyUsage::Decrypt && usage != Bindings::KeyUsage::Wrapkey && usage != Bindings::KeyUsage::Unwrapkey) {
  261. return WebIDL::SyntaxError::create(m_realm, MUST(String::formatted("Invalid key usage '{}'", idl_enum_to_string(usage))));
  262. }
  263. }
  264. // 2. Generate an RSA key pair, as defined in [RFC3447], with RSA modulus length equal to the modulusLength member of normalizedAlgorithm
  265. // and RSA public exponent equal to the publicExponent member of normalizedAlgorithm.
  266. // 3. If performing the operation results in an error, then throw an OperationError.
  267. auto const& normalized_algorithm = static_cast<RsaHashedKeyGenParams const&>(params);
  268. auto key_pair = ::Crypto::PK::RSA::generate_key_pair(normalized_algorithm.modulus_length, normalized_algorithm.public_exponent);
  269. // 4. Let algorithm be a new RsaHashedKeyAlgorithm object.
  270. auto algorithm = RsaHashedKeyAlgorithm::create(m_realm);
  271. // 5. Set the name attribute of algorithm to "RSA-OAEP".
  272. algorithm->set_name("RSA-OAEP"_string);
  273. // 6. Set the modulusLength attribute of algorithm to equal the modulusLength member of normalizedAlgorithm.
  274. algorithm->set_modulus_length(normalized_algorithm.modulus_length);
  275. // 7. Set the publicExponent attribute of algorithm to equal the publicExponent member of normalizedAlgorithm.
  276. TRY(algorithm->set_public_exponent(normalized_algorithm.public_exponent));
  277. // 8. Set the hash attribute of algorithm to equal the hash member of normalizedAlgorithm.
  278. algorithm->set_hash(normalized_algorithm.hash);
  279. // 9. Let publicKey be a new CryptoKey representing the public key of the generated key pair.
  280. auto public_key = CryptoKey::create(m_realm, CryptoKey::InternalKeyData { key_pair.public_key });
  281. // 10. Set the [[type]] internal slot of publicKey to "public"
  282. public_key->set_type(Bindings::KeyType::Public);
  283. // 11. Set the [[algorithm]] internal slot of publicKey to algorithm.
  284. public_key->set_algorithm(algorithm);
  285. // 12. Set the [[extractable]] internal slot of publicKey to true.
  286. public_key->set_extractable(true);
  287. // 13. Set the [[usages]] internal slot of publicKey to be the usage intersection of usages and [ "encrypt", "wrapKey" ].
  288. public_key->set_usages(usage_intersection(key_usages, { { Bindings::KeyUsage::Encrypt, Bindings::KeyUsage::Wrapkey } }));
  289. // 14. Let privateKey be a new CryptoKey representing the private key of the generated key pair.
  290. auto private_key = CryptoKey::create(m_realm, CryptoKey::InternalKeyData { key_pair.private_key });
  291. // 15. Set the [[type]] internal slot of privateKey to "private"
  292. private_key->set_type(Bindings::KeyType::Private);
  293. // 16. Set the [[algorithm]] internal slot of privateKey to algorithm.
  294. private_key->set_algorithm(algorithm);
  295. // 17. Set the [[extractable]] internal slot of privateKey to extractable.
  296. private_key->set_extractable(extractable);
  297. // 18. Set the [[usages]] internal slot of privateKey to be the usage intersection of usages and [ "decrypt", "unwrapKey" ].
  298. private_key->set_usages(usage_intersection(key_usages, { { Bindings::KeyUsage::Decrypt, Bindings::KeyUsage::Unwrapkey } }));
  299. // 19. Let result be a new CryptoKeyPair dictionary.
  300. // 20. Set the publicKey attribute of result to be publicKey.
  301. // 21. Set the privateKey attribute of result to be privateKey.
  302. // 22. Return the result of converting result to an ECMAScript Object, as defined by [WebIDL].
  303. return Variant<JS::NonnullGCPtr<CryptoKey>, JS::NonnullGCPtr<CryptoKeyPair>> { CryptoKeyPair::create(m_realm, public_key, private_key) };
  304. }
  305. // https://w3c.github.io/webcrypto/#rsa-oaep-operations
  306. 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)
  307. {
  308. auto& realm = m_realm;
  309. // 1. Let keyData be the key data to be imported.
  310. JS::GCPtr<CryptoKey> key = nullptr;
  311. auto const& normalized_algorithm = static_cast<RsaHashedImportParams const&>(params);
  312. // 2. -> If format is "spki":
  313. if (key_format == Bindings::KeyFormat::Spki) {
  314. // 1. If usages contains an entry which is not "encrypt" or "wrapKey", then throw a SyntaxError.
  315. for (auto const& usage : usages) {
  316. if (usage != Bindings::KeyUsage::Encrypt && usage != Bindings::KeyUsage::Wrapkey) {
  317. return WebIDL::SyntaxError::create(m_realm, MUST(String::formatted("Invalid key usage '{}'", idl_enum_to_string(usage))));
  318. }
  319. }
  320. VERIFY(key_data.has<ByteBuffer>());
  321. // 2. Let spki be the result of running the parse a subjectPublicKeyInfo algorithm over keyData.
  322. // 3. If an error occurred while parsing, then throw a DataError.
  323. auto spki = TRY(parse_a_subject_public_key_info(m_realm, key_data.get<ByteBuffer>()));
  324. // 4. If the algorithm object identifier field of the algorithm AlgorithmIdentifier field of spki
  325. // is not equal to the rsaEncryption object identifier defined in [RFC3447], then throw a DataError.
  326. if (spki.algorithm.identifier != TLS::rsa_encryption_oid)
  327. return WebIDL::DataError::create(m_realm, "Algorithm object identifier is not the rsaEncryption object identifier"_fly_string);
  328. // 5. Let publicKey be the result of performing the parse an ASN.1 structure algorithm,
  329. // with data as the subjectPublicKeyInfo field of spki, structure as the RSAPublicKey structure
  330. // specified in Section A.1.1 of [RFC3447], and exactData set to true.
  331. // NOTE: We already did this in parse_a_subject_public_key_info
  332. auto& public_key = spki.rsa;
  333. // 6. If an error occurred while parsing, or it can be determined that publicKey is not
  334. // a valid public key according to [RFC3447], then throw a DataError.
  335. // FIXME: Validate the public key
  336. // 7. Let key be a new CryptoKey that represents the RSA public key identified by publicKey.
  337. key = CryptoKey::create(m_realm, CryptoKey::InternalKeyData { public_key });
  338. // 8. Set the [[type]] internal slot of key to "public"
  339. key->set_type(Bindings::KeyType::Public);
  340. }
  341. // -> If format is "pkcs8":
  342. else if (key_format == Bindings::KeyFormat::Pkcs8) {
  343. // 1. If usages contains an entry which is not "decrypt" or "unwrapKey", then throw a SyntaxError.
  344. for (auto const& usage : usages) {
  345. if (usage != Bindings::KeyUsage::Decrypt && usage != Bindings::KeyUsage::Unwrapkey) {
  346. return WebIDL::SyntaxError::create(m_realm, MUST(String::formatted("Invalid key usage '{}'", idl_enum_to_string(usage))));
  347. }
  348. }
  349. VERIFY(key_data.has<ByteBuffer>());
  350. // 2. Let privateKeyInfo be the result of running the parse a privateKeyInfo algorithm over keyData.
  351. // 3. If an error occurred while parsing, then throw a DataError.
  352. auto private_key_info = TRY(parse_a_private_key_info(m_realm, key_data.get<ByteBuffer>()));
  353. // 4. If the algorithm object identifier field of the privateKeyAlgorithm PrivateKeyAlgorithm field of privateKeyInfo
  354. // is not equal to the rsaEncryption object identifier defined in [RFC3447], then throw a DataError.
  355. if (private_key_info.algorithm.identifier != TLS::rsa_encryption_oid)
  356. return WebIDL::DataError::create(m_realm, "Algorithm object identifier is not the rsaEncryption object identifier"_fly_string);
  357. // 5. Let rsaPrivateKey be the result of performing the parse an ASN.1 structure algorithm,
  358. // with data as the privateKey field of privateKeyInfo, structure as the RSAPrivateKey structure
  359. // specified in Section A.1.2 of [RFC3447], and exactData set to true.
  360. // NOTE: We already did this in parse_a_private_key_info
  361. auto& rsa_private_key = private_key_info.rsa;
  362. // 6. If an error occurred while parsing, or if rsaPrivateKey is not
  363. // a valid RSA private key according to [RFC3447], then throw a DataError.
  364. // FIXME: Validate the private key
  365. // 7. Let key be a new CryptoKey that represents the RSA private key identified by rsaPrivateKey.
  366. key = CryptoKey::create(m_realm, CryptoKey::InternalKeyData { rsa_private_key });
  367. // 8. Set the [[type]] internal slot of key to "private"
  368. key->set_type(Bindings::KeyType::Private);
  369. }
  370. // -> If format is "jwk":
  371. else if (key_format == Bindings::KeyFormat::Jwk) {
  372. // 1. -> If keyData is a JsonWebKey dictionary:
  373. // Let jwk equal keyData.
  374. // -> Otherwise:
  375. // Throw a DataError.
  376. if (!key_data.has<Bindings::JsonWebKey>())
  377. return WebIDL::DataError::create(m_realm, "keyData is not a JsonWebKey dictionary"_fly_string);
  378. auto& jwk = key_data.get<Bindings::JsonWebKey>();
  379. // 2. If the d field of jwk is present and usages contains an entry which is not "decrypt" or "unwrapKey", then throw a SyntaxError.
  380. if (jwk.d.has_value()) {
  381. for (auto const& usage : usages) {
  382. if (usage != Bindings::KeyUsage::Decrypt && usage != Bindings::KeyUsage::Unwrapkey) {
  383. return WebIDL::SyntaxError::create(m_realm, MUST(String::formatted("Invalid key usage '{}'", Bindings::idl_enum_to_string(usage))));
  384. }
  385. }
  386. }
  387. // 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.
  388. if (!jwk.d.has_value()) {
  389. for (auto const& usage : usages) {
  390. if (usage != Bindings::KeyUsage::Encrypt && usage != Bindings::KeyUsage::Wrapkey) {
  391. return WebIDL::SyntaxError::create(m_realm, MUST(String::formatted("Invalid key usage '{}'", Bindings::idl_enum_to_string(usage))));
  392. }
  393. }
  394. }
  395. // 4. If the kty field of jwk is not a case-sensitive string match to "RSA", then throw a DataError.
  396. if (jwk.kty != "RSA"_string)
  397. return WebIDL::DataError::create(m_realm, "Invalid key type"_fly_string);
  398. // 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.
  399. if (!usages.is_empty() && jwk.use.has_value() && *jwk.use != "enc"_string)
  400. return WebIDL::DataError::create(m_realm, "Invalid use field"_fly_string);
  401. // 6. If the key_ops field of jwk is present, and is invalid according to the requirements of JSON Web Key [JWK]
  402. // or does not contain all of the specified usages values, then throw a DataError.
  403. for (auto const& usage : usages) {
  404. if (!jwk.key_ops->contains_slow(Bindings::idl_enum_to_string(usage)))
  405. return WebIDL::DataError::create(m_realm, MUST(String::formatted("Missing key_ops field: {}", Bindings::idl_enum_to_string(usage))));
  406. }
  407. // FIXME: Validate jwk.key_ops against requirements in https://www.rfc-editor.org/rfc/rfc7517#section-4.3
  408. // 7. If the ext field of jwk is present and has the value false and extractable is true, then throw a DataError.
  409. if (jwk.ext.has_value() && !*jwk.ext && extractable)
  410. return WebIDL::DataError::create(m_realm, "Invalid ext field"_fly_string);
  411. Optional<String> hash = {};
  412. // 8. -> If the alg field of jwk is not present:
  413. if (!jwk.alg.has_value()) {
  414. // Let hash be undefined.
  415. }
  416. // -> If the alg field of jwk is equal to "RSA-OAEP":
  417. if (jwk.alg == "RSA-OAEP"sv) {
  418. // Let hash be the string "SHA-1".
  419. hash = "SHA-1"_string;
  420. }
  421. // -> If the alg field of jwk is equal to "RSA-OAEP-256":
  422. else if (jwk.alg == "RSA-OAEP-256"sv) {
  423. // Let hash be the string "SHA-256".
  424. hash = "SHA-256"_string;
  425. }
  426. // -> If the alg field of jwk is equal to "RSA-OAEP-384":
  427. else if (jwk.alg == "RSA-OAEP-384"sv) {
  428. // Let hash be the string "SHA-384".
  429. hash = "SHA-384"_string;
  430. }
  431. // -> If the alg field of jwk is equal to "RSA-OAEP-512":
  432. else if (jwk.alg == "RSA-OAEP-512"sv) {
  433. // Let hash be the string "SHA-512".
  434. hash = "SHA-512"_string;
  435. }
  436. // -> Otherwise:
  437. else {
  438. // FIXME: Support 'other applicable specifications'
  439. // 1. Perform any key import steps defined by other applicable specifications, passing format, jwk and obtaining hash.
  440. // 2. If an error occurred or there are no applicable specifications, throw a DataError.
  441. return WebIDL::DataError::create(m_realm, "Invalid alg field"_fly_string);
  442. }
  443. // 9. If hash is not undefined:
  444. if (hash.has_value()) {
  445. // 1. Let normalizedHash be the result of normalize an algorithm with alg set to hash and op set to digest.
  446. auto normalized_hash = TRY(normalize_an_algorithm(m_realm, AlgorithmIdentifier { *hash }, "digest"_string));
  447. // 2. If normalizedHash is not equal to the hash member of normalizedAlgorithm, throw a DataError.
  448. 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> {
  449. auto name_property = TRY(obj->get("name"));
  450. return name_property.to_string(m_realm.vm()); })))
  451. return WebIDL::DataError::create(m_realm, "Invalid hash"_fly_string);
  452. }
  453. // 10. -> If the d field of jwk is present:
  454. if (jwk.d.has_value()) {
  455. // 1. If jwk does not meet the requirements of Section 6.3.2 of JSON Web Algorithms [JWA], then throw a DataError.
  456. bool meets_requirements = jwk.e.has_value() && jwk.n.has_value() && jwk.d.has_value();
  457. if (jwk.p.has_value() || jwk.q.has_value() || jwk.dp.has_value() || jwk.dq.has_value() || jwk.qi.has_value())
  458. meets_requirements |= jwk.p.has_value() && jwk.q.has_value() && jwk.dp.has_value() && jwk.dq.has_value() && jwk.qi.has_value();
  459. if (jwk.oth.has_value()) {
  460. // FIXME: We don't support > 2 primes in RSA keys
  461. meets_requirements = false;
  462. }
  463. if (!meets_requirements)
  464. return WebIDL::DataError::create(m_realm, "Invalid JWK private key"_fly_string);
  465. // FIXME: Spec error, it should say 'the RSA private key identified by interpreting jwk according to section 6.3.2'
  466. // 2. Let privateKey represent the RSA public key identified by interpreting jwk according to Section 6.3.1 of JSON Web Algorithms [JWA].
  467. auto private_key = TRY(parse_jwk_rsa_private_key(realm, jwk));
  468. // FIXME: Spec error, it should say 'not to be a valid RSA private key'
  469. // 3. If privateKey can be determined to not be a valid RSA public key according to [RFC3447], then throw a DataError.
  470. // FIXME: Validate the private key
  471. // 4. Let key be a new CryptoKey representing privateKey.
  472. key = CryptoKey::create(m_realm, CryptoKey::InternalKeyData { private_key });
  473. // 5. Set the [[type]] internal slot of key to "private"
  474. key->set_type(Bindings::KeyType::Private);
  475. }
  476. // -> Otherwise:
  477. else {
  478. // 1. If jwk does not meet the requirements of Section 6.3.1 of JSON Web Algorithms [JWA], then throw a DataError.
  479. if (!jwk.e.has_value() || !jwk.n.has_value())
  480. return WebIDL::DataError::create(m_realm, "Invalid JWK public key"_fly_string);
  481. // 2. Let publicKey represent the RSA public key identified by interpreting jwk according to Section 6.3.1 of JSON Web Algorithms [JWA].
  482. auto public_key = TRY(parse_jwk_rsa_public_key(realm, jwk));
  483. // 3. If publicKey can be determined to not be a valid RSA public key according to [RFC3447], then throw a DataError.
  484. // FIXME: Validate the public key
  485. // 4. Let key be a new CryptoKey representing publicKey.
  486. key = CryptoKey::create(m_realm, CryptoKey::InternalKeyData { public_key });
  487. // 5. Set the [[type]] internal slot of key to "public"
  488. key->set_type(Bindings::KeyType::Public);
  489. }
  490. }
  491. // -> Otherwise: throw a NotSupportedError.
  492. else {
  493. return WebIDL::NotSupportedError::create(m_realm, "Unsupported key format"_fly_string);
  494. }
  495. // 3. Let algorithm be a new RsaHashedKeyAlgorithm.
  496. auto algorithm = RsaHashedKeyAlgorithm::create(m_realm);
  497. // 4. Set the name attribute of algorithm to "RSA-OAEP"
  498. algorithm->set_name("RSA-OAEP"_string);
  499. // 5. Set the modulusLength attribute of algorithm to the length, in bits, of the RSA public modulus.
  500. // 6. Set the publicExponent attribute of algorithm to the BigInteger representation of the RSA public exponent.
  501. TRY(key->handle().visit(
  502. [&](::Crypto::PK::RSAPublicKey<> const& public_key) -> WebIDL::ExceptionOr<void> {
  503. algorithm->set_modulus_length(public_key.length());
  504. TRY(algorithm->set_public_exponent(public_key.public_exponent()));
  505. return {};
  506. },
  507. [&](::Crypto::PK::RSAPrivateKey<> const& private_key) -> WebIDL::ExceptionOr<void> {
  508. algorithm->set_modulus_length(private_key.length());
  509. TRY(algorithm->set_public_exponent(private_key.public_exponent()));
  510. return {};
  511. },
  512. [](auto) -> WebIDL::ExceptionOr<void> { VERIFY_NOT_REACHED(); }));
  513. // 7. Set the hash attribute of algorithm to the hash member of normalizedAlgorithm.
  514. algorithm->set_hash(normalized_algorithm.hash);
  515. // 8. Set the [[algorithm]] internal slot of key to algorithm
  516. key->set_algorithm(algorithm);
  517. // 9. Return key.
  518. return JS::NonnullGCPtr { *key };
  519. }
  520. // https://w3c.github.io/webcrypto/#rsa-oaep-operations
  521. WebIDL::ExceptionOr<JS::NonnullGCPtr<JS::Object>> RSAOAEP::export_key(Bindings::KeyFormat format, JS::NonnullGCPtr<CryptoKey> key)
  522. {
  523. auto& realm = m_realm;
  524. auto& vm = realm.vm();
  525. // 1. Let key be the key to be exported.
  526. // 2. If the underlying cryptographic key material represented by the [[handle]] internal slot of key cannot be accessed, then throw an OperationError.
  527. // Note: In our impl this is always accessible
  528. auto const& handle = key->handle();
  529. JS::GCPtr<JS::Object> result = nullptr;
  530. // 3. If format is "spki"
  531. if (format == Bindings::KeyFormat::Spki) {
  532. // 1. If the [[type]] internal slot of key is not "public", then throw an InvalidAccessError.
  533. if (key->type() != Bindings::KeyType::Public)
  534. return WebIDL::InvalidAccessError::create(realm, "Key is not public"_fly_string);
  535. // FIXME: 2. Let data be an instance of the subjectPublicKeyInfo ASN.1 structure defined in [RFC5280] with the following properties:
  536. // - Set the algorithm field to an AlgorithmIdentifier ASN.1 type with the following properties:
  537. // - Set the algorithm field to the OID rsaEncryption defined in [RFC3447].
  538. // - Set the params field to the ASN.1 type NULL.
  539. // - Set the subjectPublicKey field to the result of DER-encoding an RSAPublicKey ASN.1 type, as defined in [RFC3447], Appendix A.1.1,
  540. // that represents the RSA public key represented by the [[handle]] internal slot of key
  541. // FIXME: 3. Let result be the result of creating an ArrayBuffer containing data.
  542. result = JS::ArrayBuffer::create(realm, TRY_OR_THROW_OOM(vm, ByteBuffer::copy(("FIXME"sv).bytes())));
  543. }
  544. // FIXME: If format is "pkcs8"
  545. // If format is "jwk"
  546. else if (format == Bindings::KeyFormat::Jwk) {
  547. // 1. Let jwk be a new JsonWebKey dictionary.
  548. Bindings::JsonWebKey jwk = {};
  549. // 2. Set the kty attribute of jwk to the string "RSA".
  550. jwk.kty = "RSA"_string;
  551. // 4. Let hash be the name attribute of the hash attribute of the [[algorithm]] internal slot of key.
  552. 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> {
  553. auto name_property = TRY(obj->get("name"));
  554. return name_property.to_string(realm.vm()); }));
  555. // 4. If hash is "SHA-1":
  556. // - Set the alg attribute of jwk to the string "RSA-OAEP".
  557. if (hash == "SHA-1"sv) {
  558. jwk.alg = "RSA-OAEP"_string;
  559. }
  560. // If hash is "SHA-256":
  561. // - Set the alg attribute of jwk to the string "RSA-OAEP-256".
  562. else if (hash == "SHA-256"sv) {
  563. jwk.alg = "RSA-OAEP-256"_string;
  564. }
  565. // If hash is "SHA-384":
  566. // - Set the alg attribute of jwk to the string "RSA-OAEP-384".
  567. else if (hash == "SHA-384"sv) {
  568. jwk.alg = "RSA-OAEP-384"_string;
  569. }
  570. // If hash is "SHA-512":
  571. // - Set the alg attribute of jwk to the string "RSA-OAEP-512".
  572. else if (hash == "SHA-512"sv) {
  573. jwk.alg = "RSA-OAEP-512"_string;
  574. } else {
  575. // FIXME: Support 'other applicable specifications'
  576. // - Perform any key export steps defined by other applicable specifications,
  577. // passing format and the hash attribute of the [[algorithm]] internal slot of key and obtaining alg.
  578. // - Set the alg attribute of jwk to alg.
  579. return WebIDL::NotSupportedError::create(realm, TRY_OR_THROW_OOM(vm, String::formatted("Unsupported hash algorithm '{}'", hash)));
  580. }
  581. // 10. Set the attributes n and e of jwk according to the corresponding definitions in JSON Web Algorithms [JWA], Section 6.3.1.
  582. auto maybe_error = handle.visit(
  583. [&](::Crypto::PK::RSAPublicKey<> const& public_key) -> ErrorOr<void> {
  584. jwk.n = TRY(base64_url_uint_encode(public_key.modulus()));
  585. jwk.e = TRY(base64_url_uint_encode(public_key.public_exponent()));
  586. return {};
  587. },
  588. [&](::Crypto::PK::RSAPrivateKey<> const& private_key) -> ErrorOr<void> {
  589. jwk.n = TRY(base64_url_uint_encode(private_key.modulus()));
  590. jwk.e = TRY(base64_url_uint_encode(private_key.public_exponent()));
  591. // 11. If the [[type]] internal slot of key is "private":
  592. // 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.
  593. jwk.d = TRY(base64_url_uint_encode(private_key.private_exponent()));
  594. jwk.p = TRY(base64_url_uint_encode(private_key.prime1()));
  595. jwk.q = TRY(base64_url_uint_encode(private_key.prime2()));
  596. jwk.dp = TRY(base64_url_uint_encode(private_key.exponent1()));
  597. jwk.dq = TRY(base64_url_uint_encode(private_key.exponent2()));
  598. jwk.qi = TRY(base64_url_uint_encode(private_key.coefficient()));
  599. // 12. If the underlying RSA private key represented by the [[handle]] internal slot of key is represented by more than two primes,
  600. // set the attribute named oth of jwk according to the corresponding definition in JSON Web Algorithms [JWA], Section 6.3.2.7
  601. // FIXME: We don't support more than 2 primes on RSA keys
  602. return {};
  603. },
  604. [](auto) -> ErrorOr<void> {
  605. VERIFY_NOT_REACHED();
  606. });
  607. // FIXME: clang-format butchers the visit if we do the TRY inline
  608. TRY_OR_THROW_OOM(vm, maybe_error);
  609. // 13. Set the key_ops attribute of jwk to the usages attribute of key.
  610. jwk.key_ops = Vector<String> {};
  611. jwk.key_ops->ensure_capacity(key->internal_usages().size());
  612. for (auto const& usage : key->internal_usages()) {
  613. jwk.key_ops->append(Bindings::idl_enum_to_string(usage));
  614. }
  615. // 14. Set the ext attribute of jwk to the [[extractable]] internal slot of key.
  616. jwk.ext = key->extractable();
  617. // 15. Let result be the result of converting jwk to an ECMAScript Object, as defined by [WebIDL].
  618. result = TRY(jwk.to_object(realm));
  619. }
  620. // Otherwise throw a NotSupportedError.
  621. else {
  622. return WebIDL::NotSupportedError::create(realm, TRY_OR_THROW_OOM(vm, String::formatted("Exporting to format {} is not supported", Bindings::idl_enum_to_string(format))));
  623. }
  624. // 8. Return result
  625. return JS::NonnullGCPtr { *result };
  626. }
  627. 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)
  628. {
  629. // 1. If format is not "raw", throw a NotSupportedError
  630. if (format != Bindings::KeyFormat::Raw) {
  631. return WebIDL::NotSupportedError::create(m_realm, "Only raw format is supported"_fly_string);
  632. }
  633. // 2. If usages contains a value that is not "deriveKey" or "deriveBits", then throw a SyntaxError.
  634. for (auto& usage : key_usages) {
  635. if (usage != Bindings::KeyUsage::Derivekey && usage != Bindings::KeyUsage::Derivebits) {
  636. return WebIDL::SyntaxError::create(m_realm, MUST(String::formatted("Invalid key usage '{}'", idl_enum_to_string(usage))));
  637. }
  638. }
  639. // 3. If extractable is not false, then throw a SyntaxError.
  640. if (extractable)
  641. return WebIDL::SyntaxError::create(m_realm, "extractable must be false"_fly_string);
  642. // 4. Let key be a new CryptoKey representing keyData.
  643. auto key = CryptoKey::create(m_realm, move(key_data));
  644. // 5. Set the [[type]] internal slot of key to "secret".
  645. key->set_type(Bindings::KeyType::Secret);
  646. // 6. Set the [[extractable]] internal slot of key to false.
  647. key->set_extractable(false);
  648. // 7. Let algorithm be a new KeyAlgorithm object.
  649. auto algorithm = KeyAlgorithm::create(m_realm);
  650. // 8. Set the name attribute of algorithm to "PBKDF2".
  651. algorithm->set_name("PBKDF2"_string);
  652. // 9. Set the [[algorithm]] internal slot of key to algorithm.
  653. key->set_algorithm(algorithm);
  654. // 10. Return key.
  655. return key;
  656. }
  657. WebIDL::ExceptionOr<JS::NonnullGCPtr<JS::ArrayBuffer>> SHA::digest(AlgorithmParams const& algorithm, ByteBuffer const& data)
  658. {
  659. auto& algorithm_name = algorithm.name;
  660. ::Crypto::Hash::HashKind hash_kind;
  661. if (algorithm_name.equals_ignoring_ascii_case("SHA-1"sv)) {
  662. hash_kind = ::Crypto::Hash::HashKind::SHA1;
  663. } else if (algorithm_name.equals_ignoring_ascii_case("SHA-256"sv)) {
  664. hash_kind = ::Crypto::Hash::HashKind::SHA256;
  665. } else if (algorithm_name.equals_ignoring_ascii_case("SHA-384"sv)) {
  666. hash_kind = ::Crypto::Hash::HashKind::SHA384;
  667. } else if (algorithm_name.equals_ignoring_ascii_case("SHA-512"sv)) {
  668. hash_kind = ::Crypto::Hash::HashKind::SHA512;
  669. } else {
  670. return WebIDL::NotSupportedError::create(m_realm, MUST(String::formatted("Invalid hash function '{}'", algorithm_name)));
  671. }
  672. ::Crypto::Hash::Manager hash { hash_kind };
  673. hash.update(data);
  674. auto digest = hash.digest();
  675. auto result_buffer = ByteBuffer::copy(digest.immutable_data(), hash.digest_size());
  676. if (result_buffer.is_error())
  677. return WebIDL::OperationError::create(m_realm, "Failed to create result buffer"_fly_string);
  678. return JS::ArrayBuffer::create(m_realm, result_buffer.release_value());
  679. }
  680. }