Crypto.cpp 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243
  1. /*
  2. * Copyright (c) 2021, Idan Horowitz <idan.horowitz@serenityos.org>
  3. *
  4. * SPDX-License-Identifier: BSD-2-Clause
  5. */
  6. #include <AK/Random.h>
  7. #include <LibJS/Runtime/TypedArray.h>
  8. #include <LibWeb/Bindings/Wrapper.h>
  9. #include <LibWeb/Crypto/Crypto.h>
  10. #include <LibWeb/Crypto/SubtleCrypto.h>
  11. namespace Web::Crypto {
  12. Crypto::Crypto()
  13. : m_subtle(SubtleCrypto::create())
  14. {
  15. }
  16. DOM::ExceptionOr<JS::Value> Crypto::get_random_values(JS::Value array) const
  17. {
  18. // 1. If array is not an Int8Array, Uint8Array, Uint8ClampedArray, Int16Array, Uint16Array, Int32Array, Uint32Array, BigInt64Array, or BigUint64Array, then throw a TypeMismatchError and terminate the algorithm.
  19. if (!array.is_object() || !(is<JS::Int8Array>(array.as_object()) || is<JS::Uint8Array>(array.as_object()) || is<JS::Uint8ClampedArray>(array.as_object()) || is<JS::Int16Array>(array.as_object()) || is<JS::Uint16Array>(array.as_object()) || is<JS::Int32Array>(array.as_object()) || is<JS::Uint32Array>(array.as_object()) || is<JS::BigInt64Array>(array.as_object()) || is<JS::BigUint64Array>(array.as_object())))
  20. return DOM::TypeMismatchError::create("array must be one of Int8Array, Uint8Array, Uint8ClampedArray, Int16Array, Uint16Array, Int32Array, Uint32Array, BigInt64Array, or BigUint64Array");
  21. auto& typed_array = static_cast<JS::TypedArrayBase&>(array.as_object());
  22. // 2. If the byteLength of array is greater than 65536, throw a QuotaExceededError and terminate the algorithm.
  23. if (typed_array.byte_length() > 65536)
  24. return DOM::QuotaExceededError::create("array's byteLength may not be greater than 65536");
  25. // IMPLEMENTATION DEFINED: If the viewed array buffer is detached, throw a InvalidStateError and terminate the algorithm.
  26. if (typed_array.viewed_array_buffer()->is_detached())
  27. return DOM::InvalidStateError::create("array is detached");
  28. // FIXME: Handle SharedArrayBuffers
  29. // 3. Overwrite all elements of array with cryptographically strong random values of the appropriate type.
  30. fill_with_random(typed_array.viewed_array_buffer()->buffer().data(), typed_array.viewed_array_buffer()->buffer().size());
  31. // 4. Return array.
  32. return array;
  33. }
  34. }