Skip to content

Instantly share code, notes, and snippets.

@najtin
Created December 28, 2021 17:24
Show Gist options
  • Save najtin/24a97d73ea7e6b5a927cefdc90776cec to your computer and use it in GitHub Desktop.
Save najtin/24a97d73ea7e6b5a927cefdc90776cec to your computer and use it in GitHub Desktop.
generate a random string in rust wasm
use rand_chacha::{self, rand_core::SeedableRng, rand_core::RngCore};
use web_sys;
let mut seed = [0u8; 8];
web_sys::window().unwrap().crypto().unwrap().get_random_values_with_u8_array(&mut seed).unwrap();
let mut s = 0u64;
for i in seed {
s |= i as u64;
s = s<<8;
}
const CHARSET: &[u8] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789)(*&^%$#@!~";
let mut rng = rand_chacha::ChaCha20Rng::seed_from_u64(s);
let cnonce: String = (0..64).map(|_| {
let idx = rng.next_u32() as usize % CHARSET.len();
CHARSET[idx] as char
}).collect();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment