CryptoAlgorithms.cpp 42 KB

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