Javascript生成具有特定字母数量的随机密码

2022-01-22 00:00:00 random passwords security javascript

我想在网页中,在客户端,用 Javascript 生成密码.密码应该使用字母和数字,也许是一些符号.如何安全地在 Javascript 中生成密码?

I want to generate a password in a web page, on the client side, in Javascript. The password should use letters and numbers, perhaps some symbols. How can I generate a password in Javascript securely?

推荐答案

由于密码需要不可预测,因此需要由种子良好的加密 PRNG 生成.Math.random 通常不安全.

Since a password needs to be unpredictable, it needs to be generated by a well seeded crypto PRNG. Math.random is usually not secure.

现代浏览器(至少是当前版本的 Firefox 和 Chrome)支持生成安全随机值的 window.crypto.getRandomValues.

Modern browsers (At least the current versions of Firefox and Chrome) support window.crypto.getRandomValues which generates secure random values.

基于 Presto 的 Opera 不支持它,但它的 Math.random 是安全的.但是既然 Opera 已经死了,那么回退应该不再是必要的了.

Presto based Opera doesn't support it, but its Math.random is secure. But since Opera has died, the fallback shouldn't be necessary anymore.

function randomString(length)
{
    var charset = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
    var i;
    var result = "";
    var isOpera = Object.prototype.toString.call(window.opera) == '[object Opera]';
    if(window.crypto && window.crypto.getRandomValues)
    {
        values = new Uint32Array(length);
        window.crypto.getRandomValues(values);
        for(i=0; i<length; i++)
        {
            result += charset[values[i] % charset.length];
        }
        return result;
    }
    else if(isOpera)//Opera's Math.random is secure, see http://lists.w3.org/Archives/Public/public-webcrypto/2013Jan/0063.html
    {
        for(i=0; i<length; i++)
        {
            result += charset[Math.floor(Math.random()*charset.length)];
        }
        return result;
    }
    else throw new Error("Your browser sucks and can't generate secure random numbers");
}

alert(randomString(10))

http://jsfiddle.net/ebbpa/

相关文章