Skip to content

Commit

Permalink
LibWeb: Implement KeyAlgorithms for big-endian
Browse files Browse the repository at this point in the history
  • Loading branch information
sideeffect42 authored and ADKaster committed Jul 10, 2024
1 parent 81a0aa5 commit 90a2dcf
Showing 1 changed file with 13 additions and 10 deletions.
23 changes: 13 additions & 10 deletions Userland/Libraries/LibWeb/Crypto/KeyAlgorithms.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -90,26 +90,29 @@ void RsaKeyAlgorithm::visit_edges(Visitor& visitor)

WebIDL::ExceptionOr<void> RsaKeyAlgorithm::set_public_exponent(::Crypto::UnsignedBigInteger exponent)
{
static_assert(AK::HostIsLittleEndian, "This code assumes a little endian host");

auto& realm = this->realm();
auto& vm = this->vm();

auto bytes = TRY_OR_THROW_OOM(vm, ByteBuffer::create_uninitialized(exponent.trimmed_byte_length()));

bool const remove_leading_zeroes = true;
auto data_size = exponent.export_data(bytes.span(), remove_leading_zeroes);
auto data_slice = bytes.bytes().slice(bytes.size() - data_size, data_size);
auto data_slice_be = bytes.bytes().slice(bytes.size() - data_size, data_size);

// The BigInteger typedef from the WebCrypto spec requires the bytes in the Uint8Array be ordered in Big Endian

Vector<u8, 32> byte_swapped_data;
byte_swapped_data.ensure_capacity(data_size);
for (size_t i = 0; i < data_size; ++i)
byte_swapped_data.append(data_slice[data_size - i - 1]);

m_public_exponent = TRY(JS::Uint8Array::create(realm, byte_swapped_data.size()));
m_public_exponent->viewed_array_buffer()->buffer().overwrite(0, byte_swapped_data.data(), byte_swapped_data.size());
if constexpr (AK::HostIsLittleEndian) {
Vector<u8, 32> data_slice_le;
data_slice_le.ensure_capacity(data_size);
for (size_t i = 0; i < data_size; ++i) {
data_slice_le.append(data_slice_be[data_size - i - 1]);
}
m_public_exponent = TRY(JS::Uint8Array::create(realm, data_slice_le.size()));
m_public_exponent->viewed_array_buffer()->buffer().overwrite(0, data_slice_le.data(), data_slice_le.size());
} else {
m_public_exponent = TRY(JS::Uint8Array::create(realm, data_slice_be.size()));
m_public_exponent->viewed_array_buffer()->buffer().overwrite(0, data_slice_be.data(), data_slice_be.size());
}

return {};
}
Expand Down

0 comments on commit 90a2dcf

Please sign in to comment.