CryptoAlgorithms.cpp 45 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902
  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. RsaOaepParams::~RsaOaepParams() = default;
  256. JS::ThrowCompletionOr<NonnullOwnPtr<AlgorithmParams>> RsaOaepParams::from_value(JS::VM& vm, JS::Value value)
  257. {
  258. auto& object = value.as_object();
  259. auto name_value = TRY(object.get("name"));
  260. auto name = TRY(name_value.to_string(vm));
  261. auto label_value = TRY(object.get("label"));
  262. ByteBuffer label;
  263. if (!label_value.is_nullish()) {
  264. if (!label_value.is_object() || !(is<JS::TypedArrayBase>(label_value.as_object()) || is<JS::ArrayBuffer>(label_value.as_object()) || is<JS::DataView>(label_value.as_object())))
  265. return vm.throw_completion<JS::TypeError>(JS::ErrorType::NotAnObjectOfType, "BufferSource");
  266. label = TRY_OR_THROW_OOM(vm, WebIDL::get_buffer_source_copy(label_value.as_object()));
  267. }
  268. return adopt_own<AlgorithmParams>(*new RsaOaepParams { name, move(label) });
  269. }
  270. // https://w3c.github.io/webcrypto/#rsa-oaep-operations
  271. WebIDL::ExceptionOr<JS::NonnullGCPtr<JS::ArrayBuffer>> RSAOAEP::encrypt(AlgorithmParams const& params, JS::NonnullGCPtr<CryptoKey> key, ByteBuffer const& plaintext)
  272. {
  273. auto& realm = m_realm;
  274. auto& vm = realm.vm();
  275. auto const& normalized_algorithm = static_cast<RsaOaepParams const&>(params);
  276. // 1. If the [[type]] internal slot of key is not "public", then throw an InvalidAccessError.
  277. if (key->type() != Bindings::KeyType::Public)
  278. return WebIDL::InvalidAccessError::create(realm, "Key is not a public key"_fly_string);
  279. // 2. Let label be the contents of the label member of normalizedAlgorithm or the empty octet string if the label member of normalizedAlgorithm is not present.
  280. [[maybe_unused]] auto const& label = normalized_algorithm.label;
  281. // 3. Perform the encryption operation defined in Section 7.1 of [RFC3447] with the key represented by key as the recipient's RSA public key,
  282. // the contents of plaintext as the message to be encrypted, M and label as the label, L, and with the hash function specified by the hash attribute
  283. // of the [[algorithm]] internal slot of key as the Hash option and MGF1 (defined in Section B.2.1 of [RFC3447]) as the MGF option.
  284. // 4. If performing the operation results in an error, then throw an OperationError.
  285. // 5. Let ciphertext be the value C that results from performing the operation.
  286. // FIXME: Actually encrypt the data
  287. auto ciphertext = TRY_OR_THROW_OOM(vm, ByteBuffer::copy(plaintext));
  288. // 6. Return the result of creating an ArrayBuffer containing ciphertext.
  289. return JS::ArrayBuffer::create(realm, move(ciphertext));
  290. }
  291. // https://w3c.github.io/webcrypto/#rsa-oaep-operations
  292. WebIDL::ExceptionOr<Variant<JS::NonnullGCPtr<CryptoKey>, JS::NonnullGCPtr<CryptoKeyPair>>> RSAOAEP::generate_key(AlgorithmParams const& params, bool extractable, Vector<Bindings::KeyUsage> const& key_usages)
  293. {
  294. // 1. If usages contains an entry which is not "encrypt", "decrypt", "wrapKey" or "unwrapKey", then throw a SyntaxError.
  295. for (auto const& usage : key_usages) {
  296. if (usage != Bindings::KeyUsage::Encrypt && usage != Bindings::KeyUsage::Decrypt && usage != Bindings::KeyUsage::Wrapkey && usage != Bindings::KeyUsage::Unwrapkey) {
  297. return WebIDL::SyntaxError::create(m_realm, MUST(String::formatted("Invalid key usage '{}'", idl_enum_to_string(usage))));
  298. }
  299. }
  300. // 2. Generate an RSA key pair, as defined in [RFC3447], with RSA modulus length equal to the modulusLength member of normalizedAlgorithm
  301. // and RSA public exponent equal to the publicExponent member of normalizedAlgorithm.
  302. // 3. If performing the operation results in an error, then throw an OperationError.
  303. auto const& normalized_algorithm = static_cast<RsaHashedKeyGenParams const&>(params);
  304. auto key_pair = ::Crypto::PK::RSA::generate_key_pair(normalized_algorithm.modulus_length, normalized_algorithm.public_exponent);
  305. // 4. Let algorithm be a new RsaHashedKeyAlgorithm object.
  306. auto algorithm = RsaHashedKeyAlgorithm::create(m_realm);
  307. // 5. Set the name attribute of algorithm to "RSA-OAEP".
  308. algorithm->set_name("RSA-OAEP"_string);
  309. // 6. Set the modulusLength attribute of algorithm to equal the modulusLength member of normalizedAlgorithm.
  310. algorithm->set_modulus_length(normalized_algorithm.modulus_length);
  311. // 7. Set the publicExponent attribute of algorithm to equal the publicExponent member of normalizedAlgorithm.
  312. TRY(algorithm->set_public_exponent(normalized_algorithm.public_exponent));
  313. // 8. Set the hash attribute of algorithm to equal the hash member of normalizedAlgorithm.
  314. algorithm->set_hash(normalized_algorithm.hash);
  315. // 9. Let publicKey be a new CryptoKey representing the public key of the generated key pair.
  316. auto public_key = CryptoKey::create(m_realm, CryptoKey::InternalKeyData { key_pair.public_key });
  317. // 10. Set the [[type]] internal slot of publicKey to "public"
  318. public_key->set_type(Bindings::KeyType::Public);
  319. // 11. Set the [[algorithm]] internal slot of publicKey to algorithm.
  320. public_key->set_algorithm(algorithm);
  321. // 12. Set the [[extractable]] internal slot of publicKey to true.
  322. public_key->set_extractable(true);
  323. // 13. Set the [[usages]] internal slot of publicKey to be the usage intersection of usages and [ "encrypt", "wrapKey" ].
  324. public_key->set_usages(usage_intersection(key_usages, { { Bindings::KeyUsage::Encrypt, Bindings::KeyUsage::Wrapkey } }));
  325. // 14. Let privateKey be a new CryptoKey representing the private key of the generated key pair.
  326. auto private_key = CryptoKey::create(m_realm, CryptoKey::InternalKeyData { key_pair.private_key });
  327. // 15. Set the [[type]] internal slot of privateKey to "private"
  328. private_key->set_type(Bindings::KeyType::Private);
  329. // 16. Set the [[algorithm]] internal slot of privateKey to algorithm.
  330. private_key->set_algorithm(algorithm);
  331. // 17. Set the [[extractable]] internal slot of privateKey to extractable.
  332. private_key->set_extractable(extractable);
  333. // 18. Set the [[usages]] internal slot of privateKey to be the usage intersection of usages and [ "decrypt", "unwrapKey" ].
  334. private_key->set_usages(usage_intersection(key_usages, { { Bindings::KeyUsage::Decrypt, Bindings::KeyUsage::Unwrapkey } }));
  335. // 19. Let result be a new CryptoKeyPair dictionary.
  336. // 20. Set the publicKey attribute of result to be publicKey.
  337. // 21. Set the privateKey attribute of result to be privateKey.
  338. // 22. Return the result of converting result to an ECMAScript Object, as defined by [WebIDL].
  339. return Variant<JS::NonnullGCPtr<CryptoKey>, JS::NonnullGCPtr<CryptoKeyPair>> { CryptoKeyPair::create(m_realm, public_key, private_key) };
  340. }
  341. // https://w3c.github.io/webcrypto/#rsa-oaep-operations
  342. 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)
  343. {
  344. auto& realm = m_realm;
  345. // 1. Let keyData be the key data to be imported.
  346. JS::GCPtr<CryptoKey> key = nullptr;
  347. auto const& normalized_algorithm = static_cast<RsaHashedImportParams const&>(params);
  348. // 2. -> If format is "spki":
  349. if (key_format == Bindings::KeyFormat::Spki) {
  350. // 1. If usages contains an entry which is not "encrypt" or "wrapKey", then throw a SyntaxError.
  351. for (auto const& usage : usages) {
  352. if (usage != Bindings::KeyUsage::Encrypt && usage != Bindings::KeyUsage::Wrapkey) {
  353. return WebIDL::SyntaxError::create(m_realm, MUST(String::formatted("Invalid key usage '{}'", idl_enum_to_string(usage))));
  354. }
  355. }
  356. VERIFY(key_data.has<ByteBuffer>());
  357. // 2. Let spki be the result of running the parse a subjectPublicKeyInfo algorithm over keyData.
  358. // 3. If an error occurred while parsing, then throw a DataError.
  359. auto spki = TRY(parse_a_subject_public_key_info(m_realm, key_data.get<ByteBuffer>()));
  360. // 4. If the algorithm object identifier field of the algorithm AlgorithmIdentifier field of spki
  361. // is not equal to the rsaEncryption object identifier defined in [RFC3447], then throw a DataError.
  362. if (spki.algorithm.identifier != TLS::rsa_encryption_oid)
  363. return WebIDL::DataError::create(m_realm, "Algorithm object identifier is not the rsaEncryption object identifier"_fly_string);
  364. // 5. Let publicKey be the result of performing the parse an ASN.1 structure algorithm,
  365. // with data as the subjectPublicKeyInfo field of spki, structure as the RSAPublicKey structure
  366. // specified in Section A.1.1 of [RFC3447], and exactData set to true.
  367. // NOTE: We already did this in parse_a_subject_public_key_info
  368. auto& public_key = spki.rsa;
  369. // 6. If an error occurred while parsing, or it can be determined that publicKey is not
  370. // a valid public key according to [RFC3447], then throw a DataError.
  371. // FIXME: Validate the public key
  372. // 7. Let key be a new CryptoKey that represents the RSA public key identified by publicKey.
  373. key = CryptoKey::create(m_realm, CryptoKey::InternalKeyData { public_key });
  374. // 8. Set the [[type]] internal slot of key to "public"
  375. key->set_type(Bindings::KeyType::Public);
  376. }
  377. // -> If format is "pkcs8":
  378. else if (key_format == Bindings::KeyFormat::Pkcs8) {
  379. // 1. If usages contains an entry which is not "decrypt" or "unwrapKey", then throw a SyntaxError.
  380. for (auto const& usage : usages) {
  381. if (usage != Bindings::KeyUsage::Decrypt && usage != Bindings::KeyUsage::Unwrapkey) {
  382. return WebIDL::SyntaxError::create(m_realm, MUST(String::formatted("Invalid key usage '{}'", idl_enum_to_string(usage))));
  383. }
  384. }
  385. VERIFY(key_data.has<ByteBuffer>());
  386. // 2. Let privateKeyInfo be the result of running the parse a privateKeyInfo algorithm over keyData.
  387. // 3. If an error occurred while parsing, then throw a DataError.
  388. auto private_key_info = TRY(parse_a_private_key_info(m_realm, key_data.get<ByteBuffer>()));
  389. // 4. If the algorithm object identifier field of the privateKeyAlgorithm PrivateKeyAlgorithm field of privateKeyInfo
  390. // is not equal to the rsaEncryption object identifier defined in [RFC3447], then throw a DataError.
  391. if (private_key_info.algorithm.identifier != TLS::rsa_encryption_oid)
  392. return WebIDL::DataError::create(m_realm, "Algorithm object identifier is not the rsaEncryption object identifier"_fly_string);
  393. // 5. Let rsaPrivateKey be the result of performing the parse an ASN.1 structure algorithm,
  394. // with data as the privateKey field of privateKeyInfo, structure as the RSAPrivateKey structure
  395. // specified in Section A.1.2 of [RFC3447], and exactData set to true.
  396. // NOTE: We already did this in parse_a_private_key_info
  397. auto& rsa_private_key = private_key_info.rsa;
  398. // 6. If an error occurred while parsing, or if rsaPrivateKey is not
  399. // a valid RSA private key according to [RFC3447], then throw a DataError.
  400. // FIXME: Validate the private key
  401. // 7. Let key be a new CryptoKey that represents the RSA private key identified by rsaPrivateKey.
  402. key = CryptoKey::create(m_realm, CryptoKey::InternalKeyData { rsa_private_key });
  403. // 8. Set the [[type]] internal slot of key to "private"
  404. key->set_type(Bindings::KeyType::Private);
  405. }
  406. // -> If format is "jwk":
  407. else if (key_format == Bindings::KeyFormat::Jwk) {
  408. // 1. -> If keyData is a JsonWebKey dictionary:
  409. // Let jwk equal keyData.
  410. // -> Otherwise:
  411. // Throw a DataError.
  412. if (!key_data.has<Bindings::JsonWebKey>())
  413. return WebIDL::DataError::create(m_realm, "keyData is not a JsonWebKey dictionary"_fly_string);
  414. auto& jwk = key_data.get<Bindings::JsonWebKey>();
  415. // 2. If the d field of jwk is present and usages contains an entry which is not "decrypt" or "unwrapKey", then throw a SyntaxError.
  416. if (jwk.d.has_value()) {
  417. for (auto const& usage : usages) {
  418. if (usage != Bindings::KeyUsage::Decrypt && usage != Bindings::KeyUsage::Unwrapkey) {
  419. return WebIDL::SyntaxError::create(m_realm, MUST(String::formatted("Invalid key usage '{}'", Bindings::idl_enum_to_string(usage))));
  420. }
  421. }
  422. }
  423. // 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.
  424. if (!jwk.d.has_value()) {
  425. for (auto const& usage : usages) {
  426. if (usage != Bindings::KeyUsage::Encrypt && usage != Bindings::KeyUsage::Wrapkey) {
  427. return WebIDL::SyntaxError::create(m_realm, MUST(String::formatted("Invalid key usage '{}'", Bindings::idl_enum_to_string(usage))));
  428. }
  429. }
  430. }
  431. // 4. If the kty field of jwk is not a case-sensitive string match to "RSA", then throw a DataError.
  432. if (jwk.kty != "RSA"_string)
  433. return WebIDL::DataError::create(m_realm, "Invalid key type"_fly_string);
  434. // 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.
  435. if (!usages.is_empty() && jwk.use.has_value() && *jwk.use != "enc"_string)
  436. return WebIDL::DataError::create(m_realm, "Invalid use field"_fly_string);
  437. // 6. If the key_ops field of jwk is present, and is invalid according to the requirements of JSON Web Key [JWK]
  438. // or does not contain all of the specified usages values, then throw a DataError.
  439. for (auto const& usage : usages) {
  440. if (!jwk.key_ops->contains_slow(Bindings::idl_enum_to_string(usage)))
  441. return WebIDL::DataError::create(m_realm, MUST(String::formatted("Missing key_ops field: {}", Bindings::idl_enum_to_string(usage))));
  442. }
  443. // FIXME: Validate jwk.key_ops against requirements in https://www.rfc-editor.org/rfc/rfc7517#section-4.3
  444. // 7. If the ext field of jwk is present and has the value false and extractable is true, then throw a DataError.
  445. if (jwk.ext.has_value() && !*jwk.ext && extractable)
  446. return WebIDL::DataError::create(m_realm, "Invalid ext field"_fly_string);
  447. Optional<String> hash = {};
  448. // 8. -> If the alg field of jwk is not present:
  449. if (!jwk.alg.has_value()) {
  450. // Let hash be undefined.
  451. }
  452. // -> If the alg field of jwk is equal to "RSA-OAEP":
  453. if (jwk.alg == "RSA-OAEP"sv) {
  454. // Let hash be the string "SHA-1".
  455. hash = "SHA-1"_string;
  456. }
  457. // -> If the alg field of jwk is equal to "RSA-OAEP-256":
  458. else if (jwk.alg == "RSA-OAEP-256"sv) {
  459. // Let hash be the string "SHA-256".
  460. hash = "SHA-256"_string;
  461. }
  462. // -> If the alg field of jwk is equal to "RSA-OAEP-384":
  463. else if (jwk.alg == "RSA-OAEP-384"sv) {
  464. // Let hash be the string "SHA-384".
  465. hash = "SHA-384"_string;
  466. }
  467. // -> If the alg field of jwk is equal to "RSA-OAEP-512":
  468. else if (jwk.alg == "RSA-OAEP-512"sv) {
  469. // Let hash be the string "SHA-512".
  470. hash = "SHA-512"_string;
  471. }
  472. // -> Otherwise:
  473. else {
  474. // FIXME: Support 'other applicable specifications'
  475. // 1. Perform any key import steps defined by other applicable specifications, passing format, jwk and obtaining hash.
  476. // 2. If an error occurred or there are no applicable specifications, throw a DataError.
  477. return WebIDL::DataError::create(m_realm, "Invalid alg field"_fly_string);
  478. }
  479. // 9. If hash is not undefined:
  480. if (hash.has_value()) {
  481. // 1. Let normalizedHash be the result of normalize an algorithm with alg set to hash and op set to digest.
  482. auto normalized_hash = TRY(normalize_an_algorithm(m_realm, AlgorithmIdentifier { *hash }, "digest"_string));
  483. // 2. If normalizedHash is not equal to the hash member of normalizedAlgorithm, throw a DataError.
  484. 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> {
  485. auto name_property = TRY(obj->get("name"));
  486. return name_property.to_string(m_realm.vm()); })))
  487. return WebIDL::DataError::create(m_realm, "Invalid hash"_fly_string);
  488. }
  489. // 10. -> If the d field of jwk is present:
  490. if (jwk.d.has_value()) {
  491. // 1. If jwk does not meet the requirements of Section 6.3.2 of JSON Web Algorithms [JWA], then throw a DataError.
  492. bool meets_requirements = jwk.e.has_value() && jwk.n.has_value() && jwk.d.has_value();
  493. if (jwk.p.has_value() || jwk.q.has_value() || jwk.dp.has_value() || jwk.dq.has_value() || jwk.qi.has_value())
  494. meets_requirements |= jwk.p.has_value() && jwk.q.has_value() && jwk.dp.has_value() && jwk.dq.has_value() && jwk.qi.has_value();
  495. if (jwk.oth.has_value()) {
  496. // FIXME: We don't support > 2 primes in RSA keys
  497. meets_requirements = false;
  498. }
  499. if (!meets_requirements)
  500. return WebIDL::DataError::create(m_realm, "Invalid JWK private key"_fly_string);
  501. // FIXME: Spec error, it should say 'the RSA private key identified by interpreting jwk according to section 6.3.2'
  502. // 2. Let privateKey represent the RSA public key identified by interpreting jwk according to Section 6.3.1 of JSON Web Algorithms [JWA].
  503. auto private_key = TRY(parse_jwk_rsa_private_key(realm, jwk));
  504. // FIXME: Spec error, it should say 'not to be a valid RSA private key'
  505. // 3. If privateKey can be determined to not be a valid RSA public key according to [RFC3447], then throw a DataError.
  506. // FIXME: Validate the private key
  507. // 4. Let key be a new CryptoKey representing privateKey.
  508. key = CryptoKey::create(m_realm, CryptoKey::InternalKeyData { private_key });
  509. // 5. Set the [[type]] internal slot of key to "private"
  510. key->set_type(Bindings::KeyType::Private);
  511. }
  512. // -> Otherwise:
  513. else {
  514. // 1. If jwk does not meet the requirements of Section 6.3.1 of JSON Web Algorithms [JWA], then throw a DataError.
  515. if (!jwk.e.has_value() || !jwk.n.has_value())
  516. return WebIDL::DataError::create(m_realm, "Invalid JWK public key"_fly_string);
  517. // 2. Let publicKey represent the RSA public key identified by interpreting jwk according to Section 6.3.1 of JSON Web Algorithms [JWA].
  518. auto public_key = TRY(parse_jwk_rsa_public_key(realm, jwk));
  519. // 3. If publicKey can be determined to not be a valid RSA public key according to [RFC3447], then throw a DataError.
  520. // FIXME: Validate the public key
  521. // 4. Let key be a new CryptoKey representing publicKey.
  522. key = CryptoKey::create(m_realm, CryptoKey::InternalKeyData { public_key });
  523. // 5. Set the [[type]] internal slot of key to "public"
  524. key->set_type(Bindings::KeyType::Public);
  525. }
  526. }
  527. // -> Otherwise: throw a NotSupportedError.
  528. else {
  529. return WebIDL::NotSupportedError::create(m_realm, "Unsupported key format"_fly_string);
  530. }
  531. // 3. Let algorithm be a new RsaHashedKeyAlgorithm.
  532. auto algorithm = RsaHashedKeyAlgorithm::create(m_realm);
  533. // 4. Set the name attribute of algorithm to "RSA-OAEP"
  534. algorithm->set_name("RSA-OAEP"_string);
  535. // 5. Set the modulusLength attribute of algorithm to the length, in bits, of the RSA public modulus.
  536. // 6. Set the publicExponent attribute of algorithm to the BigInteger representation of the RSA public exponent.
  537. TRY(key->handle().visit(
  538. [&](::Crypto::PK::RSAPublicKey<> const& public_key) -> WebIDL::ExceptionOr<void> {
  539. algorithm->set_modulus_length(public_key.length());
  540. TRY(algorithm->set_public_exponent(public_key.public_exponent()));
  541. return {};
  542. },
  543. [&](::Crypto::PK::RSAPrivateKey<> const& private_key) -> WebIDL::ExceptionOr<void> {
  544. algorithm->set_modulus_length(private_key.length());
  545. TRY(algorithm->set_public_exponent(private_key.public_exponent()));
  546. return {};
  547. },
  548. [](auto) -> WebIDL::ExceptionOr<void> { VERIFY_NOT_REACHED(); }));
  549. // 7. Set the hash attribute of algorithm to the hash member of normalizedAlgorithm.
  550. algorithm->set_hash(normalized_algorithm.hash);
  551. // 8. Set the [[algorithm]] internal slot of key to algorithm
  552. key->set_algorithm(algorithm);
  553. // 9. Return key.
  554. return JS::NonnullGCPtr { *key };
  555. }
  556. // https://w3c.github.io/webcrypto/#rsa-oaep-operations
  557. WebIDL::ExceptionOr<JS::NonnullGCPtr<JS::Object>> RSAOAEP::export_key(Bindings::KeyFormat format, JS::NonnullGCPtr<CryptoKey> key)
  558. {
  559. auto& realm = m_realm;
  560. auto& vm = realm.vm();
  561. // 1. Let key be the key to be exported.
  562. // 2. If the underlying cryptographic key material represented by the [[handle]] internal slot of key cannot be accessed, then throw an OperationError.
  563. // Note: In our impl this is always accessible
  564. auto const& handle = key->handle();
  565. JS::GCPtr<JS::Object> result = nullptr;
  566. // 3. If format is "spki"
  567. if (format == Bindings::KeyFormat::Spki) {
  568. // 1. If the [[type]] internal slot of key is not "public", then throw an InvalidAccessError.
  569. if (key->type() != Bindings::KeyType::Public)
  570. return WebIDL::InvalidAccessError::create(realm, "Key is not public"_fly_string);
  571. // FIXME: 2. Let data be an instance of the subjectPublicKeyInfo ASN.1 structure defined in [RFC5280] with the following properties:
  572. // - Set the algorithm field to an AlgorithmIdentifier ASN.1 type with the following properties:
  573. // - Set the algorithm field to the OID rsaEncryption defined in [RFC3447].
  574. // - Set the params field to the ASN.1 type NULL.
  575. // - Set the subjectPublicKey field to the result of DER-encoding an RSAPublicKey ASN.1 type, as defined in [RFC3447], Appendix A.1.1,
  576. // that represents the RSA public key represented by the [[handle]] internal slot of key
  577. // FIXME: 3. Let result be the result of creating an ArrayBuffer containing data.
  578. result = JS::ArrayBuffer::create(realm, TRY_OR_THROW_OOM(vm, ByteBuffer::copy(("FIXME"sv).bytes())));
  579. }
  580. // FIXME: If format is "pkcs8"
  581. // If format is "jwk"
  582. else if (format == Bindings::KeyFormat::Jwk) {
  583. // 1. Let jwk be a new JsonWebKey dictionary.
  584. Bindings::JsonWebKey jwk = {};
  585. // 2. Set the kty attribute of jwk to the string "RSA".
  586. jwk.kty = "RSA"_string;
  587. // 4. Let hash be the name attribute of the hash attribute of the [[algorithm]] internal slot of key.
  588. 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> {
  589. auto name_property = TRY(obj->get("name"));
  590. return name_property.to_string(realm.vm()); }));
  591. // 4. If hash is "SHA-1":
  592. // - Set the alg attribute of jwk to the string "RSA-OAEP".
  593. if (hash == "SHA-1"sv) {
  594. jwk.alg = "RSA-OAEP"_string;
  595. }
  596. // If hash is "SHA-256":
  597. // - Set the alg attribute of jwk to the string "RSA-OAEP-256".
  598. else if (hash == "SHA-256"sv) {
  599. jwk.alg = "RSA-OAEP-256"_string;
  600. }
  601. // If hash is "SHA-384":
  602. // - Set the alg attribute of jwk to the string "RSA-OAEP-384".
  603. else if (hash == "SHA-384"sv) {
  604. jwk.alg = "RSA-OAEP-384"_string;
  605. }
  606. // If hash is "SHA-512":
  607. // - Set the alg attribute of jwk to the string "RSA-OAEP-512".
  608. else if (hash == "SHA-512"sv) {
  609. jwk.alg = "RSA-OAEP-512"_string;
  610. } else {
  611. // FIXME: Support 'other applicable specifications'
  612. // - Perform any key export steps defined by other applicable specifications,
  613. // passing format and the hash attribute of the [[algorithm]] internal slot of key and obtaining alg.
  614. // - Set the alg attribute of jwk to alg.
  615. return WebIDL::NotSupportedError::create(realm, TRY_OR_THROW_OOM(vm, String::formatted("Unsupported hash algorithm '{}'", hash)));
  616. }
  617. // 10. Set the attributes n and e of jwk according to the corresponding definitions in JSON Web Algorithms [JWA], Section 6.3.1.
  618. auto maybe_error = handle.visit(
  619. [&](::Crypto::PK::RSAPublicKey<> const& public_key) -> ErrorOr<void> {
  620. jwk.n = TRY(base64_url_uint_encode(public_key.modulus()));
  621. jwk.e = TRY(base64_url_uint_encode(public_key.public_exponent()));
  622. return {};
  623. },
  624. [&](::Crypto::PK::RSAPrivateKey<> const& private_key) -> ErrorOr<void> {
  625. jwk.n = TRY(base64_url_uint_encode(private_key.modulus()));
  626. jwk.e = TRY(base64_url_uint_encode(private_key.public_exponent()));
  627. // 11. If the [[type]] internal slot of key is "private":
  628. // 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.
  629. jwk.d = TRY(base64_url_uint_encode(private_key.private_exponent()));
  630. jwk.p = TRY(base64_url_uint_encode(private_key.prime1()));
  631. jwk.q = TRY(base64_url_uint_encode(private_key.prime2()));
  632. jwk.dp = TRY(base64_url_uint_encode(private_key.exponent1()));
  633. jwk.dq = TRY(base64_url_uint_encode(private_key.exponent2()));
  634. jwk.qi = TRY(base64_url_uint_encode(private_key.coefficient()));
  635. // 12. If the underlying RSA private key represented by the [[handle]] internal slot of key is represented by more than two primes,
  636. // set the attribute named oth of jwk according to the corresponding definition in JSON Web Algorithms [JWA], Section 6.3.2.7
  637. // FIXME: We don't support more than 2 primes on RSA keys
  638. return {};
  639. },
  640. [](auto) -> ErrorOr<void> {
  641. VERIFY_NOT_REACHED();
  642. });
  643. // FIXME: clang-format butchers the visit if we do the TRY inline
  644. TRY_OR_THROW_OOM(vm, maybe_error);
  645. // 13. Set the key_ops attribute of jwk to the usages attribute of key.
  646. jwk.key_ops = Vector<String> {};
  647. jwk.key_ops->ensure_capacity(key->internal_usages().size());
  648. for (auto const& usage : key->internal_usages()) {
  649. jwk.key_ops->append(Bindings::idl_enum_to_string(usage));
  650. }
  651. // 14. Set the ext attribute of jwk to the [[extractable]] internal slot of key.
  652. jwk.ext = key->extractable();
  653. // 15. Let result be the result of converting jwk to an ECMAScript Object, as defined by [WebIDL].
  654. result = TRY(jwk.to_object(realm));
  655. }
  656. // Otherwise throw a NotSupportedError.
  657. else {
  658. return WebIDL::NotSupportedError::create(realm, TRY_OR_THROW_OOM(vm, String::formatted("Exporting to format {} is not supported", Bindings::idl_enum_to_string(format))));
  659. }
  660. // 8. Return result
  661. return JS::NonnullGCPtr { *result };
  662. }
  663. 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)
  664. {
  665. // 1. If format is not "raw", throw a NotSupportedError
  666. if (format != Bindings::KeyFormat::Raw) {
  667. return WebIDL::NotSupportedError::create(m_realm, "Only raw format is supported"_fly_string);
  668. }
  669. // 2. If usages contains a value that is not "deriveKey" or "deriveBits", then throw a SyntaxError.
  670. for (auto& usage : key_usages) {
  671. if (usage != Bindings::KeyUsage::Derivekey && usage != Bindings::KeyUsage::Derivebits) {
  672. return WebIDL::SyntaxError::create(m_realm, MUST(String::formatted("Invalid key usage '{}'", idl_enum_to_string(usage))));
  673. }
  674. }
  675. // 3. If extractable is not false, then throw a SyntaxError.
  676. if (extractable)
  677. return WebIDL::SyntaxError::create(m_realm, "extractable must be false"_fly_string);
  678. // 4. Let key be a new CryptoKey representing keyData.
  679. auto key = CryptoKey::create(m_realm, move(key_data));
  680. // 5. Set the [[type]] internal slot of key to "secret".
  681. key->set_type(Bindings::KeyType::Secret);
  682. // 6. Set the [[extractable]] internal slot of key to false.
  683. key->set_extractable(false);
  684. // 7. Let algorithm be a new KeyAlgorithm object.
  685. auto algorithm = KeyAlgorithm::create(m_realm);
  686. // 8. Set the name attribute of algorithm to "PBKDF2".
  687. algorithm->set_name("PBKDF2"_string);
  688. // 9. Set the [[algorithm]] internal slot of key to algorithm.
  689. key->set_algorithm(algorithm);
  690. // 10. Return key.
  691. return key;
  692. }
  693. WebIDL::ExceptionOr<JS::NonnullGCPtr<JS::ArrayBuffer>> SHA::digest(AlgorithmParams const& algorithm, ByteBuffer const& data)
  694. {
  695. auto& algorithm_name = algorithm.name;
  696. ::Crypto::Hash::HashKind hash_kind;
  697. if (algorithm_name.equals_ignoring_ascii_case("SHA-1"sv)) {
  698. hash_kind = ::Crypto::Hash::HashKind::SHA1;
  699. } else if (algorithm_name.equals_ignoring_ascii_case("SHA-256"sv)) {
  700. hash_kind = ::Crypto::Hash::HashKind::SHA256;
  701. } else if (algorithm_name.equals_ignoring_ascii_case("SHA-384"sv)) {
  702. hash_kind = ::Crypto::Hash::HashKind::SHA384;
  703. } else if (algorithm_name.equals_ignoring_ascii_case("SHA-512"sv)) {
  704. hash_kind = ::Crypto::Hash::HashKind::SHA512;
  705. } else {
  706. return WebIDL::NotSupportedError::create(m_realm, MUST(String::formatted("Invalid hash function '{}'", algorithm_name)));
  707. }
  708. ::Crypto::Hash::Manager hash { hash_kind };
  709. hash.update(data);
  710. auto digest = hash.digest();
  711. auto result_buffer = ByteBuffer::copy(digest.immutable_data(), hash.digest_size());
  712. if (result_buffer.is_error())
  713. return WebIDL::OperationError::create(m_realm, "Failed to create result buffer"_fly_string);
  714. return JS::ArrayBuffer::create(m_realm, result_buffer.release_value());
  715. }
  716. }