CryptoAlgorithms.cpp 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290
  1. /*
  2. * Copyright (c) 2024, Andrew Kaster <akaster@serenityos.org>
  3. *
  4. * SPDX-License-Identifier: BSD-2-Clause
  5. */
  6. #include <AK/QuickSort.h>
  7. #include <LibCrypto/Hash/HashManager.h>
  8. #include <LibCrypto/PK/RSA.h>
  9. #include <LibJS/Runtime/ArrayBuffer.h>
  10. #include <LibJS/Runtime/DataView.h>
  11. #include <LibJS/Runtime/TypedArray.h>
  12. #include <LibWeb/Crypto/CryptoAlgorithms.h>
  13. #include <LibWeb/Crypto/KeyAlgorithms.h>
  14. namespace Web::Crypto {
  15. // https://w3c.github.io/webcrypto/#concept-usage-intersection
  16. static Vector<Bindings::KeyUsage> usage_intersection(ReadonlySpan<Bindings::KeyUsage> a, ReadonlySpan<Bindings::KeyUsage> b)
  17. {
  18. Vector<Bindings::KeyUsage> result;
  19. for (auto const& usage : a) {
  20. if (b.contains_slow(usage))
  21. result.append(usage);
  22. }
  23. quick_sort(result);
  24. return result;
  25. }
  26. // Out of line to ensure this class has a key function
  27. AlgorithmMethods::~AlgorithmMethods() = default;
  28. // https://w3c.github.io/webcrypto/#big-integer
  29. static ::Crypto::UnsignedBigInteger big_integer_from_api_big_integer(JS::GCPtr<JS::Uint8Array> const& big_integer)
  30. {
  31. static_assert(AK::HostIsLittleEndian, "This method needs special treatment for BE");
  32. // The BigInteger typedef is a Uint8Array that holds an arbitrary magnitude unsigned integer
  33. // **in big-endian order**. Values read from the API SHALL have minimal typed array length
  34. // (that is, at most 7 leading zero bits, except the value 0 which shall have length 8 bits).
  35. // The API SHALL accept values with any number of leading zero bits, including the empty array, which represents zero.
  36. auto const& buffer = big_integer->viewed_array_buffer()->buffer();
  37. ::Crypto::UnsignedBigInteger result(0);
  38. if (buffer.size() > 0) {
  39. // We need to reverse the buffer to get it into little-endian order
  40. Vector<u8, 32> reversed_buffer;
  41. reversed_buffer.resize(buffer.size());
  42. for (size_t i = 0; i < buffer.size(); ++i) {
  43. reversed_buffer[buffer.size() - i - 1] = buffer[i];
  44. }
  45. result = ::Crypto::UnsignedBigInteger::import_data(reversed_buffer.data(), reversed_buffer.size());
  46. }
  47. return result;
  48. }
  49. JS::ThrowCompletionOr<NonnullOwnPtr<AlgorithmParams>> AlgorithmParams::from_value(JS::VM& vm, JS::Value value)
  50. {
  51. auto& object = value.as_object();
  52. auto name = TRY(object.get("name"));
  53. auto name_string = TRY(name.to_string(vm));
  54. return adopt_own(*new AlgorithmParams { .name = name_string });
  55. }
  56. JS::ThrowCompletionOr<NonnullOwnPtr<AlgorithmParams>> PBKDF2Params::from_value(JS::VM& vm, JS::Value value)
  57. {
  58. auto& realm = *vm.current_realm();
  59. auto& object = value.as_object();
  60. auto name_value = TRY(object.get("name"));
  61. auto name = TRY(name_value.to_string(vm));
  62. auto salt_value = TRY(object.get("salt"));
  63. JS::Handle<WebIDL::BufferSource> salt;
  64. 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())))
  65. return vm.throw_completion<JS::TypeError>(JS::ErrorType::NotAnObjectOfType, "BufferSource");
  66. salt = JS::make_handle(vm.heap().allocate<WebIDL::BufferSource>(realm, salt_value.as_object()));
  67. auto iterations_value = TRY(object.get("iterations"));
  68. auto iterations = TRY(iterations_value.to_u32(vm));
  69. auto hash_value = TRY(object.get("hash"));
  70. auto hash = Variant<Empty, HashAlgorithmIdentifier> { Empty {} };
  71. if (hash_value.is_string()) {
  72. auto hash_string = TRY(hash_value.to_string(vm));
  73. hash = HashAlgorithmIdentifier { hash_string };
  74. } else {
  75. auto hash_object = TRY(hash_value.to_object(vm));
  76. hash = HashAlgorithmIdentifier { hash_object };
  77. }
  78. return adopt_own<AlgorithmParams>(*new PBKDF2Params { { name }, salt, iterations, hash.downcast<HashAlgorithmIdentifier>() });
  79. }
  80. JS::ThrowCompletionOr<NonnullOwnPtr<AlgorithmParams>> RsaKeyGenParams::from_value(JS::VM& vm, JS::Value value)
  81. {
  82. auto& object = value.as_object();
  83. auto name_value = TRY(object.get("name"));
  84. auto name = TRY(name_value.to_string(vm));
  85. auto modulus_length_value = TRY(object.get("modulusLength"));
  86. auto modulus_length = TRY(modulus_length_value.to_u32(vm));
  87. auto public_exponent_value = TRY(object.get("publicExponent"));
  88. JS::GCPtr<JS::Uint8Array> public_exponent;
  89. if (!public_exponent_value.is_object() || !is<JS::Uint8Array>(public_exponent_value.as_object()))
  90. return vm.throw_completion<JS::TypeError>(JS::ErrorType::NotAnObjectOfType, "Uint8Array");
  91. public_exponent = static_cast<JS::Uint8Array&>(public_exponent_value.as_object());
  92. return adopt_own<AlgorithmParams>(*new RsaKeyGenParams { { name }, modulus_length, big_integer_from_api_big_integer(public_exponent) });
  93. }
  94. JS::ThrowCompletionOr<NonnullOwnPtr<AlgorithmParams>> RsaHashedKeyGenParams::from_value(JS::VM& vm, JS::Value value)
  95. {
  96. auto& object = value.as_object();
  97. auto name_value = TRY(object.get("name"));
  98. auto name = TRY(name_value.to_string(vm));
  99. auto modulus_length_value = TRY(object.get("modulusLength"));
  100. auto modulus_length = TRY(modulus_length_value.to_u32(vm));
  101. auto public_exponent_value = TRY(object.get("publicExponent"));
  102. JS::GCPtr<JS::Uint8Array> public_exponent;
  103. if (!public_exponent_value.is_object() || !is<JS::Uint8Array>(public_exponent_value.as_object()))
  104. return vm.throw_completion<JS::TypeError>(JS::ErrorType::NotAnObjectOfType, "Uint8Array");
  105. public_exponent = static_cast<JS::Uint8Array&>(public_exponent_value.as_object());
  106. auto hash_value = TRY(object.get("hash"));
  107. auto hash = Variant<Empty, HashAlgorithmIdentifier> { Empty {} };
  108. if (hash_value.is_string()) {
  109. auto hash_string = TRY(hash_value.to_string(vm));
  110. hash = HashAlgorithmIdentifier { hash_string };
  111. } else {
  112. auto hash_object = TRY(hash_value.to_object(vm));
  113. hash = HashAlgorithmIdentifier { hash_object };
  114. }
  115. return adopt_own<AlgorithmParams>(*new RsaHashedKeyGenParams { { { name }, modulus_length, big_integer_from_api_big_integer(public_exponent) }, hash.get<HashAlgorithmIdentifier>() });
  116. }
  117. // https://w3c.github.io/webcrypto/#rsa-oaep-operations
  118. WebIDL::ExceptionOr<Variant<JS::NonnullGCPtr<CryptoKey>, JS::NonnullGCPtr<CryptoKeyPair>>> RSAOAEP::generate_key(AlgorithmParams const& params, bool extractable, Vector<Bindings::KeyUsage> const& key_usages)
  119. {
  120. // 1. If usages contains an entry which is not "encrypt", "decrypt", "wrapKey" or "unwrapKey", then throw a SyntaxError.
  121. for (auto const& usage : key_usages) {
  122. if (usage != Bindings::KeyUsage::Encrypt && usage != Bindings::KeyUsage::Decrypt && usage != Bindings::KeyUsage::Wrapkey && usage != Bindings::KeyUsage::Unwrapkey) {
  123. return WebIDL::SyntaxError::create(m_realm, MUST(String::formatted("Invalid key usage '{}'", idl_enum_to_string(usage))));
  124. }
  125. }
  126. // 2. Generate an RSA key pair, as defined in [RFC3447], with RSA modulus length equal to the modulusLength member of normalizedAlgorithm
  127. // and RSA public exponent equal to the publicExponent member of normalizedAlgorithm.
  128. // 3. If performing the operation results in an error, then throw an OperationError.
  129. auto const& normalized_algorithm = static_cast<RsaHashedKeyGenParams const&>(params);
  130. auto key_pair = ::Crypto::PK::RSA::generate_key_pair(normalized_algorithm.modulus_length, normalized_algorithm.public_exponent);
  131. // 4. Let algorithm be a new RsaHashedKeyAlgorithm object.
  132. auto algorithm = RsaHashedKeyAlgorithm::create(m_realm);
  133. // 5. Set the name attribute of algorithm to "RSA-OAEP".
  134. algorithm->set_name("RSA-OAEP"_string);
  135. // 6. Set the modulusLength attribute of algorithm to equal the modulusLength member of normalizedAlgorithm.
  136. algorithm->set_modulus_length(normalized_algorithm.modulus_length);
  137. // 7. Set the publicExponent attribute of algorithm to equal the publicExponent member of normalizedAlgorithm.
  138. TRY(algorithm->set_public_exponent(normalized_algorithm.public_exponent));
  139. // 8. Set the hash attribute of algorithm to equal the hash member of normalizedAlgorithm.
  140. algorithm->set_hash(normalized_algorithm.hash);
  141. // 9. Let publicKey be a new CryptoKey representing the public key of the generated key pair.
  142. auto public_key = CryptoKey::create(m_realm, CryptoKey::InternalKeyData { key_pair.public_key });
  143. // 10. Set the [[type]] internal slot of publicKey to "public"
  144. public_key->set_type(Bindings::KeyType::Public);
  145. // 11. Set the [[algorithm]] internal slot of publicKey to algorithm.
  146. public_key->set_algorithm(algorithm);
  147. // 12. Set the [[extractable]] internal slot of publicKey to true.
  148. public_key->set_extractable(true);
  149. // 13. Set the [[usages]] internal slot of publicKey to be the usage intersection of usages and [ "encrypt", "wrapKey" ].
  150. public_key->set_usages(usage_intersection(key_usages, { { Bindings::KeyUsage::Encrypt, Bindings::KeyUsage::Wrapkey } }));
  151. // 14. Let privateKey be a new CryptoKey representing the private key of the generated key pair.
  152. auto private_key = CryptoKey::create(m_realm, CryptoKey::InternalKeyData { key_pair.private_key });
  153. // 15. Set the [[type]] internal slot of privateKey to "private"
  154. private_key->set_type(Bindings::KeyType::Private);
  155. // 16. Set the [[algorithm]] internal slot of privateKey to algorithm.
  156. private_key->set_algorithm(algorithm);
  157. // 17. Set the [[extractable]] internal slot of privateKey to extractable.
  158. private_key->set_extractable(extractable);
  159. // 18. Set the [[usages]] internal slot of privateKey to be the usage intersection of usages and [ "decrypt", "unwrapKey" ].
  160. private_key->set_usages(usage_intersection(key_usages, { { Bindings::KeyUsage::Decrypt, Bindings::KeyUsage::Unwrapkey } }));
  161. // 19. Let result be a new CryptoKeyPair dictionary.
  162. // 20. Set the publicKey attribute of result to be publicKey.
  163. // 21. Set the privateKey attribute of result to be privateKey.
  164. // 22. Return the result of converting result to an ECMAScript Object, as defined by [WebIDL].
  165. return Variant<JS::NonnullGCPtr<CryptoKey>, JS::NonnullGCPtr<CryptoKeyPair>> { CryptoKeyPair::create(m_realm, public_key, private_key) };
  166. }
  167. 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)
  168. {
  169. // 1. If format is not "raw", throw a NotSupportedError
  170. if (format != Bindings::KeyFormat::Raw) {
  171. return WebIDL::NotSupportedError::create(m_realm, "Only raw format is supported"_fly_string);
  172. }
  173. // 2. If usages contains a value that is not "deriveKey" or "deriveBits", then throw a SyntaxError.
  174. for (auto& usage : key_usages) {
  175. if (usage != Bindings::KeyUsage::Derivekey && usage != Bindings::KeyUsage::Derivebits) {
  176. return WebIDL::SyntaxError::create(m_realm, MUST(String::formatted("Invalid key usage '{}'", idl_enum_to_string(usage))));
  177. }
  178. }
  179. // 3. If extractable is not false, then throw a SyntaxError.
  180. if (extractable)
  181. return WebIDL::SyntaxError::create(m_realm, "extractable must be false"_fly_string);
  182. // 4. Let key be a new CryptoKey representing keyData.
  183. auto key = CryptoKey::create(m_realm, move(key_data));
  184. // 5. Set the [[type]] internal slot of key to "secret".
  185. key->set_type(Bindings::KeyType::Secret);
  186. // 6. Set the [[extractable]] internal slot of key to false.
  187. key->set_extractable(false);
  188. // 7. Let algorithm be a new KeyAlgorithm object.
  189. auto algorithm = KeyAlgorithm::create(m_realm);
  190. // 8. Set the name attribute of algorithm to "PBKDF2".
  191. algorithm->set_name("PBKDF2"_string);
  192. // 9. Set the [[algorithm]] internal slot of key to algorithm.
  193. key->set_algorithm(algorithm);
  194. // 10. Return key.
  195. return key;
  196. }
  197. WebIDL::ExceptionOr<JS::NonnullGCPtr<JS::ArrayBuffer>> SHA::digest(AlgorithmParams const& algorithm, ByteBuffer const& data)
  198. {
  199. auto& algorithm_name = algorithm.name;
  200. ::Crypto::Hash::HashKind hash_kind;
  201. if (algorithm_name.equals_ignoring_ascii_case("SHA-1"sv)) {
  202. hash_kind = ::Crypto::Hash::HashKind::SHA1;
  203. } else if (algorithm_name.equals_ignoring_ascii_case("SHA-256"sv)) {
  204. hash_kind = ::Crypto::Hash::HashKind::SHA256;
  205. } else if (algorithm_name.equals_ignoring_ascii_case("SHA-384"sv)) {
  206. hash_kind = ::Crypto::Hash::HashKind::SHA384;
  207. } else if (algorithm_name.equals_ignoring_ascii_case("SHA-512"sv)) {
  208. hash_kind = ::Crypto::Hash::HashKind::SHA512;
  209. } else {
  210. return WebIDL::NotSupportedError::create(m_realm, MUST(String::formatted("Invalid hash function '{}'", algorithm_name)));
  211. }
  212. ::Crypto::Hash::Manager hash { hash_kind };
  213. hash.update(data);
  214. auto digest = hash.digest();
  215. auto result_buffer = ByteBuffer::copy(digest.immutable_data(), hash.digest_size());
  216. if (result_buffer.is_error())
  217. return WebIDL::OperationError::create(m_realm, "Failed to create result buffer"_fly_string);
  218. return JS::ArrayBuffer::create(m_realm, result_buffer.release_value());
  219. }
  220. }