Skip to main content

随机生成密码

随机生成密码

在浏览器环境中,你可以使用 window.crypto 提供的 getRandomValues 方法来生成高质量的随机数,并结合字符集生成复杂的随机密码。以下是一个完整的示例代码:

function generateRandomPassword(length) {
const charset = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789!@#$%^&*()_+~`|}{[]:;?><,./-=';
const charsetLength = charset.length;
const array = new Uint8Array(length);
window.crypto.getRandomValues(array);

return Array.from(array, (byte) => charset[byte % charsetLength]).join('');
}

// 生成一个 16 位的随机密码
const password = generateRandomPassword(16);
console.log('Generated password:', password);

解释

  1. 字符集

    • charset 包含了大小写字母、数字和特殊字符,这些字符将用于生成密码。
  2. 生成随机数

    • 使用 window.crypto.getRandomValues(array) 生成高质量的随机数。这是一个安全的随机数生成方法,适用于现代浏览器。
  3. 转换为密码

    • 使用 Array.from 将生成的随机数数组转换为密码字符串。每个随机数用于从字符集中选择一个字符。

示例输出

运行上述代码,你将会看到类似以下的输出:

Generated password: aB3!kL9@zX2$wQ1#

确保兼容性

这个方法在现代浏览器中是通用的,但如果你需要支持非常旧的浏览器,可能需要考虑其他方法。对于大多数现代应用,这个方法已经足够安全和高效。

进一步定制

你可以根据需求调整字符集或密码长度。例如,如果你想要一个更长的密码或需要特定的字符集,只需修改 charsetlength 参数:

const customCharset = 'abcdef0123456789'; // 例如,只使用小写字母和数字
const customLength = 20; // 例如,生成一个 20 位的密码

const customPassword = generateRandomPassword(customLength, customCharset);
console.log('Custom generated password:', customPassword);

通过这些调整,你可以生成满足特定安全需求的复杂密码。

计算密码复杂度

https://www.npmjs.com/package/fast-password-entropy