| 1 |
//! Implementation for WASM based on Web and Node.js |
| 2 |
use crate::Error; |
| 3 |
use core::mem::MaybeUninit; |
| 4 |
|
| 5 |
pub use crate::util::{inner_u32, inner_u64}; |
| 6 |
|
| 7 |
#[cfg(not(all(target_arch = "wasm32", any(target_os = "unknown", target_os = "none"))))] |
| 8 |
compile_error!("`wasm_js` backend can be enabled only for OS-less WASM targets!"); |
| 9 |
|
| 10 |
use wasm_bindgen::{prelude::wasm_bindgen, JsValue}; |
| 11 |
|
| 12 |
// Maximum buffer size allowed in `Crypto.getRandomValuesSize` is 65536 bytes. |
| 13 |
// See https://developer.mozilla.org/en-US/docs/Web/API/Crypto/getRandomValues |
| 14 |
const MAX_BUFFER_SIZE: usize = 65536; |
| 15 |
|
| 16 |
#[cfg(not(target_feature = "atomics"))] |
| 17 |
#[inline] |
| 18 |
pub fn fill_inner(dest: &mut [MaybeUninit<u8>]) -> Result<(), Error> { |
| 19 |
for chunk in dest.chunks_mut(MAX_BUFFER_SIZE) { |
| 20 |
if get_random_values(chunk).is_err() { |
| 21 |
return Err(Error::WEB_CRYPTO); |
| 22 |
} |
| 23 |
} |
| 24 |
Ok(()) |
| 25 |
} |
| 26 |
|
| 27 |
#[cfg(target_feature = "atomics")] |
| 28 |
pub fn fill_inner(dest: &mut [MaybeUninit<u8>]) -> Result<(), Error> { |
| 29 |
// getRandomValues does not work with all types of WASM memory, |
| 30 |
// so we initially write to browser memory to avoid exceptions. |
| 31 |
let buf_len = usize::min(dest.len(), MAX_BUFFER_SIZE); |
| 32 |
let buf_len_u32 = buf_len |
| 33 |
.try_into() |
| 34 |
.expect("buffer length is bounded by MAX_BUFFER_SIZE"); |
| 35 |
let buf = js_sys::Uint8Array::new_with_length(buf_len_u32); |
| 36 |
for chunk in dest.chunks_mut(buf_len) { |
| 37 |
let chunk_len = chunk |
| 38 |
.len() |
| 39 |
.try_into() |
| 40 |
.expect("chunk length is bounded by MAX_BUFFER_SIZE"); |
| 41 |
// The chunk can be smaller than buf's length, so we call to |
| 42 |
// JS to create a smaller view of buf without allocation. |
| 43 |
let sub_buf = if chunk_len == buf_len_u32 { |
| 44 |
&buf |
| 45 |
} else { |
| 46 |
&buf.subarray(0, chunk_len) |
| 47 |
}; |
| 48 |
|
| 49 |
if get_random_values(sub_buf).is_err() { |
| 50 |
return Err(Error::WEB_CRYPTO); |
| 51 |
} |
| 52 |
|
| 53 |
sub_buf.copy_to_uninit(chunk); |
| 54 |
} |
| 55 |
Ok(()) |
| 56 |
} |
| 57 |
|
| 58 |
#[wasm_bindgen] |
| 59 |
extern "C" { |
| 60 |
// Crypto.getRandomValues() |
| 61 |
#[cfg(not(target_feature = "atomics"))] |
| 62 |
#[wasm_bindgen(js_namespace = ["globalThis", "crypto"], js_name = getRandomValues, catch)] |
| 63 |
fn get_random_values(buf: &mut [MaybeUninit<u8>]) -> Result<(), JsValue>; |
| 64 |
#[cfg(target_feature = "atomics")] |
| 65 |
#[wasm_bindgen(js_namespace = ["globalThis", "crypto"], js_name = getRandomValues, catch)] |
| 66 |
fn get_random_values(buf: &js_sys::Uint8Array) -> Result<(), JsValue>; |
| 67 |
} |
| 68 |
|
| 69 |
impl Error { |
| 70 |
/// The environment does not support the Web Crypto API. |
| 71 |
pub(crate) const WEB_CRYPTO: Error = Self::new_internal(10); |
| 72 |
} |