Generating an array of random numbers using web_sys

Viewed 256

I am trying to populate a vector with random numbers using web_sys crate

Something like this :

extern crate web_sys;

use web_sys::Crypto;    

// ...

fn main() {
    // ...

    let mut arry = [0u8; 128];
    let crypto = Crypto::new();
    crypto.get_random_values_with_u8_array(&mut arry)

    // ...
}

The Crypto struct however does not implement new methods and docs do not mention the fields needed to instantiate the the struct.

I've included Crypto as feature in my Cargo.toml file:

[dependencies.web-sys]
 version = "0.3"
 features = [
   "Crypto"
 ]

Here's the relevant docs page:

https://docs.rs/web-sys/0.3.35/i686-unknown-linux-gnu/web_sys/struct.Crypto.html

Does anyone have experience using this?

1 Answers

Thanks Masklinn's comment, I was able to get this to work by getting an instance of Window and calling crypto on it.

let mut rand_arry = [0u8; 128];
let window_instance = web_sys::window().unwrap();
let crypto = window_instance.crypto.unwrap();
crypto.get_random_values_with_u8_array(&mut rand_arry).unwrap();

Make sure to declare Crypto and Window as web-sys features

[dependencies.web-sys]
version = "0.3"
features = [
    "Window",
    "Crypto"
]  
Related