0

生成随机数的Math.floor(Math.random() * 100)or方法在密码学上不是最安全的。Math.ceil(Math.random() * 100)我想在随机密码应用程序中使用此方法,我正在尝试使用 window.crypto 属性。这是我设置的,但它似乎返回一个空值,我不确定我做错了什么。

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}`);

4

1 回答 1

1

您可以生成Uint32Array与列表长度相同的a chars。然后循环它们以获得随机值。通过使用%我们可以确保我们永远不会超过给定的长度(余数运算符

let chars = '0123456789abcdefghijklmnopqrstuvwxyz!@#$%^&*()ABCDEFGHIJKLMNOPQRSTUVWXYZ';
let pwordLength = 12;
let password = '';

const array = new Uint32Array(chars.length);
window.crypto.getRandomValues(array);

for (let i = 0; i < pwordLength; i++) {
  password += chars[array[i] % chars.length];
}


console.log(`Password is ${password}`);

于 2021-08-02T07:01:15.510 回答