The Math.floor(Math.random() * 100) or Math.ceil(Math.random() * 100) method of generating a random number isn't the most cryptographically secure. I want to use this method in a random Password application, I'm trying to use the window.crypto property. Here's what I have set up, but it seems to return an empty value and I'm not sure what I'm doing wrong.
const array = new Uint32Array(1);
window.crypto.getRandomValues(array);
let chars = '0123456789abcdefghijklmnopqrstuvwxyz!@#$%^&*()ABCDEFGHIJKLMNOPQRSTUVWXYZ';
let pwordLength = 12;
let password = '';
for (let i = 0; i <= pwordLength; i++) {
let randomNumber = array * chars.length;
password += chars.substring(randomNumber, randomNumber + 1);
}
console.log(`Password is ${password}`);
You can generate a
Uint32Arraywith the same length as yourcharslist. Then loop over them to get a random value. By using%we can ensure we never exceed the given length (remainder operator)