CryptoAlgorithms.cpp 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298
  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. AlgorithmParams::~AlgorithmParams() = default;
  50. JS::ThrowCompletionOr<NonnullOwnPtr<AlgorithmParams>> AlgorithmParams::from_value(JS::VM& vm, JS::Value value)
  51. {
  52. auto& object = value.as_object();
  53. auto name = TRY(object.get("name"));
  54. auto name_string = TRY(name.to_string(vm));
  55. return adopt_own(*new AlgorithmParams { name_string });
  56. }
  57. PBKDF2Params::~PBKDF2Params() = default;
  58. JS::ThrowCompletionOr<NonnullOwnPtr<AlgorithmParams>> PBKDF2Params::from_value(JS::VM& vm, JS::Value value)
  59. {
  60. auto& realm = *vm.current_realm();
  61. auto& object = value.as_object();
  62. auto name_value = TRY(object.get("name"));
  63. auto name = TRY(name_value.to_string(vm));
  64. auto salt_value = TRY(object.get("salt"));
  65. JS::Handle<WebIDL::BufferSource> salt;
  66. 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())))
  67. return vm.throw_completion<JS::TypeError>(JS::ErrorType::NotAnObjectOfType, "BufferSource");
  68. salt = JS::make_handle(vm.heap().allocate<WebIDL::BufferSource>(realm, salt_value.as_object()));
  69. auto iterations_value = TRY(object.get("iterations"));
  70. auto iterations = TRY(iterations_value.to_u32(vm));
  71. auto hash_value = TRY(object.get("hash"));
  72. auto hash = Variant<Empty, HashAlgorithmIdentifier> { Empty {} };
  73. if (hash_value.is_string()) {
  74. auto hash_string = TRY(hash_value.to_string(vm));
  75. hash = HashAlgorithmIdentifier { hash_string };
  76. } else {
  77. auto hash_object = TRY(hash_value.to_object(vm));
  78. hash = HashAlgorithmIdentifier { hash_object };
  79. }
  80. return adopt_own<AlgorithmParams>(*new PBKDF2Params { name, salt, iterations, hash.downcast<HashAlgorithmIdentifier>() });
  81. }
  82. RsaKeyGenParams::~RsaKeyGenParams() = default;
  83. JS::ThrowCompletionOr<NonnullOwnPtr<AlgorithmParams>> RsaKeyGenParams::from_value(JS::VM& vm, JS::Value value)
  84. {
  85. auto& object = value.as_object();
  86. auto name_value = TRY(object.get("name"));
  87. auto name = TRY(name_value.to_string(vm));
  88. auto modulus_length_value = TRY(object.get("modulusLength"));
  89. auto modulus_length = TRY(modulus_length_value.to_u32(vm));
  90. auto public_exponent_value = TRY(object.get("publicExponent"));
  91. JS::GCPtr<JS::Uint8Array> public_exponent;
  92. if (!public_exponent_value.is_object() || !is<JS::Uint8Array>(public_exponent_value.as_object()))
  93. return vm.throw_completion<JS::TypeError>(JS::ErrorType::NotAnObjectOfType, "Uint8Array");
  94. public_exponent = static_cast<JS::Uint8Array&>(public_exponent_value.as_object());
  95. return adopt_own<AlgorithmParams>(*new RsaKeyGenParams { name, modulus_length, big_integer_from_api_big_integer(public_exponent) });
  96. }
  97. RsaHashedKeyGenParams::~RsaHashedKeyGenParams() = default;
  98. JS::ThrowCompletionOr<NonnullOwnPtr<AlgorithmParams>> RsaHashedKeyGenParams::from_value(JS::VM& vm, JS::Value value)
  99. {
  100. auto& object = value.as_object();
  101. auto name_value = TRY(object.get("name"));
  102. auto name = TRY(name_value.to_string(vm));
  103. auto modulus_length_value = TRY(object.get("modulusLength"));
  104. auto modulus_length = TRY(modulus_length_value.to_u32(vm));
  105. auto public_exponent_value = TRY(object.get("publicExponent"));
  106. JS::GCPtr<JS::Uint8Array> public_exponent;
  107. if (!public_exponent_value.is_object() || !is<JS::Uint8Array>(public_exponent_value.as_object()))
  108. return vm.throw_completion<JS::TypeError>(JS::ErrorType::NotAnObjectOfType, "Uint8Array");
  109. public_exponent = static_cast<JS::Uint8Array&>(public_exponent_value.as_object());
  110. auto hash_value = TRY(object.get("hash"));
  111. auto hash = Variant<Empty, HashAlgorithmIdentifier> { Empty {} };
  112. if (hash_value.is_string()) {
  113. auto hash_string = TRY(hash_value.to_string(vm));
  114. hash = HashAlgorithmIdentifier { hash_string };
  115. } else {
  116. auto hash_object = TRY(hash_value.to_object(vm));
  117. hash = HashAlgorithmIdentifier { hash_object };
  118. }
  119. return adopt_own<AlgorithmParams>(*new RsaHashedKeyGenParams { name, modulus_length, big_integer_from_api_big_integer(public_exponent), hash.get<HashAlgorithmIdentifier>() });
  120. }
  121. // https://w3c.github.io/webcrypto/#rsa-oaep-operations
  122. WebIDL::ExceptionOr<Variant<JS::NonnullGCPtr<CryptoKey>, JS::NonnullGCPtr<CryptoKeyPair>>> RSAOAEP::generate_key(AlgorithmParams const& params, bool extractable, Vector<Bindings::KeyUsage> const& key_usages)
  123. {
  124. // 1. If usages contains an entry which is not "encrypt", "decrypt", "wrapKey" or "unwrapKey", then throw a SyntaxError.
  125. for (auto const& usage : key_usages) {
  126. if (usage != Bindings::KeyUsage::Encrypt && usage != Bindings::KeyUsage::Decrypt && usage != Bindings::KeyUsage::Wrapkey && usage != Bindings::KeyUsage::Unwrapkey) {
  127. return WebIDL::SyntaxError::create(m_realm, MUST(String::formatted("Invalid key usage '{}'", idl_enum_to_string(usage))));
  128. }
  129. }
  130. // 2. Generate an RSA key pair, as defined in [RFC3447], with RSA modulus length equal to the modulusLength member of normalizedAlgorithm
  131. // and RSA public exponent equal to the publicExponent member of normalizedAlgorithm.
  132. // 3. If performing the operation results in an error, then throw an OperationError.
  133. auto const& normalized_algorithm = static_cast<RsaHashedKeyGenParams const&>(params);
  134. auto key_pair = ::Crypto::PK::RSA::generate_key_pair(normalized_algorithm.modulus_length, normalized_algorithm.public_exponent);
  135. // 4. Let algorithm be a new RsaHashedKeyAlgorithm object.
  136. auto algorithm = RsaHashedKeyAlgorithm::create(m_realm);
  137. // 5. Set the name attribute of algorithm to "RSA-OAEP".
  138. algorithm->set_name("RSA-OAEP"_string);
  139. // 6. Set the modulusLength attribute of algorithm to equal the modulusLength member of normalizedAlgorithm.
  140. algorithm->set_modulus_length(normalized_algorithm.modulus_length);
  141. // 7. Set the publicExponent attribute of algorithm to equal the publicExponent member of normalizedAlgorithm.
  142. TRY(algorithm->set_public_exponent(normalized_algorithm.public_exponent));
  143. // 8. Set the hash attribute of algorithm to equal the hash member of normalizedAlgorithm.
  144. algorithm->set_hash(normalized_algorithm.hash);
  145. // 9. Let publicKey be a new CryptoKey representing the public key of the generated key pair.
  146. auto public_key = CryptoKey::create(m_realm, CryptoKey::InternalKeyData { key_pair.public_key });
  147. // 10. Set the [[type]] internal slot of publicKey to "public"
  148. public_key->set_type(Bindings::KeyType::Public);
  149. // 11. Set the [[algorithm]] internal slot of publicKey to algorithm.
  150. public_key->set_algorithm(algorithm);
  151. // 12. Set the [[extractable]] internal slot of publicKey to true.
  152. public_key->set_extractable(true);
  153. // 13. Set the [[usages]] internal slot of publicKey to be the usage intersection of usages and [ "encrypt", "wrapKey" ].
  154. public_key->set_usages(usage_intersection(key_usages, { { Bindings::KeyUsage::Encrypt, Bindings::KeyUsage::Wrapkey } }));
  155. // 14. Let privateKey be a new CryptoKey representing the private key of the generated key pair.
  156. auto private_key = CryptoKey::create(m_realm, CryptoKey::InternalKeyData { key_pair.private_key });
  157. // 15. Set the [[type]] internal slot of privateKey to "private"
  158. private_key->set_type(Bindings::KeyType::Private);
  159. // 16. Set the [[algorithm]] internal slot of privateKey to algorithm.
  160. private_key->set_algorithm(algorithm);
  161. // 17. Set the [[extractable]] internal slot of privateKey to extractable.
  162. private_key->set_extractable(extractable);
  163. // 18. Set the [[usages]] internal slot of privateKey to be the usage intersection of usages and [ "decrypt", "unwrapKey" ].
  164. private_key->set_usages(usage_intersection(key_usages, { { Bindings::KeyUsage::Decrypt, Bindings::KeyUsage::Unwrapkey } }));
  165. // 19. Let result be a new CryptoKeyPair dictionary.
  166. // 20. Set the publicKey attribute of result to be publicKey.
  167. // 21. Set the privateKey attribute of result to be privateKey.
  168. // 22. Return the result of converting result to an ECMAScript Object, as defined by [WebIDL].
  169. return Variant<JS::NonnullGCPtr<CryptoKey>, JS::NonnullGCPtr<CryptoKeyPair>> { CryptoKeyPair::create(m_realm, public_key, private_key) };
  170. }
  171. 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)
  172. {
  173. // 1. If format is not "raw", throw a NotSupportedError
  174. if (format != Bindings::KeyFormat::Raw) {
  175. return WebIDL::NotSupportedError::create(m_realm, "Only raw format is supported"_fly_string);
  176. }
  177. // 2. If usages contains a value that is not "deriveKey" or "deriveBits", then throw a SyntaxError.
  178. for (auto& usage : key_usages) {
  179. if (usage != Bindings::KeyUsage::Derivekey && usage != Bindings::KeyUsage::Derivebits) {
  180. return WebIDL::SyntaxError::create(m_realm, MUST(String::formatted("Invalid key usage '{}'", idl_enum_to_string(usage))));
  181. }
  182. }
  183. // 3. If extractable is not false, then throw a SyntaxError.
  184. if (extractable)
  185. return WebIDL::SyntaxError::create(m_realm, "extractable must be false"_fly_string);
  186. // 4. Let key be a new CryptoKey representing keyData.
  187. auto key = CryptoKey::create(m_realm, move(key_data));
  188. // 5. Set the [[type]] internal slot of key to "secret".
  189. key->set_type(Bindings::KeyType::Secret);
  190. // 6. Set the [[extractable]] internal slot of key to false.
  191. key->set_extractable(false);
  192. // 7. Let algorithm be a new KeyAlgorithm object.
  193. auto algorithm = KeyAlgorithm::create(m_realm);
  194. // 8. Set the name attribute of algorithm to "PBKDF2".
  195. algorithm->set_name("PBKDF2"_string);
  196. // 9. Set the [[algorithm]] internal slot of key to algorithm.
  197. key->set_algorithm(algorithm);
  198. // 10. Return key.
  199. return key;
  200. }
  201. WebIDL::ExceptionOr<JS::NonnullGCPtr<JS::ArrayBuffer>> SHA::digest(AlgorithmParams const& algorithm, ByteBuffer const& data)
  202. {
  203. auto& algorithm_name = algorithm.name;
  204. ::Crypto::Hash::HashKind hash_kind;
  205. if (algorithm_name.equals_ignoring_ascii_case("SHA-1"sv)) {
  206. hash_kind = ::Crypto::Hash::HashKind::SHA1;
  207. } else if (algorithm_name.equals_ignoring_ascii_case("SHA-256"sv)) {
  208. hash_kind = ::Crypto::Hash::HashKind::SHA256;
  209. } else if (algorithm_name.equals_ignoring_ascii_case("SHA-384"sv)) {
  210. hash_kind = ::Crypto::Hash::HashKind::SHA384;
  211. } else if (algorithm_name.equals_ignoring_ascii_case("SHA-512"sv)) {
  212. hash_kind = ::Crypto::Hash::HashKind::SHA512;
  213. } else {
  214. return WebIDL::NotSupportedError::create(m_realm, MUST(String::formatted("Invalid hash function '{}'", algorithm_name)));
  215. }
  216. ::Crypto::Hash::Manager hash { hash_kind };
  217. hash.update(data);
  218. auto digest = hash.digest();
  219. auto result_buffer = ByteBuffer::copy(digest.immutable_data(), hash.digest_size());
  220. if (result_buffer.is_error())
  221. return WebIDL::OperationError::create(m_realm, "Failed to create result buffer"_fly_string);
  222. return JS::ArrayBuffer::create(m_realm, result_buffer.release_value());
  223. }
  224. }