CryptoAlgorithms.cpp 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455
  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/Hash/HashManager.h>
  9. #include <LibCrypto/PK/RSA.h>
  10. #include <LibJS/Runtime/ArrayBuffer.h>
  11. #include <LibJS/Runtime/DataView.h>
  12. #include <LibJS/Runtime/TypedArray.h>
  13. #include <LibWeb/Crypto/CryptoAlgorithms.h>
  14. #include <LibWeb/Crypto/KeyAlgorithms.h>
  15. namespace Web::Crypto {
  16. // https://w3c.github.io/webcrypto/#concept-usage-intersection
  17. static Vector<Bindings::KeyUsage> usage_intersection(ReadonlySpan<Bindings::KeyUsage> a, ReadonlySpan<Bindings::KeyUsage> b)
  18. {
  19. Vector<Bindings::KeyUsage> result;
  20. for (auto const& usage : a) {
  21. if (b.contains_slow(usage))
  22. result.append(usage);
  23. }
  24. quick_sort(result);
  25. return result;
  26. }
  27. // Out of line to ensure this class has a key function
  28. AlgorithmMethods::~AlgorithmMethods() = default;
  29. // https://w3c.github.io/webcrypto/#big-integer
  30. static ::Crypto::UnsignedBigInteger big_integer_from_api_big_integer(JS::GCPtr<JS::Uint8Array> const& big_integer)
  31. {
  32. static_assert(AK::HostIsLittleEndian, "This method needs special treatment for BE");
  33. // The BigInteger typedef is a Uint8Array that holds an arbitrary magnitude unsigned integer
  34. // **in big-endian order**. Values read from the API SHALL have minimal typed array length
  35. // (that is, at most 7 leading zero bits, except the value 0 which shall have length 8 bits).
  36. // The API SHALL accept values with any number of leading zero bits, including the empty array, which represents zero.
  37. auto const& buffer = big_integer->viewed_array_buffer()->buffer();
  38. ::Crypto::UnsignedBigInteger result(0);
  39. if (buffer.size() > 0) {
  40. // We need to reverse the buffer to get it into little-endian order
  41. Vector<u8, 32> reversed_buffer;
  42. reversed_buffer.resize(buffer.size());
  43. for (size_t i = 0; i < buffer.size(); ++i) {
  44. reversed_buffer[buffer.size() - i - 1] = buffer[i];
  45. }
  46. result = ::Crypto::UnsignedBigInteger::import_data(reversed_buffer.data(), reversed_buffer.size());
  47. }
  48. return result;
  49. }
  50. // https://www.rfc-editor.org/rfc/rfc7518#section-2
  51. ErrorOr<String> base64_url_uint_encode(::Crypto::UnsignedBigInteger integer)
  52. {
  53. static_assert(AK::HostIsLittleEndian, "This code assumes little-endian");
  54. // The representation of a positive or zero integer value as the
  55. // base64url encoding of the value's unsigned big-endian
  56. // representation as an octet sequence. The octet sequence MUST
  57. // utilize the minimum number of octets needed to represent the
  58. // value. Zero is represented as BASE64URL(single zero-valued
  59. // octet), which is "AA".
  60. auto bytes = TRY(ByteBuffer::create_uninitialized(integer.trimmed_byte_length()));
  61. bool const remove_leading_zeroes = true;
  62. auto data_size = integer.export_data(bytes.span(), remove_leading_zeroes);
  63. auto data_slice = bytes.bytes().slice(bytes.size() - data_size, data_size);
  64. // We need to encode the integer's big endian representation as a base64 string
  65. Vector<u8, 32> byte_swapped_data;
  66. byte_swapped_data.ensure_capacity(data_size);
  67. for (size_t i = 0; i < data_size; ++i)
  68. byte_swapped_data.append(data_slice[data_size - i - 1]);
  69. auto encoded = TRY(encode_base64url(byte_swapped_data));
  70. // FIXME: create a version of encode_base64url that omits padding bytes
  71. if (auto first_padding_byte = encoded.find_byte_offset('='); first_padding_byte.has_value())
  72. return encoded.substring_from_byte_offset(0, first_padding_byte.value());
  73. return encoded;
  74. }
  75. AlgorithmParams::~AlgorithmParams() = default;
  76. JS::ThrowCompletionOr<NonnullOwnPtr<AlgorithmParams>> AlgorithmParams::from_value(JS::VM& vm, JS::Value value)
  77. {
  78. auto& object = value.as_object();
  79. auto name = TRY(object.get("name"));
  80. auto name_string = TRY(name.to_string(vm));
  81. return adopt_own(*new AlgorithmParams { name_string });
  82. }
  83. PBKDF2Params::~PBKDF2Params() = default;
  84. JS::ThrowCompletionOr<NonnullOwnPtr<AlgorithmParams>> PBKDF2Params::from_value(JS::VM& vm, JS::Value value)
  85. {
  86. auto& realm = *vm.current_realm();
  87. auto& object = value.as_object();
  88. auto name_value = TRY(object.get("name"));
  89. auto name = TRY(name_value.to_string(vm));
  90. auto salt_value = TRY(object.get("salt"));
  91. JS::Handle<WebIDL::BufferSource> salt;
  92. 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())))
  93. return vm.throw_completion<JS::TypeError>(JS::ErrorType::NotAnObjectOfType, "BufferSource");
  94. salt = JS::make_handle(vm.heap().allocate<WebIDL::BufferSource>(realm, salt_value.as_object()));
  95. auto iterations_value = TRY(object.get("iterations"));
  96. auto iterations = TRY(iterations_value.to_u32(vm));
  97. auto hash_value = TRY(object.get("hash"));
  98. auto hash = Variant<Empty, HashAlgorithmIdentifier> { Empty {} };
  99. if (hash_value.is_string()) {
  100. auto hash_string = TRY(hash_value.to_string(vm));
  101. hash = HashAlgorithmIdentifier { hash_string };
  102. } else {
  103. auto hash_object = TRY(hash_value.to_object(vm));
  104. hash = HashAlgorithmIdentifier { hash_object };
  105. }
  106. return adopt_own<AlgorithmParams>(*new PBKDF2Params { name, salt, iterations, hash.downcast<HashAlgorithmIdentifier>() });
  107. }
  108. RsaKeyGenParams::~RsaKeyGenParams() = default;
  109. JS::ThrowCompletionOr<NonnullOwnPtr<AlgorithmParams>> RsaKeyGenParams::from_value(JS::VM& vm, JS::Value value)
  110. {
  111. auto& object = value.as_object();
  112. auto name_value = TRY(object.get("name"));
  113. auto name = TRY(name_value.to_string(vm));
  114. auto modulus_length_value = TRY(object.get("modulusLength"));
  115. auto modulus_length = TRY(modulus_length_value.to_u32(vm));
  116. auto public_exponent_value = TRY(object.get("publicExponent"));
  117. JS::GCPtr<JS::Uint8Array> public_exponent;
  118. if (!public_exponent_value.is_object() || !is<JS::Uint8Array>(public_exponent_value.as_object()))
  119. return vm.throw_completion<JS::TypeError>(JS::ErrorType::NotAnObjectOfType, "Uint8Array");
  120. public_exponent = static_cast<JS::Uint8Array&>(public_exponent_value.as_object());
  121. return adopt_own<AlgorithmParams>(*new RsaKeyGenParams { name, modulus_length, big_integer_from_api_big_integer(public_exponent) });
  122. }
  123. RsaHashedKeyGenParams::~RsaHashedKeyGenParams() = default;
  124. JS::ThrowCompletionOr<NonnullOwnPtr<AlgorithmParams>> RsaHashedKeyGenParams::from_value(JS::VM& vm, JS::Value value)
  125. {
  126. auto& object = value.as_object();
  127. auto name_value = TRY(object.get("name"));
  128. auto name = TRY(name_value.to_string(vm));
  129. auto modulus_length_value = TRY(object.get("modulusLength"));
  130. auto modulus_length = TRY(modulus_length_value.to_u32(vm));
  131. auto public_exponent_value = TRY(object.get("publicExponent"));
  132. JS::GCPtr<JS::Uint8Array> public_exponent;
  133. if (!public_exponent_value.is_object() || !is<JS::Uint8Array>(public_exponent_value.as_object()))
  134. return vm.throw_completion<JS::TypeError>(JS::ErrorType::NotAnObjectOfType, "Uint8Array");
  135. public_exponent = static_cast<JS::Uint8Array&>(public_exponent_value.as_object());
  136. auto hash_value = TRY(object.get("hash"));
  137. auto hash = Variant<Empty, HashAlgorithmIdentifier> { Empty {} };
  138. if (hash_value.is_string()) {
  139. auto hash_string = TRY(hash_value.to_string(vm));
  140. hash = HashAlgorithmIdentifier { hash_string };
  141. } else {
  142. auto hash_object = TRY(hash_value.to_object(vm));
  143. hash = HashAlgorithmIdentifier { hash_object };
  144. }
  145. return adopt_own<AlgorithmParams>(*new RsaHashedKeyGenParams { name, modulus_length, big_integer_from_api_big_integer(public_exponent), hash.get<HashAlgorithmIdentifier>() });
  146. }
  147. // https://w3c.github.io/webcrypto/#rsa-oaep-operations
  148. WebIDL::ExceptionOr<Variant<JS::NonnullGCPtr<CryptoKey>, JS::NonnullGCPtr<CryptoKeyPair>>> RSAOAEP::generate_key(AlgorithmParams const& params, bool extractable, Vector<Bindings::KeyUsage> const& key_usages)
  149. {
  150. // 1. If usages contains an entry which is not "encrypt", "decrypt", "wrapKey" or "unwrapKey", then throw a SyntaxError.
  151. for (auto const& usage : key_usages) {
  152. if (usage != Bindings::KeyUsage::Encrypt && usage != Bindings::KeyUsage::Decrypt && usage != Bindings::KeyUsage::Wrapkey && usage != Bindings::KeyUsage::Unwrapkey) {
  153. return WebIDL::SyntaxError::create(m_realm, MUST(String::formatted("Invalid key usage '{}'", idl_enum_to_string(usage))));
  154. }
  155. }
  156. // 2. Generate an RSA key pair, as defined in [RFC3447], with RSA modulus length equal to the modulusLength member of normalizedAlgorithm
  157. // and RSA public exponent equal to the publicExponent member of normalizedAlgorithm.
  158. // 3. If performing the operation results in an error, then throw an OperationError.
  159. auto const& normalized_algorithm = static_cast<RsaHashedKeyGenParams const&>(params);
  160. auto key_pair = ::Crypto::PK::RSA::generate_key_pair(normalized_algorithm.modulus_length, normalized_algorithm.public_exponent);
  161. // 4. Let algorithm be a new RsaHashedKeyAlgorithm object.
  162. auto algorithm = RsaHashedKeyAlgorithm::create(m_realm);
  163. // 5. Set the name attribute of algorithm to "RSA-OAEP".
  164. algorithm->set_name("RSA-OAEP"_string);
  165. // 6. Set the modulusLength attribute of algorithm to equal the modulusLength member of normalizedAlgorithm.
  166. algorithm->set_modulus_length(normalized_algorithm.modulus_length);
  167. // 7. Set the publicExponent attribute of algorithm to equal the publicExponent member of normalizedAlgorithm.
  168. TRY(algorithm->set_public_exponent(normalized_algorithm.public_exponent));
  169. // 8. Set the hash attribute of algorithm to equal the hash member of normalizedAlgorithm.
  170. algorithm->set_hash(normalized_algorithm.hash);
  171. // 9. Let publicKey be a new CryptoKey representing the public key of the generated key pair.
  172. auto public_key = CryptoKey::create(m_realm, CryptoKey::InternalKeyData { key_pair.public_key });
  173. // 10. Set the [[type]] internal slot of publicKey to "public"
  174. public_key->set_type(Bindings::KeyType::Public);
  175. // 11. Set the [[algorithm]] internal slot of publicKey to algorithm.
  176. public_key->set_algorithm(algorithm);
  177. // 12. Set the [[extractable]] internal slot of publicKey to true.
  178. public_key->set_extractable(true);
  179. // 13. Set the [[usages]] internal slot of publicKey to be the usage intersection of usages and [ "encrypt", "wrapKey" ].
  180. public_key->set_usages(usage_intersection(key_usages, { { Bindings::KeyUsage::Encrypt, Bindings::KeyUsage::Wrapkey } }));
  181. // 14. Let privateKey be a new CryptoKey representing the private key of the generated key pair.
  182. auto private_key = CryptoKey::create(m_realm, CryptoKey::InternalKeyData { key_pair.private_key });
  183. // 15. Set the [[type]] internal slot of privateKey to "private"
  184. private_key->set_type(Bindings::KeyType::Private);
  185. // 16. Set the [[algorithm]] internal slot of privateKey to algorithm.
  186. private_key->set_algorithm(algorithm);
  187. // 17. Set the [[extractable]] internal slot of privateKey to extractable.
  188. private_key->set_extractable(extractable);
  189. // 18. Set the [[usages]] internal slot of privateKey to be the usage intersection of usages and [ "decrypt", "unwrapKey" ].
  190. private_key->set_usages(usage_intersection(key_usages, { { Bindings::KeyUsage::Decrypt, Bindings::KeyUsage::Unwrapkey } }));
  191. // 19. Let result be a new CryptoKeyPair dictionary.
  192. // 20. Set the publicKey attribute of result to be publicKey.
  193. // 21. Set the privateKey attribute of result to be privateKey.
  194. // 22. Return the result of converting result to an ECMAScript Object, as defined by [WebIDL].
  195. return Variant<JS::NonnullGCPtr<CryptoKey>, JS::NonnullGCPtr<CryptoKeyPair>> { CryptoKeyPair::create(m_realm, public_key, private_key) };
  196. }
  197. // https://w3c.github.io/webcrypto/#rsa-oaep-operations
  198. WebIDL::ExceptionOr<JS::NonnullGCPtr<JS::Object>> RSAOAEP::export_key(Bindings::KeyFormat format, JS::NonnullGCPtr<CryptoKey> key)
  199. {
  200. auto& realm = m_realm;
  201. auto& vm = realm.vm();
  202. // 1. Let key be the key to be exported.
  203. // 2. If the underlying cryptographic key material represented by the [[handle]] internal slot of key cannot be accessed, then throw an OperationError.
  204. // Note: In our impl this is always accessible
  205. auto const& handle = key->handle();
  206. JS::GCPtr<JS::Object> result = nullptr;
  207. // 3. If format is "spki"
  208. if (format == Bindings::KeyFormat::Spki) {
  209. // 1. If the [[type]] internal slot of key is not "public", then throw an InvalidAccessError.
  210. if (key->type() != Bindings::KeyType::Public)
  211. return WebIDL::InvalidAccessError::create(realm, "Key is not public"_fly_string);
  212. // FIXME: 2. Let data be an instance of the subjectPublicKeyInfo ASN.1 structure defined in [RFC5280] with the following properties:
  213. // - Set the algorithm field to an AlgorithmIdentifier ASN.1 type with the following properties:
  214. // - Set the algorithm field to the OID rsaEncryption defined in [RFC3447].
  215. // - Set the params field to the ASN.1 type NULL.
  216. // - Set the subjectPublicKey field to the result of DER-encoding an RSAPublicKey ASN.1 type, as defined in [RFC3447], Appendix A.1.1,
  217. // that represents the RSA public key represented by the [[handle]] internal slot of key
  218. // FIXME: 3. Let result be the result of creating an ArrayBuffer containing data.
  219. result = JS::ArrayBuffer::create(realm, TRY_OR_THROW_OOM(vm, ByteBuffer::copy(("FIXME"sv).bytes())));
  220. }
  221. // FIXME: If format is "pkcs8"
  222. // If format is "jwk"
  223. else if (format == Bindings::KeyFormat::Jwk) {
  224. // 1. Let jwk be a new JsonWebKey dictionary.
  225. Bindings::JsonWebKey jwk = {};
  226. // 2. Set the kty attribute of jwk to the string "RSA".
  227. jwk.kty = "RSA"_string;
  228. // 4. Let hash be the name attribute of the hash attribute of the [[algorithm]] internal slot of key.
  229. 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> {
  230. auto name_property = TRY(obj->get("name"));
  231. return name_property.to_string(realm.vm()); }));
  232. // 4. If hash is "SHA-1":
  233. // - Set the alg attribute of jwk to the string "RSA-OAEP".
  234. if (hash == "SHA-1"sv) {
  235. jwk.alg = "RSA-OAEP"_string;
  236. }
  237. // If hash is "SHA-256":
  238. // - Set the alg attribute of jwk to the string "RSA-OAEP-256".
  239. else if (hash == "SHA-256"sv) {
  240. jwk.alg = "RSA-OAEP-256"_string;
  241. }
  242. // If hash is "SHA-384":
  243. // - Set the alg attribute of jwk to the string "RSA-OAEP-384".
  244. else if (hash == "SHA-384"sv) {
  245. jwk.alg = "RSA-OAEP-384"_string;
  246. }
  247. // If hash is "SHA-512":
  248. // - Set the alg attribute of jwk to the string "RSA-OAEP-512".
  249. else if (hash == "SHA-512"sv) {
  250. jwk.alg = "RSA-OAEP-512"_string;
  251. } else {
  252. // FIXME: Support 'other applicable specifications'
  253. // - Perform any key export steps defined by other applicable specifications,
  254. // passing format and the hash attribute of the [[algorithm]] internal slot of key and obtaining alg.
  255. // - Set the alg attribute of jwk to alg.
  256. return WebIDL::NotSupportedError::create(realm, TRY_OR_THROW_OOM(vm, String::formatted("Unsupported hash algorithm '{}'", hash)));
  257. }
  258. // 10. Set the attributes n and e of jwk according to the corresponding definitions in JSON Web Algorithms [JWA], Section 6.3.1.
  259. auto maybe_error = handle.visit(
  260. [&](::Crypto::PK::RSAPublicKey<> const& public_key) -> ErrorOr<void> {
  261. jwk.n = TRY(base64_url_uint_encode(public_key.modulus()));
  262. jwk.e = TRY(base64_url_uint_encode(public_key.public_exponent()));
  263. return {};
  264. },
  265. [&](::Crypto::PK::RSAPrivateKey<> const& private_key) -> ErrorOr<void> {
  266. jwk.n = TRY(base64_url_uint_encode(private_key.modulus()));
  267. jwk.e = TRY(base64_url_uint_encode(private_key.public_exponent()));
  268. // 11. If the [[type]] internal slot of key is "private":
  269. // 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.
  270. jwk.d = TRY(base64_url_uint_encode(private_key.private_exponent()));
  271. // FIXME: Add p, q, dq, qi
  272. // 12. If the underlying RSA private key represented by the [[handle]] internal slot of key is represented by more than two primes,
  273. // set the attribute named oth of jwk according to the corresponding definition in JSON Web Algorithms [JWA], Section 6.3.2.7
  274. // FIXME: We don't support more than 2 primes on RSA keys
  275. return {};
  276. },
  277. [](auto) -> ErrorOr<void> {
  278. VERIFY_NOT_REACHED();
  279. });
  280. // FIXME: clang-format butchers the visit if we do the TRY inline
  281. TRY_OR_THROW_OOM(vm, maybe_error);
  282. // 13. Set the key_ops attribute of jwk to the usages attribute of key.
  283. jwk.key_ops = Vector<String> {};
  284. jwk.key_ops->ensure_capacity(key->internal_usages().size());
  285. for (auto const& usage : key->internal_usages()) {
  286. jwk.key_ops->append(Bindings::idl_enum_to_string(usage));
  287. }
  288. // 14. Set the ext attribute of jwk to the [[extractable]] internal slot of key.
  289. jwk.ext = key->extractable();
  290. // 15. Let result be the result of converting jwk to an ECMAScript Object, as defined by [WebIDL].
  291. result = TRY(jwk.to_object(realm));
  292. }
  293. // Otherwise throw a NotSupportedError.
  294. else {
  295. return WebIDL::NotSupportedError::create(realm, TRY_OR_THROW_OOM(vm, String::formatted("Exporting to format {} is not supported", Bindings::idl_enum_to_string(format))));
  296. }
  297. // 8. Return result
  298. return JS::NonnullGCPtr { *result };
  299. }
  300. 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)
  301. {
  302. // 1. If format is not "raw", throw a NotSupportedError
  303. if (format != Bindings::KeyFormat::Raw) {
  304. return WebIDL::NotSupportedError::create(m_realm, "Only raw format is supported"_fly_string);
  305. }
  306. // 2. If usages contains a value that is not "deriveKey" or "deriveBits", then throw a SyntaxError.
  307. for (auto& usage : key_usages) {
  308. if (usage != Bindings::KeyUsage::Derivekey && usage != Bindings::KeyUsage::Derivebits) {
  309. return WebIDL::SyntaxError::create(m_realm, MUST(String::formatted("Invalid key usage '{}'", idl_enum_to_string(usage))));
  310. }
  311. }
  312. // 3. If extractable is not false, then throw a SyntaxError.
  313. if (extractable)
  314. return WebIDL::SyntaxError::create(m_realm, "extractable must be false"_fly_string);
  315. // 4. Let key be a new CryptoKey representing keyData.
  316. auto key = CryptoKey::create(m_realm, move(key_data));
  317. // 5. Set the [[type]] internal slot of key to "secret".
  318. key->set_type(Bindings::KeyType::Secret);
  319. // 6. Set the [[extractable]] internal slot of key to false.
  320. key->set_extractable(false);
  321. // 7. Let algorithm be a new KeyAlgorithm object.
  322. auto algorithm = KeyAlgorithm::create(m_realm);
  323. // 8. Set the name attribute of algorithm to "PBKDF2".
  324. algorithm->set_name("PBKDF2"_string);
  325. // 9. Set the [[algorithm]] internal slot of key to algorithm.
  326. key->set_algorithm(algorithm);
  327. // 10. Return key.
  328. return key;
  329. }
  330. WebIDL::ExceptionOr<JS::NonnullGCPtr<JS::ArrayBuffer>> SHA::digest(AlgorithmParams const& algorithm, ByteBuffer const& data)
  331. {
  332. auto& algorithm_name = algorithm.name;
  333. ::Crypto::Hash::HashKind hash_kind;
  334. if (algorithm_name.equals_ignoring_ascii_case("SHA-1"sv)) {
  335. hash_kind = ::Crypto::Hash::HashKind::SHA1;
  336. } else if (algorithm_name.equals_ignoring_ascii_case("SHA-256"sv)) {
  337. hash_kind = ::Crypto::Hash::HashKind::SHA256;
  338. } else if (algorithm_name.equals_ignoring_ascii_case("SHA-384"sv)) {
  339. hash_kind = ::Crypto::Hash::HashKind::SHA384;
  340. } else if (algorithm_name.equals_ignoring_ascii_case("SHA-512"sv)) {
  341. hash_kind = ::Crypto::Hash::HashKind::SHA512;
  342. } else {
  343. return WebIDL::NotSupportedError::create(m_realm, MUST(String::formatted("Invalid hash function '{}'", algorithm_name)));
  344. }
  345. ::Crypto::Hash::Manager hash { hash_kind };
  346. hash.update(data);
  347. auto digest = hash.digest();
  348. auto result_buffer = ByteBuffer::copy(digest.immutable_data(), hash.digest_size());
  349. if (result_buffer.is_error())
  350. return WebIDL::OperationError::create(m_realm, "Failed to create result buffer"_fly_string);
  351. return JS::ArrayBuffer::create(m_realm, result_buffer.release_value());
  352. }
  353. }